diff --git a/CHANGELOG.md b/CHANGELOG.md index d6d3e59..e7041d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,37 @@ 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.19.0] - 2026-12-03 + +### Added +- `StoreCollectionClient::search` with `StoreSearchOptions` and `StoreSearchResult`. It sends one + request and returns the Actors that match a query best, at most 100, with the `limit` the API + applied. An empty `search` is an `InvalidArgument` error. +- `TaskClient::call` redirects the log of the run while it waits, like `ActorClient::call`. + `TaskCallOptions` has the new `log` option. +- `StreamedLog::last_redirected_at` and `StreamedLogOptions::since`. + +### Changed +- **Breaking:** `StoreListOptions` loses `search`, `sort_by`, and `allows_agentic_users`. Use + `StoreCollectionClient::search` to search. The API ignores `sort_by`, so a listing comes in Store + order and a search comes by relevance. The API dropped `allowsAgenticUsers` from the spec. +- **Breaking:** `TaskClient::call` takes `TaskCallOptions { start, wait_secs, log }` instead of + `TaskStartOptions` and `wait_secs`. It now redirects the log to the standard output by default; + pass `LogRedirect::Disabled` to opt out. +- **Breaking:** `StreamedLogOptions::from_start` is replaced by `since`, an + `Option>`. Use `since: None` for the whole log. +- A log stream that is cut off while the run is still going is reopened, and the redirection + resumes after the last redirected message. +- Documented that the signature of `DatasetClient::create_items_public_url`, + `create_items_public_url_with_format`, and `KeyValueStoreClient::create_keys_public_url` grants + access to all items or all keys until it expires, and that the list options of an items URL are + not covered by it. +- `ActorVersionCollectionClient::create` and `ActorVersionClient::update` use the `Long` timeout + tier by default, since a version can carry its source files. +- Synced with Apify OpenAPI spec `v2-2026-12-02T102104Z` (`API_SPEC_VERSION`). It documents that + the build OpenAPI definition needs a token unless the Actor is public or the build owner allows + anyone with the ID to read it, and removes agentic payments. + ## [0.18.0] - 2026-11-20 ### Added diff --git a/Cargo.toml b/Cargo.toml index 8f39189..e6cb32b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apify-client" -version = "0.18.0" +version = "0.19.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 806784f..cbc9571 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.18" +apify-client = "0.19" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } serde_json = "1" # for the `serde_json::Value` responses used in the Quick start ``` @@ -32,7 +32,8 @@ project needs `serde_json`. Two more dependencies are needed only for specific f `stream_with_options()`); it provides the `StreamExt` trait used to poll the returned stream. The [`raw_log`](examples/raw_log.rs) example imports `futures_util::StreamExt` for this. See [`docs/misc.md`](docs/misc.md#logs--clientlogbuild_or_run_id). Log redirection - (`ActorClient::call`, `RunClient::get_streamed_log`) needs no extra dependency. + (`ActorClient::call`, `TaskClient::call`, `RunClient::get_streamed_log`) needs no extra + dependency. - `chrono = "0.4"` — only if you construct or read timestamp values yourself. Model timestamp fields (e.g. `Actor::created_at`, `ActorRun::started_at`) are typed as `Option>` and `chrono` is **not** re-exported, so snippets that call `chrono::Utc::now()` (e.g. the @@ -49,7 +50,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.18", default-features = false, features = ["rustls", "zstd"] } +apify-client = { version = "0.19", default-features = false, features = ["rustls", "zstd"] } ``` The `rustls` feature requires `rustls-webpki` 0.103.16 or newer and `webpki-roots` 1.0.10 or @@ -215,7 +216,7 @@ rest pass through). `isAtHome` reflects the `APIFY_IS_AT_HOME` environment varia | `client.schedules()` / `client.schedule(id)` | collection / single | Schedules | | `client.webhooks()` / `client.webhook(id)` | collection / single | Webhooks | | `client.webhook_dispatches()` / `client.webhook_dispatch(id)` | collection / single | Webhook dispatches | -| `client.store()` | collection | Browse the Apify Store | +| `client.store()` | collection | Browse and search the Apify Store | | `client.me()` / `client.user(id)` | single | User accounts | | `client.log(build_or_run_id)` | single | Build/run logs | diff --git a/docs/README.md b/docs/README.md index 515f1ee..3a66e13 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.18" +apify-client = "0.19" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` @@ -75,12 +75,12 @@ 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`, `WaitForResources` +- Actors: `ActorStartOptions`, `ActorCallOptions`, `TaskStartOptions`, `TaskCallOptions`, `ActorBuildOptions`, `ActorListOptions`, `WaitForResources` - Runs: `RunListOptions`, `RunResurrectOptions`, `RunMetamorphOptions`, `RunChargeOptions`, `LastRunOptions` - Datasets: `DatasetListItemsOptions`, `DatasetDownloadOptions`, `DownloadItemsFormat` - Key-value stores: `ListKeysOptions`, `GetRecordOptions`, `SetRecordOptions` - Request queues: `ListRequestsOptions`, `BatchAddRequestsOptions` -- Store: `StoreListOptions` +- Store: `StoreListOptions`, `StoreSearchOptions`, `StoreSearchResult` - Logs: `LogOptions`, `LogRedirect`, `LogSink`, `StdoutLogSink`, `StreamedLog`, `StreamedLogOptions` - Shared: `ListOptions`, `StorageListOptions`, `Timeout` - Server Actors: `ActorServerRequestOptions`, `ActorServerBody`, `ActorServerCompression` diff --git a/docs/actors.md b/docs/actors.md index 75ec001..8e22b3c 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -39,9 +39,9 @@ be an Actor ID or a `username~name` (or `username/name`) reference. All fields are optional. Used by `start` and `start_raw`, and as `ActorCallOptions::start` by `call` and `call_raw` (there, `wait_for_finish` is server-side; `ActorCallOptions::wait_secs` -controls client-side polling). [Tasks](tasks.md) take `TaskStartOptions`, which has the same -fields except `content_type` and `force_permission_level`, because `POST /actor-tasks/{id}/runs` -documents neither. +controls client-side polling). [Tasks](tasks.md) take `TaskStartOptions` (inside +`TaskCallOptions` for `call`), which has the same fields except `content_type` and +`force_permission_level`, because `POST /actor-tasks/{id}/runs` documents neither. | Field | Type | Description | |---|---|---| @@ -407,4 +407,5 @@ when it is `None`. Creating a version needs `versionNumber` and `sourceType` in the body, and so does every item of the `versions` array in an Actor create or update body. The writable source types are `SOURCE_FILES`, `GIT_REPO`, `TARBALL` and `GITHUB_GIST`; `SOURCE_CODE` can be read but not sent. -Updating a version needs no required field. +Updating a version needs no required field. `create` and `update` use the `Long` timeout tier by +default, since a version can carry its source files; set another one with `with_timeout`. diff --git a/docs/builds.md b/docs/builds.md index d1e9f43..18ae1c8 100644 --- a/docs/builds.md +++ b/docs/builds.md @@ -18,7 +18,7 @@ collections are available via `actor.builds()`. | `abort()` | — | `Build` | Aborts the build. | | `delete()` | — | `()` | Deletes the build. | | `wait_for_finish(wait_secs)` | `Option` | `Build` | Polls until the build is terminal. `None` waits indefinitely, without a client-side timeout on the polls; `Some(n)` bounds the wait and gives each poll the `Medium` tier plus the hold it asks the API for. A timeout set with `with_timeout` replaces both. A build ID that keeps 404ing past a 3-second grace period (reset by any successful fetch) returns the `404` as an error instead of polling forever. | -| `get_openapi_definition()` | — | `serde_json::Value` | Fetches the OpenAPI definition generated for the build (raw JSON, endpoint `.../openapi.json`). A `404` is an error. | +| `get_openapi_definition()` | — | `serde_json::Value` | Fetches the OpenAPI definition generated for the build (raw JSON, endpoint `.../openapi.json`). A `404` is an error. No token is needed for a build of a public Actor, or one whose owner set the general resource access to `Anyone with ID can read`; otherwise the token must have access to the build. | | `log()` | — | `LogClient` | Access the build's log. | The returned `Build` model's fields (`id`, `status`, `build_number`, …) are documented in diff --git a/docs/misc.md b/docs/misc.md index 5f7b1b1..e219868 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -6,13 +6,51 @@ | Method | Arguments | Returns | Description | |---|---|---|---| -| `list(options)` | `StoreListOptions` | `PaginationList` | One page of Store Actors. | -| `iterate(options)` | `StoreListOptions` | `StoreActorIterator` | Lazy, page-fetching iterator. | +| `list(options)` | `StoreListOptions` | `PaginationList` | One page of Store Actors, in Store order. | +| `iterate(options)` | `StoreListOptions` | `StoreActorIterator` | Lazy, page-fetching iterator over the Store listing. | +| `search(options)` | `StoreSearchOptions` | `StoreSearchResult` | The Actors that match a query best, as a single page. | -`StoreListOptions`: `offset`, `limit`, `search`, `sort_by`, `category`, `username`, -`pricing_model`, `include_unrunnable_actors`, `allows_agentic_users`, `response_format`. +The API serves the Store in two ways, and the client has a method for each. `list` and `iterate` +browse the whole Store. `search` finds Actors by a text query. + +`StoreListOptions`: `offset`, `limit`, `category`, `username`, `pricing_model`, +`include_unrunnable_actors`, `response_format`, `include_input_schema`. `limit` means a single page's size for `list`, but a cap on the *total* number of -items yielded for `iterate` (see below). +items yielded for `iterate` (see below). A page has at most 1000 items, or 10 with +`include_input_schema`. The API has no option to change the order of a listing, which is the +Store order: sort the results on the client if you need a different one. `category` takes one or +more category IDs separated by commas, such as `AI_AND_ML`; an Actor must match all of them, and an +unknown category makes the API answer with a `400` error. + +`StoreSearchOptions`: a required, non-empty `search`, and `limit`, `category`, `username`, +`pricing_model`, `include_unrunnable_actors`, `response_format`, `include_input_schema`. There is no +`offset`. An empty `search` fails with `ApifyClientError::InvalidArgument`, because the API answers +it with the Store listing. + +The API ranks the results of a search by relevance and returns them as a single page of at most +100 Actors, so a larger `limit` is reduced to 100. It ignores `offset`, and it reports the number +of Actors it returned as `total`, not the number of Actors that match. A search therefore can't be +paged through, and `search` has no iterator. `StoreSearchResult` has `items` and `limit`, the +limit the API applied. When `items.len()` equals it, more Actors may match than were returned: +narrow the search with a more specific query or with the filters. + +```rust,no_run +# use apify_client::{ApifyClient, StoreSearchOptions}; +# async fn run(client: ApifyClient) -> Result<(), Box> { +let result = client + .store() + .search(StoreSearchOptions { + search: "instagram posts".to_string(), + limit: Some(10), + ..Default::default() + }) + .await?; +for actor in result.items { + println!("{}: {:?}", actor.id, actor.title.or(actor.name)); +} +# Ok(()) +# } +``` `StoreActorIterator` is a type alias for `ListIterator` (the shared iterator returned by every collection's `iterate`), re-exported at the crate root alongside `ListIterator` @@ -50,7 +88,7 @@ while let Some(actor) = iter.next().await? { # } ``` -`ActorStoreListItem` (from `apify_client::models`) is the element type yielded by both `list` +`ActorStoreListItem` (from `apify_client::models`) is the element type yielded by `list`, `search` and the iterator. Its fields: | Field | Type | Description | diff --git a/docs/runs.md b/docs/runs.md index 6b1ce1e..afa869e 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -26,7 +26,7 @@ collections are available via `actor.runs()` and `task.runs()`. | `charge(options)` | `RunChargeOptions` | `()` | Charges a pay-per-event run (always sends an idempotency key). | | `wait_for_finish(wait_secs)` | `Option` | `ActorRun` | Polls until the run is terminal. `None` waits indefinitely, without a client-side timeout on the polls; `Some(n)` bounds the wait, gives each poll the `Medium` tier plus the hold it asks the API for, and may return a still-running (non-terminal) run if `n` elapses first. A timeout set with `with_timeout` replaces both. A run ID that keeps 404ing past a 3-second grace period (reset by any successful fetch) returns the `404` as an error instead of polling forever. | | `dataset()` / `key_value_store()` / `request_queue()` / `log()` | — | resource client | Access the run's default storages and log. | -| `get_streamed_log(options)` | `StreamedLogOptions { to_log, from_start }` | `Result>` (async — `.await` it) | The [redirection](#log-redirection) of the run's log; `None` if `to_log` is `LogRedirect::Disabled`, or, for `LogRedirect::Default`, if the run does not exist. A custom sink makes no request, so a missing run shows up as the error of `stop()`. | +| `get_streamed_log(options)` | `StreamedLogOptions { to_log, since }` | `Result>` (async — `.await` it) | The [redirection](#log-redirection) of the run's log; `None` if `to_log` is `LogRedirect::Disabled`, or, for `LogRedirect::Default`, if the run does not exist. A custom sink makes no request, so a missing run shows up as the error of `stop()`. | ### Log redirection @@ -42,12 +42,18 @@ stays in one piece, and each message goes to a `LogSink`: a logging framework. - `LogRedirect::Disabled` redirects nothing. -`from_start: false` drops the messages stamped before the call. A run that has not logged yet is -followed by reopening its empty log stream until the first bytes arrive. `ActorClient::call` does -all of this for the run it waits for; when the redirection ends early on an error, it passes a -`Log redirection stopped due to error: ..` message to the sink instead of failing the call. To -read the log as raw chunks instead, use `run.log().stream_with_options(..)`; the -[`raw_log`](../examples/raw_log.rs) example does. +`since` drops the messages stamped before it. `StreamedLog::last_redirected_at()` returns the +timestamp of the last redirected message, so a redirection that was interrupted can continue with +`since` set to that timestamp plus one millisecond. A run that has not logged yet is followed by +reopening its empty log stream until the first bytes arrive. A stream that is cut off while the +run goes on, for example after the run has logged nothing for several minutes, is reopened and +the redirection resumes after the last redirected message. The API cannot continue a stream from a +given point, so the reopen downloads the whole log again, and the lines of a message that arrive +only after the break (for example the rest of a stack trace) are not redirected. +`ActorClient::call` and `TaskClient::call` do all of this for the run they wait for. When the +redirection ends early on an error, they pass a `Log redirection stopped due to error: ..` message +to the sink instead of failing the call. To read the log as raw chunks instead, use +`run.log().stream_with_options(..)`; the [`raw_log`](../examples/raw_log.rs) example does. ```rust,no_run use apify_client::{ApifyClient, LogRedirect, StreamedLogOptions}; @@ -57,7 +63,7 @@ let run = client.run(run_id); let mut streamed_log = run .get_streamed_log(StreamedLogOptions { to_log: LogRedirect::to_sink(|message: &str| println!("run -> {message}")), - from_start: true, + since: None, }) .await? .ok_or("the run does not exist")?; diff --git a/docs/storages.md b/docs/storages.md index af7f036..b6dab44 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -70,7 +70,7 @@ let scratch = client.datasets().get_or_create(None).await?; | `get_statistics()` | — | `Value` | Field statistics. A `404` is an error. | | `download_items(format, options)` | `DownloadItemsFormat`, `DatasetDownloadOptions` | `Vec` | Export items as JSON/JSONL/CSV/XLSX/XML/RSS/HTML. | | `download_items_stream(format, options)` | `DownloadItemsFormat`, `DatasetDownloadOptions` | `Result>>>` (async — `.await` it) | Like `download_items`, but streams the export instead of buffering it, for constant-memory processing of a large export. | -| `create_items_public_url(options, expires)` | `DatasetListItemsOptions`, `Option` | `String` | Shareable (HMAC-signed for private) items URL, served as `json`. `expires` is the validity of the signed URL in seconds and must be positive and at most `common::MAX_EXPIRES_IN_SECS` (4611686018427387, about 146 million years): `0`, a negative or a larger value fails with `InvalidArgument`. Leave it out for a URL that does not expire. | +| `create_items_public_url(options, expires)` | `DatasetListItemsOptions`, `Option` | `String` | Shareable (HMAC-signed for private) items URL, served as `json`. The signature grants read access to all items until it expires. The list options are plain query parameters that it does not cover, so they only set the default shape of the response: anyone holding the URL can change or remove them. `expires` is the validity of the signed URL in seconds and must be positive and at most `common::MAX_EXPIRES_IN_SECS` (4611686018427387, about 146 million years): `0`, a negative or a larger value fails with `InvalidArgument`. Leave it out for a URL that does not expire. | | `create_items_public_url_with_format(options, expires, format)` | `DatasetListItemsOptions`, `Option`, `Option` | `String` | Like `create_items_public_url`, but lets the URL serve another export format (CSV, XLSX, ...). `None` defaults to `json`. `expires` follows the same rule as in `create_items_public_url`. | `DatasetListItemsOptions` (all optional): @@ -164,7 +164,7 @@ println!("streamed {total_bytes} bytes of JSONL"); | `delete_record(key)` | `&str` | `()` | Deletes a record. | | `get_record_with_options(key, options)` | `&str`, `GetRecordOptions { attachment, signature }` | `Option` | Reads a record with explicit attachment/signature options. | | `get_record_public_url(key)` | `&str` | `String` | Shareable (HMAC-signed for private) record URL. | -| `create_keys_public_url(expires)` | `Option` | `String` | Shareable keys-list URL. `expires` is the validity of the signed URL in seconds and must be positive and at most `common::MAX_EXPIRES_IN_SECS` (4611686018427387, about 146 million years): `0`, a negative or a larger value fails with `InvalidArgument`. Leave it out for a URL that does not expire. | +| `create_keys_public_url(expires)` | `Option` | `String` | Shareable keys-list URL. The signature grants access to the list of all keys until it expires. `expires` is the validity of the signed URL in seconds and must be positive and at most `common::MAX_EXPIRES_IN_SECS` (4611686018427387, about 146 million years): `0`, a negative or a larger value fails with `InvalidArgument`. Leave it out for a URL that does not expire. | `ListKeysOptions`: `limit`, `exclusive_start_key`, `prefix`, `collection`, `signature`. Like `StoreListOptions.limit`, the meaning of `limit` depends on the method: for `list_keys` it is a diff --git a/docs/tasks.md b/docs/tasks.md index 15f78a2..1cee7a9 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -20,7 +20,7 @@ Obtained via `client.tasks()` (collection) and `client.task(id)` (single). | `unpublish()` | — | `Task` | Unpublishes the task from its public landing page (sets `isPublic: false`), preserving `publicConfig`. | | `delete()` | — | `()` | Deletes the task. | | `start(input, options)` | `Option<&impl Serialize>`, `TaskStartOptions` | `ActorRun` | Starts a run. `TaskStartOptions` has the fields of [`ActorStartOptions`](actors.md#actorstartoptions) except `content_type` and `force_permission_level`, which the endpoint does not document. | -| `call(input, options, wait_secs)` | `Option<&impl Serialize>`, `TaskStartOptions`, `Option` | `ActorRun` | Starts a run and waits. Like [`ActorClient::call`](actors.md#actorcalloptions), it starts without a client-side timeout, but it does not redirect the log. | +| `call(input, options)` | `Option<&impl Serialize>`, `TaskCallOptions { start, wait_secs, log }` | `ActorRun` | Starts a run and waits for it to finish, redirecting its log to the standard output unless `options.log` says otherwise. `start` is the `TaskStartOptions` of `start`, and `wait_secs` and `log` work as in [`ActorCallOptions`](actors.md#actorcalloptions). Like `ActorClient::call`, it starts without a client-side timeout. A redirection that ends early on an error does not fail the call; the error goes to the log sink as a `Log redirection stopped due to error: ..` message. | | `get_input()` / `update_input(input)` | — / `&impl Serialize` | `Value` / `Value` | The task's saved input. `get_input` returns a `404` as an error. | | `last_run(status)` | `Option<&str>` | `RunClient` | The task's last run, optionally filtered by status. See [Actor runs](runs.md) for the accepted `status` values. | | `last_run_with_options(options)` | `LastRunOptions { status, origin }` | `RunClient` | The task's last run, optionally filtered by status and/or origin. See [Actor runs](runs.md) for the accepted `status` and `origin` values (common origins: `DEVELOPMENT`, `WEB`, `API`, `SCHEDULER`). | diff --git a/examples/log_redirection.rs b/examples/log_redirection.rs index 7d63cd2..f662194 100644 --- a/examples/log_redirection.rs +++ b/examples/log_redirection.rs @@ -42,7 +42,7 @@ async fn main() -> Result<(), Box> { to_log: LogRedirect::to_sink(move |message: &str| { println!("[{source_actor}] {message}") }), - from_start: true, + since: None, }) .await? .ok_or("the run does not exist")?; diff --git a/examples/run_store_actor.rs b/examples/run_store_actor.rs index b7c183b..a1028a6 100644 --- a/examples/run_store_actor.rs +++ b/examples/run_store_actor.rs @@ -7,7 +7,7 @@ //! //! Run with: `APIFY_TOKEN=... cargo run --example run_store_actor` -use apify_client::{ApifyClient, StoreListOptions}; +use apify_client::{ApifyClient, StoreSearchOptions}; #[tokio::main] async fn main() -> Result<(), Box> { @@ -22,19 +22,19 @@ async fn main() -> Result<(), Box> { // 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. - let store_page = client + let found = client .store() - .list(StoreListOptions { - search: Some("hello world".to_string()), + .search(StoreSearchOptions { + search: "hello world".to_string(), limit: Some(25), ..Default::default() }) .await?; // Prefer the ID discovered via search, but fall back to the well-known `apify/hello-world` - // identifier if Store ranking pushes it out of the first page — that keeps the example + // identifier if Store ranking pushes it out of the results, which keeps the example // (and its CI smoke test) from failing when search results shift. - let actor_id = store_page + let actor_id = found .items .into_iter() .find(|a| { diff --git a/src/clients/actor.rs b/src/clients/actor.rs index b1369e9..f70484a 100644 --- a/src/clients/actor.rs +++ b/src/clients/actor.rs @@ -16,7 +16,7 @@ use crate::clients::build::BuildClient; use crate::clients::build_collection::BuildCollectionClient; use crate::clients::run::{LastRunOptions, RunClient}; use crate::clients::run_collection::RunCollectionClient; -use crate::clients::streamed_log::{LogRedirect, StreamedLogOptions}; +use crate::clients::streamed_log::LogRedirect; use crate::clients::webhook_collection::WebhookCollectionClient; use crate::common::{parse_data_envelope, QueryParams}; use crate::error::ApifyClientResult; @@ -125,7 +125,7 @@ pub struct ActorCallOptions { } /// Options shared by [`TaskClient::start`](crate::clients::task::TaskClient::start) and -/// [`TaskClient::call`](crate::clients::task::TaskClient::call): the +/// [`TaskClient::call`](crate::clients::task::TaskClient::call) (inside [`TaskCallOptions`]): the /// [`ActorStartOptions`] the `POST /actor-tasks/{id}/runs` endpoint accepts. A task takes its /// input as JSON, and its permission level is that of its Actor, so there is no `content_type` /// or `force_permission_level`. @@ -153,6 +153,19 @@ pub struct TaskStartOptions { pub wait_for_resources: Option, } +/// Options of [`TaskClient::call`](crate::clients::task::TaskClient::call). +#[derive(Debug, Default, Clone)] +pub struct TaskCallOptions { + /// The options of the run start. + pub start: TaskStartOptions, + /// The wait budget, in seconds, as in [`ActorCallOptions::wait_secs`]. Time spent retrying + /// under [`TaskStartOptions::wait_for_resources`] does not count toward it. + pub wait_secs: Option, + /// Where to redirect the log of the run while it is waited for, as in + /// [`ActorCallOptions::log`]: to the standard output by default. + pub log: LogRedirect, +} + impl From for ActorStartOptions { fn from(options: TaskStartOptions) -> Self { Self { @@ -349,27 +362,7 @@ impl ActorClient { if let Some(timeout) = self.ctx.timeout { run_client = run_client.with_timeout(timeout); } - let mut streamed_log = run_client - .get_streamed_log(StreamedLogOptions { - to_log: log, - from_start: true, - }) - .await - .unwrap_or_else(|error| { - eprintln!("Log redirection could not start: {error}"); - None - }); - if let Some(streamed_log) = streamed_log.as_mut() { - // A redirection that was just created is not started yet, so this cannot fail. - let _ = streamed_log.start(); - } - let finished = run_client.wait_for_finish(wait_secs).await; - if let Some(streamed_log) = streamed_log.as_mut() { - if let Err(error) = streamed_log.stop().await { - streamed_log.warn(&error); - } - } - finished + run_client.wait_for_finish_with_log(wait_secs, log).await } /// Builds the given version of the Actor and returns the created build. diff --git a/src/clients/actor_version.rs b/src/clients/actor_version.rs index 80a9ad8..1a9ef3f 100644 --- a/src/clients/actor_version.rs +++ b/src/clients/actor_version.rs @@ -32,8 +32,11 @@ impl ActorVersionClient { } /// Updates the version with the given fields. + /// + /// The request uses the `Long` timeout tier by default, since the version can carry its + /// source files. Set another one with [`with_timeout`](Self::with_timeout). pub async fn update(&self, new_fields: &T) -> ApifyClientResult { - update_resource(&self.ctx, None, new_fields, Timeout::Short).await + update_resource(&self.ctx, None, new_fields, Timeout::Long).await } /// Deletes the version. diff --git a/src/clients/actor_version_collection.rs b/src/clients/actor_version_collection.rs index 42efa26..7f8782f 100644 --- a/src/clients/actor_version_collection.rs +++ b/src/clients/actor_version_collection.rs @@ -41,7 +41,10 @@ impl ActorVersionCollectionClient { } /// Creates a new Actor version. + /// + /// The request uses the `Long` timeout tier by default, since the version can carry its + /// source files. Set another one with [`with_timeout`](Self::with_timeout). pub async fn create(&self, version: &T) -> ApifyClientResult { - create_resource(&self.ctx, &QueryParams::new(), version, Timeout::Short).await + create_resource(&self.ctx, &QueryParams::new(), version, Timeout::Long).await } } diff --git a/src/clients/build.rs b/src/clients/build.rs index a3958e9..d3c029f 100644 --- a/src/clients/build.rs +++ b/src/clients/build.rs @@ -69,6 +69,10 @@ impl BuildClient { /// OpenAPI document (not wrapped in a `data` envelope), returned as JSON. A build that does /// not exist, or has no OpenAPI definition, is a [`NotFound`](crate::ApiError::is_not_found) /// error: the response cannot tell the two apart. + /// + /// The API needs no token for the definition of a build of a public Actor, or of a build whose + /// owner set the general resource access to `Anyone with ID can read`. Otherwise, the token + /// must have access to the build, or the API answers with a `401` or `403` error. pub async fn get_openapi_definition(&self) -> ApifyClientResult { let response = crate::clients::base::get_raw_required( &self.ctx, diff --git a/src/clients/dataset.rs b/src/clients/dataset.rs index 3065031..b1842c5 100644 --- a/src/clients/dataset.rs +++ b/src/clients/dataset.rs @@ -447,6 +447,11 @@ impl DatasetClient { /// value fails with /// [`InvalidArgument`](crate::ApifyClientError::InvalidArgument) before any request is sent. /// Leave it out for a URL that does not expire. + /// + /// The signature grants read access to all items of the dataset until it expires. The list + /// options are added to the URL as plain query parameters that the signature does not cover, + /// so they only set the default shape of the response: anyone holding the URL can change or + /// remove them. pub async fn create_items_public_url( &self, options: DatasetListItemsOptions, @@ -462,6 +467,10 @@ impl DatasetClient { /// default. `expires_in_secs` follows the same rule as in /// [`create_items_public_url`](Self::create_items_public_url): positive, and at most /// [`MAX_EXPIRES_IN_SECS`](crate::common::MAX_EXPIRES_IN_SECS). + /// + /// The signature grants read access to all items until it expires, and, as for + /// [`create_items_public_url`](Self::create_items_public_url), anyone holding the URL can + /// change or remove the list options and the `format`, which the signature does not cover. pub async fn create_items_public_url_with_format( &self, options: DatasetListItemsOptions, diff --git a/src/clients/key_value_store.rs b/src/clients/key_value_store.rs index 1d34d91..0b97ec5 100644 --- a/src/clients/key_value_store.rs +++ b/src/clients/key_value_store.rs @@ -339,6 +339,8 @@ impl KeyValueStoreClient { /// value fails with /// [`InvalidArgument`](crate::ApifyClientError::InvalidArgument) before any request is sent. /// Leave it out for a URL that does not expire. + /// + /// The signature grants access to the list of all keys of the store until it expires. pub async fn create_keys_public_url( &self, expires_in_secs: Option, diff --git a/src/clients/run.rs b/src/clients/run.rs index 14ff9c6..92f4800 100644 --- a/src/clients/run.rs +++ b/src/clients/run.rs @@ -446,7 +446,7 @@ impl RunClient { &self, options: StreamedLogOptions, ) -> ApifyClientResult> { - let StreamedLogOptions { to_log, from_start } = options; + let StreamedLogOptions { to_log, since } = options; let (sink, prefix): (Arc, String) = match to_log { LogRedirect::Disabled => return Ok(None), LogRedirect::Sink(sink) => (sink, String::new()), @@ -475,6 +475,40 @@ impl RunClient { (Arc::new(StdoutLogSink), format!("{name} -> ")) } }; - Ok(Some(StreamedLog::new(self.log(), sink, prefix, from_start))) + Ok(Some(StreamedLog::new(self.log(), sink, prefix, since))) + } + + /// Waits for the run to finish like [`wait_for_finish`](Self::wait_for_finish), redirecting + /// its log meanwhile, the way `call()` of an Actor or a task does. + /// + /// A redirection that cannot be set up is reported on the standard error and the run is + /// waited for without it, since the run has already started and the caller has to get it. One + /// that ends early on an error is reported to the log sink. + pub(crate) async fn wait_for_finish_with_log( + &self, + wait_secs: Option, + log: LogRedirect, + ) -> ApifyClientResult { + let mut streamed_log = self + .get_streamed_log(StreamedLogOptions { + to_log: log, + since: None, + }) + .await + .unwrap_or_else(|error| { + eprintln!("Log redirection could not start: {error}"); + None + }); + if let Some(streamed_log) = streamed_log.as_mut() { + // A redirection that was just created is not started yet, so this cannot fail. + let _ = streamed_log.start(); + } + let finished = self.wait_for_finish(wait_secs).await; + if let Some(streamed_log) = streamed_log.as_mut() { + if let Err(error) = streamed_log.stop().await { + streamed_log.warn(&error); + } + } + finished } } diff --git a/src/clients/store_collection.rs b/src/clients/store_collection.rs index 13d3d9f..06f5077 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -1,9 +1,9 @@ -//! Client for browsing the Apify Store (`/v2/store`). +//! Client for browsing and searching the Apify Store (`/v2/store`). use crate::clients::base::{list_resource, ResourceContext}; use crate::clients::pagination::{list_iterator, ListIterator}; use crate::common::{PaginationList, QueryParams}; -use crate::error::ApifyClientResult; +use crate::error::{ApifyClientError, ApifyClientResult}; use crate::http_client::HttpClient; use crate::models::ActorStoreListItem; use crate::timeouts::Timeout; @@ -15,30 +15,31 @@ use crate::timeouts::Timeout; /// from the API transparently until the listing is exhausted. pub type StoreActorIterator = ListIterator; -/// Options for searching the Apify Store. +/// Options for listing the Apify Store with [`StoreCollectionClient::list`] and +/// [`StoreCollectionClient::iterate`]. The Actors come in Store order, which the API has no option +/// to change. To find Actors by a text query, use [`StoreCollectionClient::search`]. #[derive(Debug, Default, Clone)] pub struct StoreListOptions { /// Number of items to skip. pub offset: Option, - /// Item limit. Its meaning depends on the method: for [`StoreCollectionClient::list`] it is a - /// single page's size (the maximum items that one call returns); for + /// Item limit. The default and the maximum are 1000. With `include_input_schema`, they are + /// 10. Its meaning depends on the method: for [`StoreCollectionClient::list`] it is a single + /// page's size (the maximum items that one call returns); for /// [`StoreCollectionClient::iterate`] it is a cap on the *total* number of items yielded across /// all pages. See each method's docs. pub limit: Option, - /// Full-text search query. - pub search: Option, - /// Sort key (e.g. `popularity`, `newest`). - pub sort_by: Option, - /// Filter by category. + /// Filter by category. Accepts one or more category IDs separated by commas, case-insensitive + /// (for example `AI_AND_ML`). An Actor must match all of the listed categories. An unknown + /// category makes the API answer with a `400` error. pub category: Option, /// Filter by owner username. pub username: Option, /// Filter by pricing model: `FREE`, `PRICE_PER_DATASET_ITEM` or `PAY_PER_EVENT`. pub pricing_model: Option, - /// Include Actors that the current user cannot run (e.g. needing a missing integration). + /// By default, results exclude Actors that are not safe to run automatically, such as Actors + /// from developers who have not passed KYC or full-permission Actors without a large user + /// base. Set to `true` to bypass this safety filtering and include all Actors. pub include_unrunnable_actors: Option, - /// Filter to Actors that allow agentic (x402/Skyfire) users. - pub allows_agentic_users: Option, /// Response format requested from the API (`full` or `agent`, the API default is `full`). pub response_format: Option, /// If `true`, each Actor in the results includes an `inputSchema` field with a compact version @@ -47,7 +48,50 @@ pub struct StoreListOptions { pub include_input_schema: Option, } -/// Client for the Apify Store. +/// Options of [`StoreCollectionClient::search`]. There is no `offset`, as the API ignores it for a +/// search, and no `sort_by`, as the API ignores that too. +#[derive(Debug, Default, Clone)] +pub struct StoreSearchOptions { + /// Text to search for. It can't be an empty string, since the API answers an empty search with + /// the Store listing. + pub search: String, + /// Maximum number of Actors to return. The API returns at most 100 Actors for a search, which + /// is also the default, and reduces a larger value to 100. With `include_input_schema`, the + /// default and the maximum are 10. + pub limit: Option, + /// Filter by category, see [`StoreListOptions::category`]. + pub category: Option, + /// Filter by owner username. + pub username: Option, + /// Filter by pricing model: `FREE`, `PRICE_PER_DATASET_ITEM` or `PAY_PER_EVENT`. + pub pricing_model: Option, + /// Include the Actors that are not safe to run automatically, see + /// [`StoreListOptions::include_unrunnable_actors`]. + pub include_unrunnable_actors: Option, + /// Response format requested from the API (`full` or `agent`, the API default is `full`). + pub response_format: Option, + /// If `true`, each Actor in the results includes a compact `inputSchema` field, see + /// [`StoreListOptions::include_input_schema`]. + pub include_input_schema: Option, +} + +/// The single page of results that [`StoreCollectionClient::search`] returns. +#[derive(Debug, Clone)] +pub struct StoreSearchResult { + /// The Actors matching the query, best match first. + pub items: Vec, + /// The maximum number of Actors the API allowed in this result: the requested `limit`, or the + /// API's maximum when no limit or a larger one was requested. With `items.len()` equal to it, + /// more Actors may match the query than were returned. + pub limit: i64, +} + +/// Client for browsing and searching the Apify Store. +/// +/// The API serves the Store in two ways, and this client has one method for each: +/// - [`list`](Self::list) and [`iterate`](Self::iterate) browse the whole Store in Store order, +/// page by page. +/// - [`search`](Self::search) returns the Actors that match a query best, as a single page. #[derive(Debug, Clone)] pub struct StoreCollectionClient { ctx: ResourceContext, @@ -62,7 +106,9 @@ impl StoreCollectionClient { } } - /// Lists Actors from the Apify Store matching the given options. + /// Lists Actors from the Apify Store, ordered by their position in the Store. + /// + /// To find Actors by a text query, use [`search`](Self::search) instead. /// /// Awaiting once returns a single page; use [`StoreCollectionClient::iterate`] to lazily /// iterate across pages. @@ -70,7 +116,16 @@ impl StoreCollectionClient { &self, options: StoreListOptions, ) -> ApifyClientResult> { - let params = self.build_params(&options); + let mut params = QueryParams::new(); + params + .add_int("offset", options.offset) + .add_int("limit", options.limit) + .add_str("category", options.category) + .add_str("username", options.username) + .add_str("pricingModel", options.pricing_model) + .add_bool("includeUnrunnableActors", options.include_unrunnable_actors) + .add_str("responseFormat", options.response_format) + .add_bool("includeInputSchema", options.include_input_schema); list_resource(&self.ctx, None, ¶ms, Timeout::Medium).await } @@ -87,20 +142,66 @@ impl StoreCollectionClient { list_iterator!(self, options, list) } - fn build_params(&self, options: &StoreListOptions) -> QueryParams { + /// Searches the Apify Store and returns the Actors that match the query best, ordered by + /// relevance. + /// + /// The API answers a search with a single page of at most 100 Actors. There is no next page + /// and no way to skip results, and the API does not report how many Actors match the query in + /// total. A result holding as many Actors as [`StoreSearchResult::limit`] can therefore be cut + /// off: narrow it down with a more specific query or with the `category`, `username`, and + /// `pricing_model` options. To go through the whole Store, use [`list`](Self::list) or + /// [`iterate`](Self::iterate). + /// + /// Fails with [`ApifyClientError::InvalidArgument`] when `options.search` is empty. + /// + /// # Example + /// ```no_run + /// use apify_client::clients::store_collection::StoreSearchOptions; + /// use apify_client::ApifyClient; + /// + /// # async fn run() -> Result<(), Box> { + /// let client = ApifyClient::new("my-api-token"); + /// let result = client + /// .store() + /// .search(StoreSearchOptions { + /// search: "instagram posts".to_string(), + /// limit: Some(10), + /// ..Default::default() + /// }) + /// .await?; + /// for actor in result.items { + /// println!("{:?}", actor.name); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn search( + &self, + options: StoreSearchOptions, + ) -> ApifyClientResult { + if options.search.is_empty() { + return Err(ApifyClientError::InvalidArgument( + "`search` must not be empty: the API answers an empty search with the Store listing; use `list` to browse the Store".to_string(), + )); + } let mut params = QueryParams::new(); params - .add_int("offset", options.offset) + .add_str("search", Some(options.search)) .add_int("limit", options.limit) - .add_str("search", options.search.clone()) - .add_str("sortBy", options.sort_by.clone()) - .add_str("category", options.category.clone()) - .add_str("username", options.username.clone()) - .add_str("pricingModel", options.pricing_model.clone()) + .add_str("category", options.category) + .add_str("username", options.username) + .add_str("pricingModel", options.pricing_model) .add_bool("includeUnrunnableActors", options.include_unrunnable_actors) - .add_bool("allowsAgenticUsers", options.allows_agentic_users) - .add_str("responseFormat", options.response_format.clone()) + .add_str("responseFormat", options.response_format) .add_bool("includeInputSchema", options.include_input_schema); - params + let page: PaginationList = + list_resource(&self.ctx, None, ¶ms, Timeout::Medium).await?; + // The response has the shape of a listing page, but a search fills its `total` and `count` + // with the number of Actors returned and its `offset` with zero, whatever the query + // matches. They are left out, as they would read as the number of matches. + Ok(StoreSearchResult { + items: page.items, + limit: page.limit, + }) } } diff --git a/src/clients/streamed_log.rs b/src/clients/streamed_log.rs index f3f25d2..65304d6 100644 --- a/src/clients/streamed_log.rs +++ b/src/clients/streamed_log.rs @@ -3,12 +3,13 @@ //! [`StreamedLog`] follows the log //! of a run in a background task, splits it into messages at the timestamps the Actor's log lines //! start with, and hands every message to a [`LogSink`]. [`ActorClient::call`] uses it to redirect -//! the log of the run it waits for. +//! the log of the run it waits for, and so does [`TaskClient::call`]. //! //! [`ActorClient::call`]: crate::clients::actor::ActorClient::call +//! [`TaskClient::call`]: crate::clients::task::TaskClient::call use std::fmt; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use chrono::{DateTime, Utc}; @@ -18,6 +19,7 @@ use tokio::task::JoinHandle; use crate::clients::log::{LogClient, LogOptions}; use crate::error::{ApifyClientError, ApifyClientResult}; +use crate::http_client::is_error_retryable; /// How long to wait before reopening the log stream of a run that has not logged anything yet. /// The API serves such a log as an empty stream that ends at once. The pause doubles up to @@ -25,6 +27,10 @@ use crate::error::{ApifyClientError, ApifyClientResult}; const EMPTY_LOG_STREAM_RETRY: Duration = Duration::from_millis(500); /// The longest pause between two reopenings of an empty log stream. const EMPTY_LOG_STREAM_MAX_RETRY: Duration = Duration::from_secs(5); +/// How long to wait before reopening a log stream that broke off before its end. A stream that has +/// carried no data for several minutes is cut off even though the run goes on. The stream of a +/// finished log ends without an error. +const BROKEN_LOG_STREAM_REOPEN: Duration = Duration::from_secs(1); /// How long [`StreamedLog::stop`] lets the lines already in flight arrive before it cuts the /// log stream. const STOP_GRACE: Duration = Duration::from_secs(1); @@ -71,10 +77,11 @@ impl LogSink for StdoutLogSink { } } -/// Where the log of a run goes: the `log` option of [`ActorClient::call`] and the `to_log` option -/// of [`RunClient::get_streamed_log`]. +/// Where the log of a run goes: the `log` option of [`ActorClient::call`] and +/// [`TaskClient::call`], and the `to_log` option of [`RunClient::get_streamed_log`]. /// /// [`ActorClient::call`]: crate::clients::actor::ActorClient::call +/// [`TaskClient::call`]: crate::clients::task::TaskClient::call /// [`RunClient::get_streamed_log`]: crate::clients::run::RunClient::get_streamed_log #[derive(Clone, Default)] pub enum LogRedirect { @@ -106,23 +113,16 @@ impl fmt::Debug for LogRedirect { } /// Options of [`RunClient::get_streamed_log`](crate::clients::run::RunClient::get_streamed_log). -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct StreamedLogOptions { /// Where to redirect the log. [`LogRedirect::Disabled`] makes `get_streamed_log` return /// `None`. pub to_log: LogRedirect, - /// Redirect the log from its beginning. When `false`, messages stamped before the call are - /// dropped. Defaults to `true`. - pub from_start: bool, -} - -impl Default for StreamedLogOptions { - fn default() -> Self { - Self { - to_log: LogRedirect::Default, - from_start: true, - } - } + /// Redirect only the messages stamped at this time or later. By default, the whole log is + /// redirected. Redirecting only the recent messages can be useful for long-running Actors, + /// such as Server Actors. To continue a redirection that was interrupted, pass + /// [`StreamedLog::last_redirected_at`] plus one millisecond. + pub since: Option>, } /// What the redirection task is asked to do. @@ -147,12 +147,19 @@ struct Running { /// [`start`](Self::start) spawns a task that follows the log, and [`stop`](Self::stop) ends it. /// Dropping a started `StreamedLog` cancels the task without reading the rest of the log. /// +/// When the log stream is cut off while the run is still going, for example after the run has +/// logged nothing for several minutes, the stream is reopened and the redirection resumes after +/// the last redirected message. The API cannot continue a stream from a given point, so the +/// reopen downloads the whole log again. The lines of a message that arrive only after the break +/// (for example the rest of a stack trace) are not redirected. +/// /// A line that continues a message in a later chunk is emitted as a message of its own. pub struct StreamedLog { log: LogClient, sink: Arc, prefix: String, - relevancy_limit: Option>, + since: Option>, + last_redirected_at: Arc>>>, running: Option, } @@ -170,17 +177,28 @@ impl StreamedLog { log: LogClient, sink: Arc, prefix: String, - from_start: bool, + since: Option>, ) -> Self { Self { log, sink, prefix, - relevancy_limit: (!from_start).then(Utc::now), + since, + last_redirected_at: Arc::default(), running: None, } } + /// The timestamp of the last redirected message, or `None` if nothing has been redirected + /// yet. Pass it plus one millisecond as [`StreamedLogOptions::since`] to continue the + /// redirection after a restart. + pub fn last_redirected_at(&self) -> Option> { + *self + .last_redirected_at + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + /// Reports a failure of the redirection to the sink of the log, without the prefix, so the log /// does not just stop without a trace. pub(crate) fn warn(&self, error: &ApifyClientError) { @@ -201,7 +219,7 @@ impl StreamedLog { self.log.clone(), self.sink.clone(), self.prefix.clone(), - self.relevancy_limit, + MessageSplitter::new(self.since, self.last_redirected_at.clone()), receiver, )); self.running = Some(Running { control, task }); @@ -209,9 +227,10 @@ impl StreamedLog { } /// Stops redirecting the log. Waits up to one second for the lines in flight, then cuts the - /// log stream. If the stream has delivered nothing yet, reads the whole log in one request - /// instead. Fails with [`ApifyClientError::InvalidArgument`] when the redirection is not - /// started, and with the error that ended the redirection early, if there was one. + /// log stream. If the stream has delivered nothing yet, or broke off and was not replayed up to + /// the last redirected message, reads the whole log in one request instead. Fails with + /// [`ApifyClientError::InvalidArgument`] when the redirection is not started, and with the + /// error that ended the redirection early, if there was one. pub async fn stop(&mut self) -> ApifyClientResult<()> { let Some(Running { control, mut task }) = self.running.take() else { return Err(ApifyClientError::InvalidArgument( @@ -256,28 +275,40 @@ async fn stopped(mut control: watch::Receiver) { } /// The redirection task. Returns the error that ended it early. +/// +/// The API serves the log of a run that has not logged anything yet as an empty stream that ends +/// at once, so the stream is reopened until the first bytes arrive. A stream that broke off after +/// it had delivered data is reopened too. A stream that ends without an error after delivering +/// data carried the whole log of a finished run. async fn redirect( log: LogClient, sink: Arc, prefix: String, - relevancy_limit: Option>, + mut messages: MessageSplitter, control: watch::Receiver, ) -> Option { - let mut messages = MessageSplitter::new(relevancy_limit); let emit = |message: &str| sink.line(&format!("{prefix}{message}")); let raw = LogOptions { raw: Some(true), download: None, }; let mut retry = EMPTY_LOG_STREAM_RETRY; - // The API serves the log of a run that has not logged anything yet as an empty stream that - // ends at once, so reopen it until the first bytes arrive. Once stopped, read the whole log - // in one request instead. + let mut received_any = false; loop { if is_stopping(&control) { - match log.get_bytes_with_options(raw.clone()).await { - Ok(content) => messages.feed(&content.unwrap_or_default(), &emit), - Err(error) => return Some(error), + // A stream opened this late would be cut after its first chunk, so if no stream has + // delivered anything yet, read the whole log in one request instead. The same goes + // for a stream that broke off and has not been replayed up to the last redirected + // message: the rest of the log is still unread. + let replay_pending = messages.replay_pending(); + if !received_any || replay_pending { + if replay_pending { + messages.prepare_reopen(); + } + match log.get_bytes_with_options(raw.clone()).await { + Ok(content) => messages.feed(&content.unwrap_or_default(), &emit), + Err(error) => return Some(error), + } } break; } @@ -295,7 +326,7 @@ async fn redirect( continue; } futures_util::pin_mut!(stream); - let mut received_any = false; + let mut broke_off = false; loop { let item = tokio::select! { item = stream.next() => item, @@ -311,20 +342,37 @@ async fn redirect( } Some(Err(_)) if is_stopping(&control) => break, Some(Err(error)) => { + if received_any && is_error_retryable(&error) && messages.replay_caught_up() { + messages.prepare_reopen(); + broke_off = true; + break; + } + // Either the error is final, or the reopened stream broke off again before it + // reached the last redirected message, so reopening would not get further. messages.finish(&emit); return Some(error); } None => break, } } - if received_any { + if received_any && !broke_off { + if is_stopping(&control) && messages.replay_pending() { + // The stop cut a replaying stream short, so read the rest of the log. + continue; + } break; } + let pause = if received_any { + BROKEN_LOG_STREAM_REOPEN + } else { + let pause = retry; + retry = (retry * 2).min(EMPTY_LOG_STREAM_MAX_RETRY); + pause + }; tokio::select! { - () = tokio::time::sleep(retry) => {} + () = tokio::time::sleep(pause) => {} () = stopped(control.clone()) => {} } - retry = (retry * 2).min(EMPTY_LOG_STREAM_MAX_RETRY); } // Whatever is left may be incomplete, or the last line of the log without a line break. messages.finish(&emit); @@ -337,18 +385,38 @@ struct MessageSplitter { /// The incomplete last line of the bytes fed so far, led by the line break before it. remainder: Vec, /// Messages stamped before this are dropped. - relevancy_limit: Option>, + since: Option>, /// Whether the message in progress at the end of the previous batch was relevant, so the /// lines that continue it are too. relevant: bool, + /// The timestamp of the last redirected message, shared with the [`StreamedLog`]. + shared_last_redirected_at: Arc>>>, + last_redirected_at: Option>, + /// How many redirected messages carry `last_redirected_at`. Several can share a millisecond. + redirected_at_last_timestamp: usize, + /// A reopened stream replays the messages before `replayed_until`, and the first + /// `replay_skip_count` messages stamped exactly at it. + replayed_until: Option>, + replay_skip_count: usize, + /// Set when a stream broke off, until a message the stream before it did not carry arrives. + awaiting_replay: bool, } impl MessageSplitter { - fn new(relevancy_limit: Option>) -> Self { + fn new( + since: Option>, + shared_last_redirected_at: Arc>>>, + ) -> Self { Self { remainder: Vec::new(), - relevancy_limit, - relevant: relevancy_limit.is_none(), + since, + relevant: since.is_none(), + shared_last_redirected_at, + last_redirected_at: None, + redirected_at_last_timestamp: 0, + replayed_until: None, + replay_skip_count: 0, + awaiting_replay: false, } } @@ -369,13 +437,35 @@ impl MessageSplitter { self.feed(&[], emit); } + /// Whether the current stream got at least as far as the stream before it. + fn replay_caught_up(&self) -> bool { + self.replayed_until.is_none() || self.replay_skip_count == 0 + } + + /// Whether a stream broke off and the one after it has not yet got past the last redirected + /// message, so the log after that message has not been read. + fn replay_pending(&self) -> bool { + self.awaiting_replay + } + + /// Makes the next stream redirect only the messages after the last redirected one, since the + /// API replays the log from its start. The incomplete last line is dropped, as the replay + /// delivers it again. + fn prepare_reopen(&mut self) { + self.replayed_until = self.last_redirected_at; + self.replay_skip_count = self.redirected_at_last_timestamp; + self.awaiting_replay = true; + self.remainder.clear(); + self.relevant = self.replayed_until.is_none() && self.since.is_none(); + } + fn emit_messages(&mut self, text: &str, emit: &dyn Fn(&str)) { let mut message = String::new(); for line in text.split('\n') { if starts_with_timestamp(line) { self.emit_message(&message, emit); message.clear(); - self.relevant = self.is_relevant(&line[..TIMESTAMP_LEN]); + self.relevant = self.accept(&line[..TIMESTAMP_LEN]); } if !message.is_empty() { message.push('\n'); @@ -392,14 +482,47 @@ impl MessageSplitter { } } - fn is_relevant(&self, timestamp: &str) -> bool { - match ( - self.relevancy_limit, - DateTime::parse_from_rfc3339(timestamp), - ) { - (Some(limit), Ok(time)) => time >= limit, - _ => true, + /// Whether the message stamped `timestamp` is to be redirected, and if it is, remembers it as + /// the last redirected one. + fn accept(&mut self, timestamp: &str) -> bool { + let Ok(time) = DateTime::parse_from_rfc3339(timestamp) else { + return true; + }; + let time = time.with_timezone(&Utc); + if self.is_replayed(time) { + return false; + } + self.awaiting_replay = false; + if self.since.is_some_and(|since| time < since) { + return false; + } + if self.last_redirected_at == Some(time) { + self.redirected_at_last_timestamp += 1; + } else { + self.last_redirected_at = Some(time); + self.redirected_at_last_timestamp = 1; + *self + .shared_last_redirected_at + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(time); + } + true + } + + /// Whether a message of a reopened stream was already redirected before the stream broke off. + fn is_replayed(&mut self, time: DateTime) -> bool { + let Some(until) = self.replayed_until else { + return false; + }; + if time < until { + return true; } + if time == until && self.replay_skip_count > 0 { + self.replay_skip_count -= 1; + return true; + } + self.replayed_until = None; + false } } @@ -421,10 +544,14 @@ mod tests { use super::*; use std::cell::RefCell; - fn split(limit: Option>, chunks: &[&str], finish: bool) -> Vec { + fn splitter(since: Option>) -> MessageSplitter { + MessageSplitter::new(since, Arc::default()) + } + + fn split(since: Option>, chunks: &[&str], finish: bool) -> Vec { let out = RefCell::new(Vec::new()); let emit = |m: &str| out.borrow_mut().push(m.to_string()); - let mut splitter = MessageSplitter::new(limit); + let mut splitter = splitter(since); for chunk in chunks { splitter.feed(chunk.as_bytes(), &emit); } @@ -442,7 +569,7 @@ mod tests { crate::ApifyClient::new("token").log("run"), Arc::new(move |line: &str| sink.lock().unwrap().push(line.to_string())), "actor runId:run -> ".to_string(), - true, + None, ); streamed.warn(&ApifyClientError::Http("it broke".to_string())); assert_eq!( @@ -491,7 +618,7 @@ mod tests { } #[test] - fn messages_stamped_before_the_limit_are_dropped() { + fn messages_stamped_before_since_are_dropped() { let limit = DateTime::parse_from_rfc3339("2024-01-01T00:00:01.000Z") .unwrap() .with_timezone(&Utc); @@ -502,6 +629,82 @@ mod tests { ); } + /// Feeds `chunks` to a splitter in turn, reopening it (as a broken stream does) before each + /// chunk after the first, and returns what it emitted and its last redirected timestamp. + fn split_with_reopens(chunks: &[&str]) -> (Vec, Option>) { + let out = RefCell::new(Vec::new()); + let emit = |m: &str| out.borrow_mut().push(m.to_string()); + let mut splitter = splitter(None); + for (index, chunk) in chunks.iter().enumerate() { + if index > 0 { + assert!(splitter.replay_caught_up()); + splitter.prepare_reopen(); + } + splitter.feed(chunk.as_bytes(), &emit); + } + splitter.finish(&emit); + (out.into_inner(), splitter.last_redirected_at) + } + + #[test] + fn a_reopened_stream_redirects_only_the_messages_after_the_last_redirected_one() { + let first = "2024-01-01T00:00:00.000Z a\n2024-01-01T00:00:01.000Z b\n2024-01-01T00:00:02.000Z c\n2024-01-01T00:00:03.000Z incompl"; + let replay = "2024-01-01T00:00:00.000Z a\n2024-01-01T00:00:01.000Z b\n2024-01-01T00:00:02.000Z c\n2024-01-01T00:00:03.000Z incomplete\n2024-01-01T00:00:04.000Z d\n"; + let (out, last) = split_with_reopens(&[first, replay]); + assert_eq!( + out, + vec![ + "2024-01-01T00:00:00.000Z a", + "2024-01-01T00:00:01.000Z b", + "2024-01-01T00:00:02.000Z c", + "2024-01-01T00:00:03.000Z incomplete", + "2024-01-01T00:00:04.000Z d", + ] + ); + assert_eq!( + last, + Some( + DateTime::parse_from_rfc3339("2024-01-01T00:00:04.000Z") + .unwrap() + .with_timezone(&Utc) + ) + ); + } + + #[test] + fn messages_sharing_a_millisecond_are_not_redirected_twice_by_a_reopen() { + let first = + "2024-01-01T00:00:00.000Z a\n2024-01-01T00:00:00.000Z b\n2024-01-01T00:00:01.000Z c\n"; + let replay = "2024-01-01T00:00:00.000Z a\n2024-01-01T00:00:00.000Z b\n2024-01-01T00:00:01.000Z c\n2024-01-01T00:00:01.000Z d\n"; + let (out, _) = split_with_reopens(&[first, replay]); + assert_eq!( + out, + vec![ + "2024-01-01T00:00:00.000Z a", + "2024-01-01T00:00:00.000Z b", + "2024-01-01T00:00:01.000Z c", + "2024-01-01T00:00:01.000Z d", + ] + ); + } + + #[test] + fn a_reopened_stream_that_falls_short_of_the_last_redirected_message_cannot_be_reopened_again() + { + let out = RefCell::new(Vec::new()); + let emit = |m: &str| out.borrow_mut().push(m.to_string()); + let mut splitter = splitter(None); + splitter.feed( + b"2024-01-01T00:00:00.000Z a\n2024-01-01T00:00:01.000Z b\n", + &emit, + ); + splitter.finish(&emit); + splitter.prepare_reopen(); + // The replay breaks off before it reaches `b`. + splitter.feed(b"2024-01-01T00:00:00.000Z a\n", &emit); + assert!(!splitter.replay_caught_up()); + } + #[test] fn lines_without_a_timestamp_continue_the_previous_message() { let out = split(None, &["2024-01-01T00:00:00.000Z a\n", "continued\n"], true); diff --git a/src/clients/task.rs b/src/clients/task.rs index 4744ef7..413c6c8 100644 --- a/src/clients/task.rs +++ b/src/clients/task.rs @@ -4,7 +4,7 @@ use serde::Serialize; use serde_json::Value; use crate::client::ApifyClient; -use crate::clients::actor::{ActorStartOptions, TaskStartOptions}; +use crate::clients::actor::{ActorStartOptions, TaskCallOptions, TaskStartOptions}; use crate::clients::base::{ delete_resource, get_resource, post_creating, update_resource, ResourceContext, }; @@ -115,34 +115,35 @@ impl TaskClient { .await } - /// Starts the task and waits (client-side polling) for it to finish. + /// Starts the task and waits (client-side polling) for it to finish, redirecting the log of + /// the run while it waits. /// - /// `wait_secs` controls the wait budget: - /// - `None` polls indefinitely until the run reaches a terminal state. - /// - `Some(n)` bounds the wait to roughly `n` seconds; if the run has not finished by - /// then, the **last fetched (still non-terminal) run is returned** rather than an - /// error. Check `status` / `is_terminal()` on the result when using `Some`. - /// - /// Time spent retrying under [`TaskStartOptions::wait_for_resources`] does not count - /// toward `wait_secs`, since that budget only starts once the run has actually started. + /// See [`TaskCallOptions`] for the wait budget and the log redirection. The log goes to the + /// standard output unless `options.log` says otherwise. A redirection that ends early on an + /// error does not fail the call; a `Log redirection stopped due to error: ..` message goes to + /// the log sink instead. One that cannot be set up is reported on the standard error. /// /// Like [`ActorClient::call`](crate::clients::actor::ActorClient::call), the start request /// has no client-side timeout unless the client was given one with `with_timeout`, which - /// then applies to the polls as well. The log of the run is not redirected. + /// then applies to the polls as well. pub async fn call( &self, input: Option<&T>, - options: TaskStartOptions, - wait_secs: Option, + options: TaskCallOptions, ) -> ApifyClientResult { + let TaskCallOptions { + start, + wait_secs, + log, + } = options; let run = self - .start_with_tier(input, options, Timeout::NoTimeout) + .start_with_tier(input, start, Timeout::NoTimeout) .await?; let mut run_client = self.root.run(run.id); if let Some(timeout) = self.ctx.timeout { run_client = run_client.with_timeout(timeout); } - run_client.wait_for_finish(wait_secs).await + run_client.wait_for_finish_with_log(wait_secs, log).await } /// Fetches the task's saved input. diff --git a/src/http_client.rs b/src/http_client.rs index f531625..07a4c75 100644 --- a/src/http_client.rs +++ b/src/http_client.rs @@ -840,7 +840,7 @@ fn is_status_retryable(status: u16, retry_status_codes: Option<&[u16]>) -> bool /// Only transport failures (network errors and timeouts) are retried. Serialization errors, /// invalid arguments and API errors are not. -fn is_error_retryable(err: &ApifyClientError) -> bool { +pub(crate) fn is_error_retryable(err: &ApifyClientError) -> bool { matches!(err, ApifyClientError::Http(_) | ApifyClientError::Timeout) } diff --git a/src/lib.rs b/src/lib.rs index de05097..1bb536e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -77,7 +77,8 @@ pub use timeouts::Timeout; pub use version::{API_SPEC_VERSION, CLIENT_VERSION}; pub use clients::actor::{ - ActorBuildOptions, ActorCallOptions, ActorStartOptions, TaskStartOptions, WaitForResources, + ActorBuildOptions, ActorCallOptions, ActorStartOptions, TaskCallOptions, TaskStartOptions, + WaitForResources, }; pub use clients::actor_collection::ActorListOptions; pub use clients::actor_server::{ @@ -97,7 +98,9 @@ pub use clients::run::{ }; pub use clients::run_collection::RunListOptions; pub use clients::run_dataset_items::RunDatasetItemsIterator; -pub use clients::store_collection::{StoreActorIterator, StoreListOptions}; +pub use clients::store_collection::{ + StoreActorIterator, StoreListOptions, StoreSearchOptions, StoreSearchResult, +}; pub use clients::streamed_log::{ LogRedirect, LogSink, StdoutLogSink, StreamedLog, StreamedLogOptions, }; diff --git a/src/version.rs b/src/version.rs index f4f3b3f..c40304a 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-18T151559Z"; +pub const API_SPEC_VERSION: &str = "v2-2026-12-02T102104Z"; diff --git a/tests/store.rs b/tests/store.rs index 549fa0e..bec283a 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -2,7 +2,7 @@ mod common; -use apify_client::clients::store_collection::StoreListOptions; +use apify_client::clients::store_collection::{StoreListOptions, StoreSearchOptions}; /// Simple GET: listing Store Actors. #[tokio::test(flavor = "multi_thread")] @@ -58,3 +58,42 @@ async fn list_store_with_input_schema() { assert!(!page.items.is_empty(), "the Store lists Actors"); assert!(page.items.len() <= 3); } + +/// Simple GET: a search returns the best matching Actors as a single page of at most `limit`. +#[tokio::test(flavor = "multi_thread")] +async fn search_store() { + let client = require_client!(); + let result = client + .store() + .search(StoreSearchOptions { + search: "web scraper".to_string(), + limit: Some(5), + ..Default::default() + }) + .await + .expect("searching the store should succeed"); + assert!(!result.items.is_empty(), "the search finds Actors"); + assert!(result.items.len() <= 5); + assert_eq!(result.limit, 5, "the API reports the limit it applied"); +} + +/// A search takes the same filters as a listing, and the API reduces a `limit` above 100. +#[tokio::test(flavor = "multi_thread")] +async fn search_store_with_a_filter_and_a_large_limit() { + let client = require_client!(); + let result = client + .store() + .search(StoreSearchOptions { + search: "scraper".to_string(), + username: Some("apify".to_string()), + limit: Some(1000), + ..Default::default() + }) + .await + .expect("searching the store with a filter should succeed"); + assert!( + result.items.len() <= 100, + "a search returns at most 100 Actors" + ); + assert_eq!(result.limit, 100, "the API reduces the limit to 100"); +} diff --git a/tests/task.rs b/tests/task.rs index f6bc83d..29d314e 100644 --- a/tests/task.rs +++ b/tests/task.rs @@ -2,6 +2,7 @@ mod common; +use apify_client::TaskCallOptions; use serde_json::json; /// Simple GET: listing tasks. @@ -328,7 +329,13 @@ async fn task_webhooks_and_last_run() { let run = client .task(&task.id) - .call::(None, Default::default(), Some(120)) + .call::( + None, + TaskCallOptions { + wait_secs: Some(120), + ..Default::default() + }, + ) .await .expect("call the task"); diff --git a/tests/unit_call.rs b/tests/unit_call.rs index 297fba7..323210b 100644 --- a/tests/unit_call.rs +++ b/tests/unit_call.rs @@ -5,6 +5,7 @@ mod common; +use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -16,10 +17,12 @@ use apify_client::http_client::{ use apify_client::timeouts::NO_TIMEOUT; use apify_client::{ ActorBuildOptions, ActorCallOptions, ActorStartOptions, ApifyClient, ApifyClientError, - LogRedirect, StreamedLogOptions, TaskStartOptions, Timeout, + LogRedirect, StreamedLogOptions, TaskCallOptions, TaskStartOptions, Timeout, }; use async_trait::async_trait; +use chrono::Utc; use common::mock_backend::{client_with, MockBackend, MockOutcome}; +use futures_util::{Stream, StreamExt}; use serde_json::{json, Value}; const RUN_READY: &str = r#"{"data":{"id":"r1","actId":"a1","status":"READY"}}"#; @@ -37,6 +40,18 @@ fn call_options(wait_secs: Option) -> ActorCallOptions { } } +fn task_call_options(wait_secs: Option) -> TaskCallOptions { + TaskCallOptions { + wait_secs, + log: LogRedirect::Disabled, + ..Default::default() + } +} + +/// The chunks of one log stream, ending with an error if the last one is, and whether the stream +/// then stalls instead of ending. +type ScriptedStream = (Vec, ApifyClientError>>, bool); + type Route = dyn Fn(&HttpRequest, usize) -> Result + Send + Sync; /// A backend that answers by request, and records every request. @@ -45,6 +60,8 @@ struct RouteBackend { route: Box, /// Makes every log stream deliver its first line and then fail, and raises the flag. failing_log_stream: Option>, + /// The chunks of the next log streams, in order. Once they are used up, the route answers. + scripted_log_streams: Mutex>, } impl std::fmt::Debug for RouteBackend { @@ -64,6 +81,22 @@ impl RouteBackend { requests: Mutex::new(Vec::new()), route: Box::new(route), failing_log_stream: None, + scripted_log_streams: Mutex::new(Vec::new()), + }) + } + + fn with_scripted_log_streams( + streams: Vec, + route: impl Fn(&HttpRequest, usize) -> Result + + Send + + Sync + + 'static, + ) -> Arc { + Arc::new(Self { + requests: Mutex::new(Vec::new()), + route: Box::new(route), + failing_log_stream: None, + scripted_log_streams: Mutex::new(streams), }) } @@ -78,6 +111,7 @@ impl RouteBackend { requests: Mutex::new(Vec::new()), route: Box::new(route), failing_log_stream: Some(stream_failed), + scripted_log_streams: Mutex::new(Vec::new()), }) } @@ -108,6 +142,26 @@ impl HttpBackend for RouteBackend { &self, request: HttpRequest, ) -> Result { + if request.url.contains("stream=1") { + let scripted = { + let mut streams = self.scripted_log_streams.lock().unwrap(); + (!streams.is_empty()).then(|| streams.remove(0)) + }; + if let Some((chunks, stalls)) = scripted { + self.requests.lock().unwrap().push(request); + let chunks = futures_util::stream::iter(chunks); + let body: Pin + Send>> = if stalls { + Box::pin(chunks.chain(futures_util::stream::pending())) + } else { + Box::pin(chunks) + }; + return Ok(StreamingHttpResponse { + status: 200, + headers: Default::default(), + body, + }); + } + } let failing = self .failing_log_stream .as_ref() @@ -124,7 +178,9 @@ impl HttpBackend for RouteBackend { stream_failed.store(true, Ordering::SeqCst); let chunks: Vec, ApifyClientError>> = vec![ Ok(b"2024-01-01T00:00:00.000Z first\n".to_vec()), - Err(ApifyClientError::Http("the stream broke".to_string())), + Err(ApifyClientError::InvalidResponse( + "the stream broke".to_string(), + )), ]; Ok(StreamingHttpResponse { status: 200, @@ -178,7 +234,7 @@ async fn call_does_not_abort_and_retry_a_slow_start() { let run = client .task("t") - .call::(None, TaskStartOptions::default(), None) + .call::(None, task_call_options(None)) .await .unwrap(); assert_eq!(run.status.as_deref(), Some("SUCCEEDED")); @@ -233,7 +289,7 @@ async fn call_applies_the_timeout_of_the_client_to_the_start_and_the_polls() { client .task("t") .with_timeout(seven) - .call::(None, TaskStartOptions::default(), Some(5)) + .call::(None, task_call_options(Some(5))) .await .unwrap(); assert_eq!(backend.timeouts(), vec![Duration::from_secs(7); 4]); @@ -408,7 +464,7 @@ async fn a_streamed_log_redirects_the_messages_of_the_log_to_the_sink() { .run("r1") .get_streamed_log(StreamedLogOptions { to_log, - from_start: true, + since: None, }) .await .unwrap() @@ -453,7 +509,7 @@ async fn the_default_redirection_prefixes_the_messages_with_the_actor_and_the_ru .run("r1") .get_streamed_log(StreamedLogOptions { to_log: LogRedirect::Disabled, - from_start: true, + since: None, }) .await .unwrap(); @@ -471,7 +527,7 @@ async fn an_empty_log_stream_is_reopened() { .run("r1") .get_streamed_log(StreamedLogOptions { to_log, - from_start: true, + since: None, }) .await .unwrap() @@ -495,7 +551,7 @@ async fn stopping_before_the_first_bytes_reads_the_whole_log() { .run("r1") .get_streamed_log(StreamedLogOptions { to_log, - from_start: true, + since: None, }) .await .unwrap() @@ -512,14 +568,14 @@ async fn stopping_before_the_first_bytes_reads_the_whole_log() { } #[tokio::test] -async fn from_start_false_drops_the_messages_stamped_before_the_call() { +async fn since_drops_the_messages_stamped_before_it() { let client = client_on(log_backend(0), 0); let (messages, to_log) = collecting_sink(); let mut streamed = client .run("r1") .get_streamed_log(StreamedLogOptions { to_log, - from_start: false, + since: Some(Utc::now()), }) .await .unwrap() @@ -596,7 +652,7 @@ async fn a_failing_log_stream_is_reported_by_stop_and_does_not_fail_call() { .run("r1") .get_streamed_log(StreamedLogOptions { to_log, - from_start: true, + since: None, }) .await .unwrap() @@ -604,7 +660,10 @@ async fn a_failing_log_stream_is_reported_by_stop_and_does_not_fail_call() { streamed.start().unwrap(); tokio::time::sleep(Duration::from_millis(100)).await; let error = streamed.stop().await.expect_err("the stream broke"); - assert!(matches!(error, ApifyClientError::Http(_)), "{error:?}"); + assert!( + matches!(error, ApifyClientError::InvalidResponse(_)), + "{error:?}" + ); assert_eq!( *messages.lock().unwrap(), vec!["2024-01-01T00:00:00.000Z first".to_string()] @@ -636,8 +695,245 @@ async fn a_failing_log_stream_is_reported_by_stop_and_does_not_fail_call() { *messages.lock().unwrap(), vec![ "2024-01-01T00:00:00.000Z first".to_string(), - "Log redirection stopped due to error: HTTP transport error: the stream broke" - .to_string() + "Log redirection stopped due to error: Invalid response: the stream broke".to_string() + ] + ); +} + +/// A task call redirects the log of the run like an Actor call does. +#[tokio::test] +async fn a_task_call_redirects_the_log_of_the_run_to_the_sink() { + let backend = log_backend(0); + let client = client_on(backend.clone(), 0); + let (messages, log) = collecting_sink(); + let run = client + .task("t") + .call::( + None, + TaskCallOptions { + start: TaskStartOptions::default(), + log, + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!(run.status.as_deref(), Some("SUCCEEDED")); + assert_eq!( + *messages.lock().unwrap(), + vec![ + "2024-01-01T00:00:00.000Z first\n trace".to_string(), + "2024-01-01T00:00:01.000Z second".to_string() + ] + ); +} + +/// The log goes to the standard output by default, which costs a request for the run and one +/// for its Actor; `LogRedirect::Disabled` makes none of them. +#[tokio::test] +async fn a_task_call_redirects_by_default_and_not_when_disabled() { + let backend = log_backend(0); + let client = client_on(backend.clone(), 0); + client + .task("t") + .call::(None, TaskCallOptions::default()) + .await + .unwrap(); + // The run finishes at once, so the log is read in one request or streamed. + assert!(backend.count(HttpMethod::Get, "/log") >= 1); + assert_eq!(backend.count(HttpMethod::Get, "/actors/a1"), 1); + + let backend = log_backend(0); + let client = client_on(backend.clone(), 0); + client + .task("t") + .call::(None, task_call_options(None)) + .await + .unwrap(); + assert_eq!(backend.count(HttpMethod::Get, "/log"), 0); +} + +/// A redirection that cannot be set up does not fail the call: the run is waited for without it. +#[tokio::test] +async fn a_task_call_still_returns_the_run_when_the_redirection_cannot_be_set_up() { + let backend = RouteBackend::new(|request, _| { + if request.method == HttpMethod::Post { + return response(201, RUN_READY); + } + if request.url.contains("/actor-runs/r1") && !request.url.contains("/log") { + // The default redirection fetches the run once to name its messages, and so does + // the wait. + return response(200, RUN_DONE); + } + response(500, r#"{"error":{"message":"down"}}"#) + }); + let client = client_on(backend, 0); + let run = client + .task("t") + .call::(None, TaskCallOptions::default()) + .await + .unwrap(); + assert_eq!(run.status.as_deref(), Some("SUCCEEDED")); +} + +fn timestamp(text: &str) -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339(text) + .unwrap() + .with_timezone(&Utc) +} + +/// A log stream that is cut off while the run goes on is reopened. The API replays the whole log, +/// and the messages that were already redirected are not redirected again. +#[tokio::test(start_paused = true)] +async fn a_broken_log_stream_is_reopened_and_resumes_after_the_last_redirected_message() { + let broken = vec![ + Ok(b"2024-01-01T00:00:00.000Z first\n trace\n2024-01-01T00:00:01.000Z sec".to_vec()), + Err(ApifyClientError::Http("connection reset".to_string())), + ]; + // The reopened stream carries the whole log. + let backend = RouteBackend::with_scripted_log_streams(vec![(broken, false)], |request, _| { + if request.url.contains("stream=1") { + return response(200, &format!("{LOG}2024-01-01T00:00:02.000Z third\n")); + } + response(200, RUN_DONE) + }); + let client = client_on(backend.clone(), 0); + let (messages, to_log) = collecting_sink(); + let mut streamed = client + .run("r1") + .get_streamed_log(StreamedLogOptions { + to_log, + since: None, + }) + .await + .unwrap() + .unwrap(); + assert_eq!(streamed.last_redirected_at(), None); + streamed.start().unwrap(); + tokio::time::sleep(Duration::from_secs(10)).await; + streamed.stop().await.unwrap(); + + assert_eq!( + *messages.lock().unwrap(), + vec![ + "2024-01-01T00:00:00.000Z first\n trace".to_string(), + "2024-01-01T00:00:01.000Z second".to_string(), + "2024-01-01T00:00:02.000Z third".to_string(), + ] + ); + assert_eq!(backend.count(HttpMethod::Get, "stream=1"), 2); + assert_eq!( + streamed.last_redirected_at(), + Some(timestamp("2024-01-01T00:00:02.000Z")) + ); +} + +/// `since` starts the redirection at a given time, so a redirection can continue after a restart. +#[tokio::test] +async fn since_redirects_the_messages_stamped_at_that_time_or_later() { + let client = client_on(log_backend(0), 0); + let (messages, to_log) = collecting_sink(); + let mut streamed = client + .run("r1") + .get_streamed_log(StreamedLogOptions { + to_log, + since: Some(timestamp("2024-01-01T00:00:01.000Z")), + }) + .await + .unwrap() + .unwrap(); + streamed.start().unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + streamed.stop().await.unwrap(); + assert_eq!( + *messages.lock().unwrap(), + vec!["2024-01-01T00:00:01.000Z second".to_string()] + ); + assert_eq!( + streamed.last_redirected_at(), + Some(timestamp("2024-01-01T00:00:01.000Z")) + ); +} + +/// Stopping while a broken stream is waiting to be reopened reads the rest of the log in one +/// request, so the messages logged after the break are not lost. +#[tokio::test(start_paused = true)] +async fn stopping_after_a_broken_log_stream_reads_the_rest_of_the_log() { + let broken = vec![ + Ok(b"2024-01-01T00:00:00.000Z first\n".to_vec()), + Err(ApifyClientError::Http("connection reset".to_string())), + ]; + let backend = RouteBackend::with_scripted_log_streams(vec![(broken, false)], |_, _| { + response(200, &format!("{LOG}2024-01-01T00:00:02.000Z third\n")) + }); + let client = client_on(backend.clone(), 0); + let (messages, to_log) = collecting_sink(); + let mut streamed = client + .run("r1") + .get_streamed_log(StreamedLogOptions { + to_log, + since: None, + }) + .await + .unwrap() + .unwrap(); + streamed.start().unwrap(); + // The stream breaks at once, and the reopen waits a second. + tokio::time::sleep(Duration::from_millis(100)).await; + streamed.stop().await.unwrap(); + + assert_eq!( + *messages.lock().unwrap(), + vec![ + "2024-01-01T00:00:00.000Z first".to_string(), + "2024-01-01T00:00:01.000Z second".to_string(), + "2024-01-01T00:00:02.000Z third".to_string(), + ] + ); + assert_eq!(backend.count(HttpMethod::Get, "stream=1"), 1); + assert_eq!( + streamed.last_redirected_at(), + Some(timestamp("2024-01-01T00:00:02.000Z")) + ); +} + +/// Stopping while a reopened stream is still replaying, and has not reached the last redirected +/// message, reads the rest of the log in one request. +#[tokio::test(start_paused = true)] +async fn stopping_during_the_replay_of_a_reopened_stream_reads_the_rest_of_the_log() { + let broken = vec![ + Ok(b"2024-01-01T00:00:00.000Z first\n".to_vec()), + Err(ApifyClientError::Http("connection reset".to_string())), + ]; + // The reopened stream replays the first message and then stalls. + let stalled = vec![Ok(b"2024-01-01T00:00:00.000Z first\n".to_vec())]; + let backend = + RouteBackend::with_scripted_log_streams(vec![(broken, false), (stalled, true)], |_, _| { + response(200, &format!("{LOG}2024-01-01T00:00:02.000Z third\n")) + }); + let client = client_on(backend.clone(), 0); + let (messages, to_log) = collecting_sink(); + let mut streamed = client + .run("r1") + .get_streamed_log(StreamedLogOptions { + to_log, + since: None, + }) + .await + .unwrap() + .unwrap(); + streamed.start().unwrap(); + // The first stream breaks at once, and the second one opens after the pause and stalls. + tokio::time::sleep(Duration::from_secs(3)).await; + assert_eq!(backend.count(HttpMethod::Get, "stream=1"), 2); + streamed.stop().await.unwrap(); + + assert_eq!( + *messages.lock().unwrap(), + vec![ + "2024-01-01T00:00:00.000Z first".to_string(), + "2024-01-01T00:00:01.000Z second".to_string(), + "2024-01-01T00:00:02.000Z third".to_string(), ] ); } diff --git a/tests/unit_http.rs b/tests/unit_http.rs index c8e05b4..5ae0706 100644 --- a/tests/unit_http.rs +++ b/tests/unit_http.rs @@ -10,7 +10,8 @@ use std::time::Duration; use apify_client::{ ActorCallOptions, ActorStartOptions, ApifyClient, ApifyClientError, LastRunOptions, - LogRedirect, RequestCompression, TaskStartOptions, WaitForResources, + LogRedirect, RequestCompression, StoreListOptions, StoreSearchOptions, TaskStartOptions, + WaitForResources, }; use common::mock_backend::{client_with, MockBackend, MockOutcome}; use futures_util::StreamExt; @@ -1699,6 +1700,93 @@ async fn iterate_steps_by_the_count_the_api_reports_when_it_exceeds_the_items_re assert!(urls[2].contains("offset=6"), "{urls:?}"); } +/// A search is one request. The API ignores `offset` for it and reports the number of Actors it +/// returned as `total`, so the result keeps only the items and the limit the API applied. +#[tokio::test] +async fn a_store_search_sends_one_request_and_returns_the_items_and_the_limit() { + let backend = MockBackend::new(vec![MockOutcome::Status( + 200, + br#"{"data":{"total":2,"count":2,"offset":0,"limit":10,"items":[{"id":"a"},{"id":"b"}]}}"# + .to_vec(), + )]); + let client = client_with(backend.clone(), 0); + + let result = client + .store() + .search(StoreSearchOptions { + search: "scraper".to_string(), + limit: Some(10), + category: Some("AI_AND_ML".to_string()), + ..Default::default() + }) + .await + .expect("ok"); + + let ids: Vec<&str> = result.items.iter().map(|actor| actor.id.as_str()).collect(); + assert_eq!(ids, ["a", "b"]); + assert_eq!(result.limit, 10); + let urls = backend.urls(); + assert_eq!(urls.len(), 1, "{urls:?}"); + assert!(urls[0].contains("search=scraper"), "{urls:?}"); + assert!(urls[0].contains("limit=10"), "{urls:?}"); + assert!(urls[0].contains("category=AI_AND_ML"), "{urls:?}"); + assert!(!urls[0].contains("offset"), "{urls:?}"); + assert!(!urls[0].contains("sortBy"), "{urls:?}"); +} + +/// The API answers an empty `search` with the Store listing, so it is not a search. +#[tokio::test] +async fn a_store_search_rejects_an_empty_query_without_a_request() { + let backend = MockBackend::new(vec![]); + let client = client_with(backend.clone(), 0); + + let result = client.store().search(StoreSearchOptions::default()).await; + + assert!(matches!(result, Err(ApifyClientError::InvalidArgument(_)))); + assert_eq!(backend.call_count(), 0); +} + +/// Listing the Store never searches, and keeps paging through it as usual. +#[tokio::test] +async fn iterating_the_store_sends_no_search_and_pages_normally() { + let backend = MockBackend::new(vec![ + MockOutcome::Status( + 200, + br#"{"data":{"total":4,"count":2,"items":[{"id":"a"},{"id":"b"}]}}"#.to_vec(), + ), + MockOutcome::Status( + 200, + br#"{"data":{"total":4,"count":2,"items":[{"id":"c"},{"id":"d"}]}}"#.to_vec(), + ), + MockOutcome::Status( + 200, + br#"{"data":{"total":4,"count":0,"items":[]}}"#.to_vec(), + ), + ]); + let client = client_with(backend.clone(), 0); + + let actors = client + .store() + .iterate(StoreListOptions { + username: Some("apify".to_string()), + ..Default::default() + }) + .with_chunk_size(2) + .collect_all() + .await + .expect("ok"); + + assert_eq!(actors.len(), 4); + let urls = backend.urls(); + assert!(urls[0].contains("username=apify"), "{urls:?}"); + assert!(urls[1].contains("offset=2"), "{urls:?}"); + assert!( + urls.iter() + .all(|url| !url.contains("search") && !url.contains("sortBy")), + "{urls:?}" + ); +} + /// A streaming call retries an error status until the response starts, like a buffered call. #[tokio::test] async fn a_stream_is_retried_on_an_error_status_until_the_response_starts() { diff --git a/tests/unit_timeouts.rs b/tests/unit_timeouts.rs index bc4d442..b385906 100644 --- a/tests/unit_timeouts.rs +++ b/tests/unit_timeouts.rs @@ -56,6 +56,32 @@ async fn listing_uses_the_medium_tier() { assert_eq!(backend.last_timeout(), Duration::from_secs(30)); } +#[tokio::test] +async fn creating_and_updating_an_actor_version_use_the_long_tier() { + let backend = MockBackend::new(vec![ + ok_data(json!({ "versionNumber": "0.1" })), + ok_data(json!({ "versionNumber": "0.1" })), + ]); + let client = client_with(backend.clone(), 0); + let body = json!({ "versionNumber": "0.1", "sourceType": "SOURCE_FILES" }); + client + .actor("a") + .versions() + .create(&body) + .await + .expect("create version"); + client + .actor("a") + .version("0.1") + .update(&body) + .await + .expect("update version"); + assert_eq!( + backend.timeouts(), + vec![Duration::from_secs(360), Duration::from_secs(360)] + ); +} + #[tokio::test] async fn dataset_items_use_the_long_tier() { let backend = MockBackend::new(vec![MockOutcome::Status(200, b"[]".to_vec())]);