diff --git a/.github/workflows/rust-integration-tests.yml b/.github/workflows/rust-integration-tests.yml index 0c573e0..10392e0 100644 --- a/.github/workflows/rust-integration-tests.yml +++ b/.github/workflows/rust-integration-tests.yml @@ -59,7 +59,7 @@ jobs: # The `rustls` feature swaps the TLS stack, so it needs its own lint and compile check. - name: Clippy with rustls - run: cargo clippy --no-default-features --features rustls -- -D warnings + run: cargo clippy --no-default-features --features rustls --all-targets -- -D warnings # The `zstd` feature is on by default, so the build without it needs its own check. - name: Clippy without zstd diff --git a/CHANGELOG.md b/CHANGELOG.md index b742e66..d6d3e59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to the Rust Apify API client are documented here. The format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to [Semantic Versioning](https://semver.org/). +## [0.18.0] - 2026-11-20 + +### Added +- `SetRecordOptions` is re-exported at the crate root. + +### Fixed +- `UserClient::get` no longer fails for a request authenticated with a proxy password. The API + answers it with only the reduced data Apify Proxy reads, without `id` and `username`. +- `client.user(id).get()` no longer fails for the public profile of another user, which has no `id`. + +### Changed +- Synced with Apify OpenAPI spec `v2-2026-11-18T151559Z` (`API_SPEC_VERSION`). It adds the reduced + proxy variant to the responses of `GET /v2/users/me` and `GET /v2/users/{userId}`, types the + schedule's `uiState` as nullable, and changes descriptions: single-tenant Server Actor runs + ignore the `requestId` of a charge, a charge is sent from the run itself with the token in + `APIFY_TOKEN`, and API tokens are shown only once. +- **Breaking:** `User::id` is `Option`, because the public profile and the reduced proxy + data have no `id`. +- Documented that only the run itself can metamorph, with its own token, on + `RunClient::metamorph` and `metamorph_raw`. +- Documented the other description changes on `RunChargeOptions`, `RunClient::charge`, and in the + docs. + ## [0.17.0] - 2026-11-10 ### Added diff --git a/Cargo.toml b/Cargo.toml index d2be488..8f39189 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apify-client" -version = "0.17.0" +version = "0.18.0" authors = ["Apify Technologies "] description = "Rust client for the Apify API (https://apify.com)." license = "Apache-2.0" diff --git a/README.md b/README.md index 1be575d..806784f 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ It provides a resource-oriented, async interface that follows the ```toml [dependencies] -apify-client = "0.17" +apify-client = "0.18" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } serde_json = "1" # for the `serde_json::Value` responses used in the Quick start ``` @@ -49,7 +49,7 @@ instead, disable the default features and name `rustls`. The `"zstd"` entry keep so drop it if you do not need it: ```toml -apify-client = { version = "0.17", default-features = false, features = ["rustls", "zstd"] } +apify-client = { version = "0.18", default-features = false, features = ["rustls", "zstd"] } ``` The `rustls` feature requires `rustls-webpki` 0.103.16 or newer and `webpki-roots` 1.0.10 or @@ -304,8 +304,8 @@ code snippets in this README and `docs/` as doctests (`cargo test --doc`). ## Examples -Runnable examples live in [`examples/`](examples). Each requires `APIFY_TOKEN` and can be -run with `cargo run --example `: +Runnable examples live in [`examples/`](examples). Each requires `APIFY_TOKEN`, and `APIFY_API_URL` optionally overrides the API URL +(default `https://api.apify.com/v2`). Run one with `cargo run --example `: - `run_store_actor` — run a Store Actor, wait, read its default dataset. - `storages` — create each storage type (dataset, key-value store, request queue), write and read back. diff --git a/docs/README.md b/docs/README.md index 28e42e0..515f1ee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,7 +31,7 @@ Add the crate and an async runtime: ```toml [dependencies] -apify-client = "0.17" +apify-client = "0.18" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` @@ -64,6 +64,10 @@ suite and the Apify platform use), so production code typically does `ApifyClient::new(std::env::var("APIFY_TOKEN")?)`. The literal `"my-api-token"` above is only a placeholder for brevity. +Create the token on the [Integrations page](https://console.apify.com/settings/integrations) in +Apify Console. Apify Console shows the token only once, right after you create or rotate it, so copy it +and store it somewhere safe. + ## Imports The client, the builder, and **every** option/parameter struct are re-exported at the crate @@ -71,23 +75,24 @@ root, so you can import them directly from `apify_client` — you never need the `apify_client::clients::::` path. The complete set of re-exported option/parameter types is: -- Actors: `ActorStartOptions`, `ActorCallOptions`, `TaskStartOptions`, `ActorBuildOptions`, `ActorListOptions` +- Actors: `ActorStartOptions`, `ActorCallOptions`, `TaskStartOptions`, `ActorBuildOptions`, `ActorListOptions`, `WaitForResources` - Runs: `RunListOptions`, `RunResurrectOptions`, `RunMetamorphOptions`, `RunChargeOptions`, `LastRunOptions` - Datasets: `DatasetListItemsOptions`, `DatasetDownloadOptions`, `DownloadItemsFormat` -- Key-value stores: `ListKeysOptions`, `GetRecordOptions` -- Request queues: `ListRequestsOptions` +- Key-value stores: `ListKeysOptions`, `GetRecordOptions`, `SetRecordOptions` +- Request queues: `ListRequestsOptions`, `BatchAddRequestsOptions` - Store: `StoreListOptions` -- Logs: `LogOptions`, `LogRedirect`, `LogSink`, `StreamedLog`, `StreamedLogOptions` -- Shared: `ListOptions`, `StorageListOptions` +- Logs: `LogOptions`, `LogRedirect`, `LogSink`, `StdoutLogSink`, `StreamedLog`, `StreamedLogOptions` +- Shared: `ListOptions`, `StorageListOptions`, `Timeout` - Server Actors: `ActorServerRequestOptions`, `ActorServerBody`, `ActorServerCompression` -- Client configuration: `RequestCompression` +- Client configuration: `RequestCompression`, `HttpCompressor`, `BrotliHttpCompressor`, `GzipHttpCompressor`, and `ZstdHttpCompressor` (needs the `zstd` feature) plus the common container `PaginationList`, `ListIterator` (the return type of every collection client's `iterate()` method), `StoreActorIterator` (a type alias for `ListIterator`, the return type of -`StoreCollectionClient::iterate`), and the two cursor-based iterators `KeyValueStoreKeysIterator` +`StoreCollectionClient::iterate`), the two cursor-based iterators `KeyValueStoreKeysIterator` (from `KeyValueStoreClient::iterate_keys`) and `RequestQueueRequestsIterator` (from -`RequestQueueClient::paginate_requests`). Import any of them directly from `apify_client`: +`RequestQueueClient::paginate_requests`), and `RunDatasetItemsIterator` (from +`RunClient::iterate_dataset_items`). Import any of them directly from `apify_client`: ```rust,no_run use apify_client::{ApifyClient, ActorListOptions, StoreListOptions, DownloadItemsFormat}; diff --git a/docs/actors.md b/docs/actors.md index d098b55..75ec001 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -339,7 +339,7 @@ When your multi-tenant Server Actor calls another one while it handles a request `X-Actor-Request-ID` header in `parent_request_id`. The client sends it as the same header, so the called Actor charges at the pricing tier of your incoming request. Use a client created with the run's `APIFY_TOKEN`. For details, see -[Compose multi-tenant Server Actors](https://docs.apify.com/platform/actors/development/programming-interface/standby#compose-server-actors). +[Call another multi-tenant Server Actor](https://docs.apify.com/platform/actors/monetize/server-actors#call-another-multi-tenant-server-actor). ```rust,no_run use apify_client::{ActorServerRequestOptions, ApifyClient}; diff --git a/docs/misc.md b/docs/misc.md index 3f282c1..5f7b1b1 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -87,16 +87,20 @@ organization your API token belongs to. They return a `404` as an error. | Field | Type | Description | |---|---|---| -| `id` | `String` | Unique user ID (always present). | -| `username` | `Option` | Username. | +| `id` | `Option` | Unique user ID. Present in the private account details, absent from the public profile and the reduced proxy data. | +| `username` | `Option` | Username. Absent from the reduced proxy data. | | `profile` | `Option` | The public profile: `name`, `picture_url` and `website_url` (both normalized to their WHATWG URL serialization) and the other fields in `extra`. | | `extra` | `Extra` | Any other fields returned by the API (more fields are present for `me` than for a public `user(id)`). | +A request authenticated with a proxy password (`PROXY_PASSWORD` or `ACTOR_RUN_PROXY_PASSWORD`) gets only +the reduced data Apify Proxy reads: `plan.availableProxyGroups`, `effectivePlatformFeatures`, and +`isPaying`, all in `extra`. In that case, `id` and `username` are `None`. + ```rust,no_run # use apify_client::ApifyClient; # async fn run(client: ApifyClient) -> Result<(), Box> { if let Some(user) = client.me().get().await? { - println!("account id {}, username {:?}", user.id, user.username); + println!("account id {:?}, username {:?}", user.id, user.username); } # Ok(()) # } diff --git a/docs/runs.md b/docs/runs.md index 7bb5a0a..6b1ce1e 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -19,7 +19,7 @@ collections are available via `actor.runs()` and `task.runs()`. | `update(fields)` | `&impl Serialize` | `ActorRun` | Updates the run (e.g. status message). | | `delete()` | — | `()` | Deletes the run. | | `abort(gracefully)` | `Option` | `ActorRun` | Aborts the run. `None` omits the param (server default, immediate); `Some(true)`/`Some(false)` abort gracefully/immediately. | -| `metamorph(target, input, options)` | `&str`, `Option<&impl Serialize>`, `RunMetamorphOptions` | `ActorRun` | Transforms the run into another Actor. | +| `metamorph(target, input, options)` | `&str`, `Option<&impl Serialize>`, `RunMetamorphOptions` | `ActorRun` | Transforms the run into another Actor. Only the run itself can metamorph: use the run's own token from `APIFY_TOKEN`, as the API rejects any other token. | | `metamorph_raw(target, input, options)` | `&str`, `&[u8]`, `RunMetamorphOptions` | `ActorRun` | Like `metamorph`, but sends `input` as a raw request body (no JSON serialization), paired with `options.content_type`. | | `reboot()` | — | `ActorRun` | Reboots the run's container. | | `resurrect(options)` | `RunResurrectOptions` | `ActorRun` | Resurrects a run in a terminal state (`SUCCEEDED`, `FAILED`, `ABORTED`, `TIMED-OUT`). To continue a run that reached its cost limit, pass a higher `max_total_charge_usd`; the limit covers the whole run, including the cost before the resurrection. | @@ -77,7 +77,8 @@ streamed_log.stop().await?; the charge, so a retry past that window creates a new charge instead of being deduplicated), `request_id` (ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the incoming request; required for multi-tenant Server Actor runs, where it maps the charge to the -caller's account; omitted from the request when `None`). +caller's account, and ignored by runs of single-tenant Server Actors; omitted from the request +when `None`). Call `charge` from the run itself, with the token the run received in `APIFY_TOKEN`. `ActorRun.status` is a stringly-typed `Option` carrying the API's run status. Known values are `READY`, `RUNNING`, `SUCCEEDED`, `FAILED`, `ABORTING`, `ABORTED`, `TIMING-OUT`, and diff --git a/examples/create_build_run_actor.rs b/examples/create_build_run_actor.rs index e89efe4..5e6b614 100644 --- a/examples/create_build_run_actor.rs +++ b/examples/create_build_run_actor.rs @@ -9,7 +9,13 @@ use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // Create a minimal Actor with an inline source-files version. let suffix = uuid_like(); diff --git a/examples/get_account.rs b/examples/get_account.rs index 4e1756a..da0339b 100644 --- a/examples/get_account.rs +++ b/examples/get_account.rs @@ -8,10 +8,16 @@ use chrono::Utc; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); let user = client.me().get().await?.expect("current user"); - println!("Account id: {}", user.id); + println!("Account id: {}", user.id.as_deref().unwrap_or("(none)")); println!("Username: {}", user.username.as_deref().unwrap_or("(none)")); // Monthly usage for the current billing cycle (`None` == current cycle). diff --git a/examples/iterate_store.rs b/examples/iterate_store.rs index 23b2fea..76aa1be 100644 --- a/examples/iterate_store.rs +++ b/examples/iterate_store.rs @@ -7,7 +7,13 @@ use apify_client::{ApifyClient, StoreListOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // Iterate the store, fetching pages of 5 on demand. `with_chunk_size` sets the per-request // page size; the options' `limit` (left unset here) would instead cap the total number of diff --git a/examples/log_redirection.rs b/examples/log_redirection.rs index 5f13a56..7d63cd2 100644 --- a/examples/log_redirection.rs +++ b/examples/log_redirection.rs @@ -13,7 +13,13 @@ use apify_client::{ActorCallOptions, ApifyClient, LogRedirect, StreamedLogOption #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // The (separate) Actor whose log we will redirect into this program's output. let source_actor = "apify/hello-world"; diff --git a/examples/raw_log.rs b/examples/raw_log.rs index ffb7623..a28738e 100644 --- a/examples/raw_log.rs +++ b/examples/raw_log.rs @@ -13,7 +13,13 @@ use futures_util::StreamExt; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // Run a short public Actor and wait for it to finish so it has a complete log. let run = client diff --git a/examples/run_and_last_run_storages.rs b/examples/run_and_last_run_storages.rs index f57f253..3e35dfe 100644 --- a/examples/run_and_last_run_storages.rs +++ b/examples/run_and_last_run_storages.rs @@ -8,7 +8,13 @@ use apify_client::{ApifyClient, LastRunOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // Start a run and wait for it to finish. let run = client diff --git a/examples/run_store_actor.rs b/examples/run_store_actor.rs index 0975fe7..b7c183b 100644 --- a/examples/run_store_actor.rs +++ b/examples/run_store_actor.rs @@ -12,7 +12,13 @@ use apify_client::{ApifyClient, StoreListOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // Discover the public `apify/hello-world` Actor through the Apify Store API. It is free, // fast, and runs without input, which keeps this example reliable. diff --git a/examples/storages.rs b/examples/storages.rs index 26959fe..bd47510 100644 --- a/examples/storages.rs +++ b/examples/storages.rs @@ -11,7 +11,13 @@ use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { let token = std::env::var("APIFY_TOKEN").expect("set APIFY_TOKEN"); - let client = ApifyClient::new(token); + // `APIFY_API_URL` optionally points the example at another API, such as a staging deployment. + let api_url = + std::env::var("APIFY_API_URL").unwrap_or_else(|_| "https://api.apify.com/v2".into()); + let client = ApifyClient::builder() + .token(token) + .base_url(api_url) + .build(); // ---- Dataset: create, push, read ---- let dataset = client.datasets().get_or_create(None).await?; diff --git a/src/clients/run.rs b/src/clients/run.rs index 6689af9..14ff9c6 100644 --- a/src/clients/run.rs +++ b/src/clients/run.rs @@ -85,8 +85,8 @@ pub struct RunChargeOptions { pub idempotency_key: Option, /// ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header /// of the incoming request. Required for multi-tenant Server Actor runs, where it maps the - /// charge to the caller's account instead of the account that started the run. Omitted from - /// the request body when `None`. + /// charge to the caller's account instead of the account that started the run. Runs of + /// single-tenant Server Actors ignore it. Omitted from the request body when `None`. pub request_id: Option, } @@ -177,6 +177,10 @@ impl RunClient { /// Transforms the run into a run of another Actor (metamorph). /// + /// Only the run itself can metamorph: the client must use the run's own API token, which the + /// run gets in the `APIFY_TOKEN` environment variable. With any other token, the API rejects + /// the request. + /// /// `options.content_type` sets the content type of the input body (default /// `application/json`). To send a non-JSON input as raw bytes, use /// [`metamorph_raw`](Self::metamorph_raw). @@ -197,6 +201,8 @@ impl RunClient { /// Transforms the run into a run of another Actor (metamorph) with a raw request body /// instead of a JSON-serializable value. /// + /// Like [`metamorph`](Self::metamorph), only the run itself can call it, with its own token. + /// /// The bytes are sent exactly as given, with no JSON serialization — pair this with /// `options.content_type` for a non-JSON input. For an object or array input, use /// [`metamorph`](Self::metamorph) instead. @@ -289,7 +295,8 @@ impl RunClient { /// An idempotency key is always sent (generated when `options.idempotency_key` is `None`), so /// a charge that the transport retries is applied at most once. /// - /// The charge endpoint returns an empty body on success, so any 2xx response is a success. + /// Call it from the run itself, with the token the run received in `APIFY_TOKEN`. The charge + /// endpoint returns an empty body on success, so any 2xx response is a success. pub async fn charge(&self, options: RunChargeOptions) -> ApifyClientResult<()> { let count = options.count.unwrap_or(1); let idempotency_key = options diff --git a/src/clients/user.rs b/src/clients/user.rs index fcf4a64..e05eec9 100644 --- a/src/clients/user.rs +++ b/src/clients/user.rs @@ -30,7 +30,8 @@ impl UserClient { /// Fetches the user account information, or `None` if the user does not exist. /// /// For the current user (`me`) this returns private account details; for other users - /// it returns the public profile. + /// it returns the public profile. A request authenticated with a proxy password gets only the + /// reduced data Apify Proxy reads, so `id` and `username` can be `None`. pub async fn get(&self) -> ApifyClientResult> { get_resource(&self.ctx, None, &QueryParams::new(), Timeout::Short).await } diff --git a/src/lib.rs b/src/lib.rs index c341b28..de05097 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -84,7 +84,9 @@ pub use clients::actor_server::{ ActorServerBody, ActorServerCompression, ActorServerRequestOptions, }; pub use clients::dataset::{DatasetDownloadOptions, DatasetListItemsOptions, DownloadItemsFormat}; -pub use clients::key_value_store::{GetRecordOptions, KeyValueStoreKeysIterator, ListKeysOptions}; +pub use clients::key_value_store::{ + GetRecordOptions, KeyValueStoreKeysIterator, ListKeysOptions, SetRecordOptions, +}; pub use clients::log::LogOptions; pub use clients::pagination::ListIterator; pub use clients::request_queue::{ diff --git a/src/models.rs b/src/models.rs index 1950504..2953c96 100644 --- a/src/models.rs +++ b/src/models.rs @@ -753,18 +753,25 @@ pub struct WebhookDispatchWebhookSummary { } /// Account information about a user. +/// +/// The API answers with one of three shapes, and every field is optional so that all of them +/// deserialize: the private account details, the public profile, or, for a request authenticated +/// with a proxy password (`PROXY_PASSWORD` or `ACTOR_RUN_PROXY_PASSWORD`), only the reduced data +/// Apify Proxy reads (`plan.availableProxyGroups`, `effectivePlatformFeatures`, and `isPaying`, +/// found in `extra`). #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct User { - /// Unique user ID. - pub id: String, - /// Username. + /// Unique user ID. Absent from the public profile and the reduced proxy data. + #[serde(default)] + pub id: Option, + /// Username. Absent from the reduced proxy data. #[serde(default)] pub username: Option, /// The user's public profile. #[serde(default)] pub profile: Option, - /// Any other fields returned by the API (public or private depending on the call). + /// Any other fields returned by the API (public, private, or reduced depending on the call). #[serde(flatten)] pub extra: Extra, } diff --git a/src/version.rs b/src/version.rs index e91ab73..f4f3b3f 100644 --- a/src/version.rs +++ b/src/version.rs @@ -10,4 +10,4 @@ pub const CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION"); /// and verified against. /// /// This corresponds to the `info.version` field of the Apify OpenAPI document. -pub const API_SPEC_VERSION: &str = "v2-2026-11-09T143926Z"; +pub const API_SPEC_VERSION: &str = "v2-2026-11-18T151559Z"; diff --git a/tests/build.rs b/tests/build.rs index aca3e8b..045f817 100644 --- a/tests/build.rs +++ b/tests/build.rs @@ -150,18 +150,14 @@ async fn build_actor_flow() { let log = build_client.log().get().await.expect("get build log"); assert!(log.is_some(), "finished build should have a log"); - // Fetch the build's OpenAPI definition (simple GET; may be None if not generated). + // Fetch the build's OpenAPI definition (simple GET). let _openapi = build_client .get_openapi_definition() .await .expect("get openapi definition"); - // Validate input against the just-built `latest` build, exercising the spec's optional - // `build` query parameter on POST /v2/actors/{actorId}/validate-input. A real `latest` - // build now exists (built above), so `build=latest` resolves to a concrete artifact. - // The success response is an object with a `valid` boolean; asserting that field is present - // (rather than merely `is_object()`) proves the call hit the endpoint with the param accepted - // and did not return an error envelope. + // Validate input against the just-built `latest` build (the optional `build` query parameter). + // A `valid` boolean in the response shows the endpoint accepted it, not an error envelope. let validation = actor_client .validate_input_for_build(&json!({}), Some("latest")) .await @@ -170,7 +166,4 @@ async fn build_actor_flow() { validation.get("valid").and_then(|v| v.as_bool()).is_some(), "validate-input response should contain a `valid` boolean, got: {validation}" ); - - // Clean up. - actor_client.delete().await.expect("delete actor"); } diff --git a/tests/unit_http.rs b/tests/unit_http.rs index 694cd03..c8e05b4 100644 --- a/tests/unit_http.rs +++ b/tests/unit_http.rs @@ -39,7 +39,7 @@ async fn success_single_call() { )]); let client = client_with(backend.clone(), 3); let user = client.me().get().await.expect("ok").expect("some"); - assert_eq!(user.id, "abc"); + assert_eq!(user.id.as_deref(), Some("abc")); assert_eq!(backend.call_count(), 1); } @@ -104,7 +104,7 @@ async fn retry_then_success() { ]); let client = client_with(backend.clone(), 5); let user = client.me().get().await.expect("ok").expect("some"); - assert_eq!(user.id, "ok"); + assert_eq!(user.id.as_deref(), Some("ok")); assert_eq!(backend.call_count(), 3); } diff --git a/tests/unit_resources.rs b/tests/unit_resources.rs index c199dbe..75d45e5 100644 --- a/tests/unit_resources.rs +++ b/tests/unit_resources.rs @@ -463,7 +463,7 @@ async fn a_pending_request_with_a_null_handled_at_deserializes() { } /// The API returns a `null` `uiState` once an update changed the schedule's `cronExpression` or -/// `timezone`, although the spec types it as an object. +/// `timezone`, which the spec types as nullable. #[tokio::test] async fn a_schedule_with_a_null_ui_state_deserializes() { let backend = MockBackend::new(vec![ok_data(json!({ @@ -481,6 +481,48 @@ async fn a_schedule_with_a_null_ui_state_deserializes() { assert_eq!(schedule.extra.get("uiState"), Some(&Value::Null)); } +/// A request authenticated with a proxy password gets only the reduced proxy data, without `id` +/// and `username`. +#[tokio::test] +async fn reduced_proxy_user_data_deserializes() { + let backend = MockBackend::new(vec![ok_data(json!({ + "plan": { "availableProxyGroups": ["RESIDENTIAL"] }, + "effectivePlatformFeatures": {}, + "isPaying": true + }))]); + let client = client_with(backend, 0); + let user = client + .me() + .get() + .await + .unwrap() + .expect("the current user exists"); + assert_eq!(user.id, None); + assert_eq!(user.username, None); + assert_eq!(user.extra.get("isPaying"), Some(&Value::Bool(true))); + assert_eq!( + user.extra + .get("plan") + .and_then(|plan| plan.pointer("/availableProxyGroups/0")), + Some(&json!("RESIDENTIAL")) + ); +} + +/// The public profile of another user has a `username` but no `id`. +#[tokio::test] +async fn public_user_profile_without_an_id_deserializes() { + let backend = MockBackend::new(vec![ok_data(json!({ "username": "someone" }))]); + let client = client_with(backend, 0); + let user = client + .user("someone") + .get() + .await + .unwrap() + .expect("the user exists"); + assert_eq!(user.id, None); + assert_eq!(user.username.as_deref(), Some("someone")); +} + // ----- clients chained from the last run -------------------------------------------------- /// The `status` and `origin` filters of `last_run` select the run, so the log and the storages of diff --git a/tests/unit_timeouts.rs b/tests/unit_timeouts.rs index d1bed5d..bc4d442 100644 --- a/tests/unit_timeouts.rs +++ b/tests/unit_timeouts.rs @@ -9,14 +9,13 @@ mod common; use std::sync::Arc; use std::time::Duration; -use apify_client::clients::key_value_store::SetRecordOptions; use apify_client::http_client::{HttpBackend, HttpMethod, HttpRequest, ReqwestBackend}; use apify_client::timeouts::NO_TIMEOUT; #[cfg(feature = "zstd")] use apify_client::ZstdHttpCompressor; use apify_client::{ ActorStartOptions, ApifyClient, ApifyClientError, BrotliHttpCompressor, GzipHttpCompressor, - HttpCompressor, Timeout, + HttpCompressor, SetRecordOptions, Timeout, }; use common::mock_backend::{client_with, MockBackend, MockOutcome}; use serde_json::{json, Value}; diff --git a/tests/user.rs b/tests/user.rs index 31693bd..fb52738 100644 --- a/tests/user.rs +++ b/tests/user.rs @@ -12,7 +12,47 @@ async fn get_own_account() { .await .expect("get current user") .expect("current user should exist"); - assert!(!user.id.is_empty(), "user id should be present"); + let id = user + .id + .expect("the private account details carry the user id"); + assert!(!id.is_empty(), "user id should not be empty"); +} + +/// Simple GET: the by-id endpoint answers for the caller's own account, as the private details. +#[tokio::test(flavor = "multi_thread")] +async fn get_own_account_by_user_id() { + let client = require_client!(); + let me = client + .me() + .get() + .await + .expect("get current user") + .expect("current user should exist"); + let id = me + .id + .expect("the private account details carry the user id"); + + let by_id = client + .user(&id) + .get() + .await + .expect("get user by id") + .expect("own account should exist"); + assert_eq!(by_id.username, me.username); +} + +/// Simple GET: the public profile of another account has a `username` and no `id`. +#[tokio::test(flavor = "multi_thread")] +async fn get_public_profile_of_another_user() { + let client = require_client!(); + let user = client + .user("apify") + .get() + .await + .expect("get public profile") + .expect("the apify account should exist"); + assert_eq!(user.username.as_deref(), Some("apify")); + assert_eq!(user.id, None, "a public profile carries no user id"); } /// Simple GET: the current account's monthly usage. @@ -93,7 +133,10 @@ async fn get_limits_and_monthly_usage_by_user_id() { .expect("get current user") .expect("current user should exist"); - let by_id = client.user(&user.id); + let id = user + .id + .expect("the private account details carry the user id"); + let by_id = client.user(&id); let limits = by_id.limits().await.expect("get limits by user id"); assert!(limits.is_object(), "limits should be a JSON object"); let usage = by_id