From bb22896356cc0deaff7a5050ec462c6da96314e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:55:07 +0000 Subject: [PATCH 01/11] feat: sync with Apify OpenAPI spec updates and use the long timeout for Actor version uploads Document the Store search semantics and the deprecated sortBy, and send Actor version create and update requests with the Long timeout tier. --- CHANGELOG.md | 13 +++++++++++++ Cargo.toml | 2 +- README.md | 4 ++-- docs/README.md | 2 +- docs/actors.md | 3 ++- docs/misc.md | 7 +++++++ src/clients/actor_version.rs | 5 ++++- src/clients/actor_version_collection.rs | 5 ++++- src/clients/store_collection.rs | 17 +++++++++++----- tests/store.rs | 17 ++++++++++++++++ tests/unit_timeouts.rs | 26 +++++++++++++++++++++++++ 11 files changed, 89 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6d3e59..8c8dd5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ 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-11-27 + +### Changed +- Synced with the Apify OpenAPI spec. `GET /v2/store` ranks the results of a `search` by relevance + and returns a single page of at most 100 items, `sortBy` is deprecated and ignored, and + `category` takes comma-separated category IDs. Documented it on `StoreListOptions` and in the + docs. The Store listing items keep the new `stats` shape and `isVerified` in `extra`. The spec + also adds the `APIFY_AI` run origin, marks eight response fields as nullable, and adds the `409` + response to creating an Actor and the `401` response to getting a build. These need no code + change. +- `ActorVersionCollectionClient::create` and `ActorVersionClient::update` use the `Long` timeout + tier by default, since a version can carry its source files. + ## [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..1ef751e 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 ``` @@ -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.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 diff --git a/docs/README.md b/docs/README.md index 515f1ee..e75fb3c 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"] } ``` diff --git a/docs/actors.md b/docs/actors.md index 75ec001..d7e0f6b 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -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/misc.md b/docs/misc.md index 5f7b1b1..27aa7af 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -14,6 +14,13 @@ `limit` means a single page's size for `list`, but a cap on the *total* number of items yielded for `iterate` (see below). +With `search`, the API ranks the results by relevance and returns a single page of at most 100 +items: `offset` is ignored, a larger `limit` is reduced to 100, and there is no second page. Without +it, a page has at most 1000 items. `sort_by` is deprecated: the API accepts it and ignores it, so +sort the results on the client if you need a different order. `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. + `StoreActorIterator` is a type alias for `ListIterator` (the shared iterator returned by every collection's `iterate`), re-exported at the crate root alongside `ListIterator` itself. Its `next()` is `async` and fallible — it returns 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/store_collection.rs b/src/clients/store_collection.rs index 13d3d9f..8bc5849 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -18,18 +18,25 @@ pub type StoreActorIterator = ListIterator; /// Options for searching the Apify Store. #[derive(Debug, Default, Clone)] pub struct StoreListOptions { - /// Number of items to skip. + /// Number of items to skip. The API ignores it when `search` is used. pub offset: Option, - /// Item limit. Its meaning depends on the method: for [`StoreCollectionClient::list`] it is a + /// Item limit. The default and the maximum are 1000. When `search` is used, they are 100, and + /// a larger value is reduced to 100. 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. + /// Search query. With it, the API ranks the results by relevance and returns a single page of + /// at most 100 items: `offset` is ignored and there is no second page. To narrow the results, + /// use `category`, `username` or `pricing_model`. pub search: Option, - /// Sort key (e.g. `popularity`, `newest`). + /// Deprecated and ignored by the API, which accepts it for backward compatibility. Results + /// are ordered by relevance when `search` is used, and by Store position otherwise. Sort the + /// results on the client if you need a different order. 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, diff --git a/tests/store.rs b/tests/store.rs index 549fa0e..cf0efb2 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -58,3 +58,20 @@ async fn list_store_with_input_schema() { assert!(!page.items.is_empty(), "the Store lists Actors"); assert!(page.items.len() <= 3); } + +/// Simple GET: the deprecated `sort_by` is accepted by the Store endpoint, which ignores it, so +/// the order of the result is not asserted. +#[tokio::test(flavor = "multi_thread")] +async fn list_store_accepts_the_deprecated_sort_by() { + let client = require_client!(); + let page = client + .store() + .list(StoreListOptions { + limit: Some(10), + sort_by: Some("popularity".to_string()), + ..Default::default() + }) + .await + .expect("listing the store with the deprecated sort_by should succeed"); + assert!(!page.items.is_empty(), "the Store lists Actors"); +} 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())]); From 90bafd18ffb316f5e3aa5b1179b02e9ee75185ab Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:03:16 +0000 Subject: [PATCH 02/11] fix: stop iterating a Store search after its single page Mark StoreListOptions::sort_by deprecated, align the Store option docs with the spec, and shorten the changelog entry. --- CHANGELOG.md | 13 ++++++------- docs/misc.md | 8 +++++--- src/clients/store_collection.rs | 30 ++++++++++++++++++++++++------ tests/store.rs | 19 +++++++++++++++++++ tests/unit_http.rs | 31 ++++++++++++++++++++++++++++++- 5 files changed, 84 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c8dd5c..2dbb28e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,13 @@ to [Semantic Versioning](https://semver.org/). ## [0.19.0] - 2026-11-27 +### Fixed +- `StoreCollectionClient::iterate` with `search` fetches the single page the API returns and + stops, instead of repeating the same Actors. + ### Changed -- Synced with the Apify OpenAPI spec. `GET /v2/store` ranks the results of a `search` by relevance - and returns a single page of at most 100 items, `sortBy` is deprecated and ignored, and - `category` takes comma-separated category IDs. Documented it on `StoreListOptions` and in the - docs. The Store listing items keep the new `stats` shape and `isVerified` in `extra`. The spec - also adds the `APIFY_AI` run origin, marks eight response fields as nullable, and adds the `409` - response to creating an Actor and the `401` response to getting a build. These need no code - change. +- Documented the Store search, `limit`, `category` and `sort_by` semantics on `StoreListOptions` and + in the docs, and deprecated `StoreListOptions::sort_by`, which the API ignores. - `ActorVersionCollectionClient::create` and `ActorVersionClient::update` use the `Long` timeout tier by default, since a version can carry its source files. diff --git a/docs/misc.md b/docs/misc.md index 27aa7af..5978d40 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -10,13 +10,14 @@ | `iterate(options)` | `StoreListOptions` | `StoreActorIterator` | Lazy, page-fetching iterator. | `StoreListOptions`: `offset`, `limit`, `search`, `sort_by`, `category`, `username`, -`pricing_model`, `include_unrunnable_actors`, `allows_agentic_users`, `response_format`. +`pricing_model`, `include_unrunnable_actors`, `allows_agentic_users`, `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). With `search`, the API ranks the results by relevance and returns a single page of at most 100 items: `offset` is ignored, a larger `limit` is reduced to 100, and there is no second page. Without -it, a page has at most 1000 items. `sort_by` is deprecated: the API accepts it and ignores it, so +it, a page has at most 1000 items, or 10 with `include_input_schema`. `sort_by` is deprecated: the API accepts it and ignores it, so sort the results on the client if you need a different order. `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. @@ -41,7 +42,8 @@ while let Some(actor) = iter.next().await? { ``` `options.limit` caps the total number of Actors the iterator yields (unset iterates the whole -Store). The per-request page size is separate: call `.with_chunk_size(n)` on the returned +Store). With `search`, the API returns a single page and ignores `offset`, so the iterator fetches +that one page of at most 100 Actors and stops; `with_chunk_size` has no effect then. The per-request page size is separate: call `.with_chunk_size(n)` on the returned `StoreActorIterator` to fetch `n` Actors per API call (when unset, the API's default page size is used). If you set a large `limit` cap, also set `with_chunk_size` so the first request does not ask for the entire cap at once — for example, `client.store().iterate(opts).with_chunk_size(50)`: diff --git a/src/clients/store_collection.rs b/src/clients/store_collection.rs index 8bc5849..f4ee47d 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -21,18 +21,20 @@ pub struct StoreListOptions { /// Number of items to skip. The API ignores it when `search` is used. pub offset: Option, /// Item limit. The default and the maximum are 1000. When `search` is used, they are 100, and - /// a larger value is reduced to 100. Its meaning depends on the method: for [`StoreCollectionClient::list`] it is a - /// single page's size (the maximum items that one call returns); for + /// a larger value is reduced to 100. 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, /// Search query. With it, the API ranks the results by relevance and returns a single page of /// at most 100 items: `offset` is ignored and there is no second page. To narrow the results, - /// use `category`, `username` or `pricing_model`. + /// use `category`, `username`, or `pricing_model`. pub search: Option, /// Deprecated and ignored by the API, which accepts it for backward compatibility. Results /// are ordered by relevance when `search` is used, and by Store position otherwise. Sort the /// results on the client if you need a different order. + #[deprecated(note = "the API ignores `sortBy`: sort the results on the client")] pub sort_by: Option, /// 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 @@ -42,9 +44,12 @@ pub struct StoreListOptions { 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. + /// If `true`, returns only Actors that allow agentic users. If `false`, returns only Actors + /// that do not allow agentic users. pub allows_agentic_users: Option, /// Response format requested from the API (`full` or `agent`, the API default is `full`). pub response_format: Option, @@ -90,10 +95,23 @@ impl StoreCollectionClient { /// [`list`](Self::list) where `limit` is a single page's size. Set the per-page fetch size /// with [`with_chunk_size`](crate::ListIterator::with_chunk_size); see /// [`ListIterator`] for details. + /// + /// With `options.search`, the API returns a single page of at most 100 Actors and ignores + /// `offset`, so the iterator fetches that one page and stops. `with_chunk_size` has no effect + /// then, and `options.limit` is sent as given. pub fn iterate(&self, options: StoreListOptions) -> StoreActorIterator { - list_iterator!(self, options, list) + if options.search.is_none() { + return list_iterator!(self, options, list); + } + let client = self.clone(); + ListIterator::new_single_page(Box::new(move |_offset, _page_limit| { + let client = client.clone(); + let options = options.clone(); + Box::pin(async move { client.list(options).await }) + })) } + #[allow(deprecated)] // `sort_by` is deprecated, but it is still sent as the caller set it. fn build_params(&self, options: &StoreListOptions) -> QueryParams { let mut params = QueryParams::new(); params diff --git a/tests/store.rs b/tests/store.rs index cf0efb2..600d168 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -62,6 +62,7 @@ async fn list_store_with_input_schema() { /// Simple GET: the deprecated `sort_by` is accepted by the Store endpoint, which ignores it, so /// the order of the result is not asserted. #[tokio::test(flavor = "multi_thread")] +#[allow(deprecated)] // The test covers the deprecated option. async fn list_store_accepts_the_deprecated_sort_by() { let client = require_client!(); let page = client @@ -75,3 +76,21 @@ async fn list_store_accepts_the_deprecated_sort_by() { .expect("listing the store with the deprecated sort_by should succeed"); assert!(!page.items.is_empty(), "the Store lists Actors"); } + +/// Convenience: iterating a search fetches its single page and ends, without repeating Actors. +#[tokio::test(flavor = "multi_thread")] +async fn iterate_store_search_ends_with_unique_actors() { + let client = require_client!(); + let mut iter = client.store().iterate(StoreListOptions { + search: Some("web scraper".to_string()), + ..Default::default() + }); + let mut ids = std::collections::HashSet::new(); + let mut seen = 0; + while let Some(actor) = iter.next().await.expect("iterate the store search") { + seen += 1; + assert!(ids.insert(actor.id), "an Actor was yielded twice"); + } + assert!(seen > 0, "the search yields at least one Actor"); + assert!(seen <= 100, "a search returns at most 100 Actors"); +} diff --git a/tests/unit_http.rs b/tests/unit_http.rs index c8e05b4..b7f0039 100644 --- a/tests/unit_http.rs +++ b/tests/unit_http.rs @@ -10,7 +10,7 @@ use std::time::Duration; use apify_client::{ ActorCallOptions, ActorStartOptions, ApifyClient, ApifyClientError, LastRunOptions, - LogRedirect, RequestCompression, TaskStartOptions, WaitForResources, + LogRedirect, RequestCompression, StoreListOptions, TaskStartOptions, WaitForResources, }; use common::mock_backend::{client_with, MockBackend, MockOutcome}; use futures_util::StreamExt; @@ -1699,6 +1699,35 @@ async fn iterate_steps_by_the_count_the_api_reports_when_it_exceeds_the_items_re assert!(urls[2].contains("offset=6"), "{urls:?}"); } +/// With `search` the API returns one page and ignores `offset`, so the iterator stops after it +/// instead of requesting the same Actors again. +#[tokio::test] +async fn iterating_a_store_search_fetches_a_single_page() { + let backend = MockBackend::new(vec![MockOutcome::Status( + 200, + br#"{"data":{"total":2,"count":2,"items":[{"id":"a"},{"id":"b"}]}}"#.to_vec(), + )]); + let client = client_with(backend.clone(), 0); + + let actors = client + .store() + .iterate(StoreListOptions { + search: Some("scraper".to_string()), + limit: Some(10), + ..Default::default() + }) + .collect_all() + .await + .expect("ok"); + + let ids: Vec<&str> = actors.iter().map(|actor| actor.id.as_str()).collect(); + assert_eq!(ids, ["a", "b"]); + let urls = backend.urls(); + assert_eq!(urls.len(), 1, "{urls:?}"); + assert!(urls[0].contains("search=scraper"), "{urls:?}"); + assert!(urls[0].contains("limit=10"), "{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() { From 9f420d11c8376080e519527e40929029bba0f638 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:09:29 +0000 Subject: [PATCH 03/11] fix: keep paging a Store iteration with an empty search Only a non-empty search takes the single-page path. Update the pagination docs and the Store docs to match. --- CHANGELOG.md | 2 +- docs/misc.md | 20 ++++++++++-------- src/clients/pagination.rs | 11 ++++++---- src/clients/store_collection.rs | 15 +++++++++----- tests/unit_http.rs | 36 +++++++++++++++++++++++++++++++++ 5 files changed, 66 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dbb28e..16d2570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ to [Semantic Versioning](https://semver.org/). stops, instead of repeating the same Actors. ### Changed -- Documented the Store search, `limit`, `category` and `sort_by` semantics on `StoreListOptions` and +- Documented the Store search, `limit`, `category`, and `sort_by` semantics on `StoreListOptions` and in the docs, and deprecated `StoreListOptions::sort_by`, which the API ignores. - `ActorVersionCollectionClient::create` and `ActorVersionClient::update` use the `Long` timeout tier by default, since a version can carry its source files. diff --git a/docs/misc.md b/docs/misc.md index 5978d40..8b1a71e 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -15,12 +15,13 @@ `limit` means a single page's size for `list`, but a cap on the *total* number of items yielded for `iterate` (see below). -With `search`, the API ranks the results by relevance and returns a single page of at most 100 -items: `offset` is ignored, a larger `limit` is reduced to 100, and there is no second page. Without -it, a page has at most 1000 items, or 10 with `include_input_schema`. `sort_by` is deprecated: the API accepts it and ignores it, so -sort the results on the client if you need a different order. `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. +With a non-empty `search`, the API ranks the results by relevance and returns a single page of at +most 100 items: `offset` is ignored, a larger `limit` is reduced to 100, and there is no second +page. Without it, a page has at most 1000 items, or 10 with `include_input_schema`. `sort_by` is +deprecated: the API accepts it and ignores it, so sort the results on the client if you need a +different order. `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. `StoreActorIterator` is a type alias for `ListIterator` (the shared iterator returned by every collection's `iterate`), re-exported at the crate root alongside `ListIterator` @@ -42,8 +43,7 @@ while let Some(actor) = iter.next().await? { ``` `options.limit` caps the total number of Actors the iterator yields (unset iterates the whole -Store). With `search`, the API returns a single page and ignores `offset`, so the iterator fetches -that one page of at most 100 Actors and stops; `with_chunk_size` has no effect then. The per-request page size is separate: call `.with_chunk_size(n)` on the returned +Store). The per-request page size is separate: call `.with_chunk_size(n)` on the returned `StoreActorIterator` to fetch `n` Actors per API call (when unset, the API's default page size is used). If you set a large `limit` cap, also set `with_chunk_size` so the first request does not ask for the entire cap at once — for example, `client.store().iterate(opts).with_chunk_size(50)`: @@ -59,6 +59,10 @@ while let Some(actor) = iter.next().await? { # } ``` +With a non-empty `search`, the API returns a single page and ignores `offset`, so the iterator +fetches that one page of at most 100 Actors and stops; `with_chunk_size` has no effect then. An +empty `search` is the same as none. + `ActorStoreListItem` (from `apify_client::models`) is the element type yielded by both `list` and the iterator. Its fields: diff --git a/src/clients/pagination.rs b/src/clients/pagination.rs index 6a52bf5..1690b77 100644 --- a/src/clients/pagination.rs +++ b/src/clients/pagination.rs @@ -30,7 +30,8 @@ type PageFetcher = Box) -> PageFuture + Send + Syn /// Collections whose listing does not fit this shape build their iterator directly instead: /// the run listing takes a separate `filter` argument, dataset items use `list_items::`, and /// the listings that are not paginated (an Actor's versions and a version's env vars) use -/// `single_page_iterator!`. +/// `single_page_iterator!`. The Store listing uses this macro, except for a search, which +/// returns one page and ignores `offset`, so it builds a single-page iterator itself. macro_rules! list_iterator { ($self:expr, $options:expr, $list:ident) => {{ let client = $self.clone(); @@ -124,8 +125,9 @@ pub struct ListIterator { remaining: Option, /// Page size to request per fetch; `None` = let the API choose its default page size. chunk_size: Option, - /// When `true`, the underlying endpoint is not offset-paginated: the first fetch returns the - /// whole result set, so the iterator stops after it rather than requesting a second page. + /// When `true`, the underlying endpoint is not offset-paginated, or ignores `offset` (a Store + /// search): the first fetch returns the whole result set, so the iterator stops after it + /// rather than requesting a second page. single_page: bool, /// Set once the listing has been fully consumed. exhausted: bool, @@ -148,7 +150,8 @@ impl ListIterator { } /// Builds an iterator over an endpoint that is **not** offset-paginated (it returns every - /// item in one response, e.g. an Actor version's environment variables). `fetch` is called + /// item in one response, e.g. an Actor version's environment variables) or that ignores + /// `offset` for the request at hand (a Store search). `fetch` is called /// exactly once; the iterator does not attempt a second page, so it does not depend on the /// endpoint reporting a page `limit` and cannot refetch the same items. pub(crate) fn new_single_page(fetch: PageFetcher) -> Self { diff --git a/src/clients/store_collection.rs b/src/clients/store_collection.rs index f4ee47d..b7cf59a 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -27,7 +27,7 @@ pub struct StoreListOptions { /// [`StoreCollectionClient::iterate`] it is a cap on the *total* number of items yielded across /// all pages. See each method's docs. pub limit: Option, - /// Search query. With it, the API ranks the results by relevance and returns a single page of + /// Search query. With a non-empty one, the API ranks the results by relevance and returns a single page of /// at most 100 items: `offset` is ignored and there is no second page. To narrow the results, /// use `category`, `username`, or `pricing_model`. pub search: Option, @@ -96,11 +96,16 @@ impl StoreCollectionClient { /// with [`with_chunk_size`](crate::ListIterator::with_chunk_size); see /// [`ListIterator`] for details. /// - /// With `options.search`, the API returns a single page of at most 100 Actors and ignores - /// `offset`, so the iterator fetches that one page and stops. `with_chunk_size` has no effect - /// then, and `options.limit` is sent as given. + /// With a non-empty `options.search`, the API returns a single page of at most 100 Actors and + /// ignores `offset`, so the iterator fetches that one page and stops. `with_chunk_size` has no + /// effect then, and `options.limit` is sent as given. pub fn iterate(&self, options: StoreListOptions) -> StoreActorIterator { - if options.search.is_none() { + // The API treats an empty search as no search, and pages through the Store as usual. + if !options + .search + .as_deref() + .is_some_and(|search| !search.is_empty()) + { return list_iterator!(self, options, list); } let client = self.clone(); diff --git a/tests/unit_http.rs b/tests/unit_http.rs index b7f0039..dcf607d 100644 --- a/tests/unit_http.rs +++ b/tests/unit_http.rs @@ -1728,6 +1728,42 @@ async fn iterating_a_store_search_fetches_a_single_page() { assert!(urls[0].contains("limit=10"), "{urls:?}"); } +/// The API treats an empty `search` as no search and pages through the Store, so the iterator +/// keeps paging instead of stopping after the first page. +#[tokio::test] +async fn iterating_an_empty_store_search_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 { + search: Some(String::new()), + ..Default::default() + }) + .with_chunk_size(2) + .collect_all() + .await + .expect("ok"); + + assert_eq!(actors.len(), 4); + let urls = backend.urls(); + assert!(urls[1].contains("offset=2"), "{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() { From eea3913c02d7b7b0f3552cc0649988c8e618e55a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:14:05 +0000 Subject: [PATCH 04/11] refactor: reuse single_page_iterator for a Store search and tidy the docs Say non-empty search in the Store option docs and the changelog, and simplify the search check. --- CHANGELOG.md | 8 +++---- src/clients/pagination.rs | 17 ++++++++++++-- src/clients/store_collection.rs | 39 +++++++++++++-------------------- 3 files changed, 34 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16d2570..ed5145a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,12 +7,12 @@ to [Semantic Versioning](https://semver.org/). ## [0.19.0] - 2026-11-27 ### Fixed -- `StoreCollectionClient::iterate` with `search` fetches the single page the API returns and - stops, instead of repeating the same Actors. +- `StoreCollectionClient::iterate` with a non-empty `search` fetches the single page the API + returns and stops, instead of repeating the same Actors. ### Changed -- Documented the Store search, `limit`, `category`, and `sort_by` semantics on `StoreListOptions` and - in the docs, and deprecated `StoreListOptions::sort_by`, which the API ignores. +- Documented the Store search, `limit`, `category`, and `sort_by` semantics on `StoreListOptions` + and in the docs, and deprecated `StoreListOptions::sort_by`, which the API ignores. - `ActorVersionCollectionClient::create` and `ActorVersionClient::update` use the `Long` timeout tier by default, since a version can carry its source files. diff --git a/src/clients/pagination.rs b/src/clients/pagination.rs index 1690b77..e5aec6f 100644 --- a/src/clients/pagination.rs +++ b/src/clients/pagination.rs @@ -30,8 +30,8 @@ type PageFetcher = Box) -> PageFuture + Send + Syn /// Collections whose listing does not fit this shape build their iterator directly instead: /// the run listing takes a separate `filter` argument, dataset items use `list_items::`, and /// the listings that are not paginated (an Actor's versions and a version's env vars) use -/// `single_page_iterator!`. The Store listing uses this macro, except for a search, which -/// returns one page and ignores `offset`, so it builds a single-page iterator itself. +/// `single_page_iterator!`. The Store listing uses this macro, except for a non-empty search, +/// which returns one page and ignores `offset`, so it uses `single_page_iterator!` as well. macro_rules! list_iterator { ($self:expr, $options:expr, $list:ident) => {{ let client = $self.clone(); @@ -66,6 +66,19 @@ macro_rules! single_page_iterator { }, )) }}; + // A listing that takes options and ignores `offset` for some of them: `list(options)` is + // called exactly once with the caller's options as given. + ($self:expr, $options:expr, $list:ident) => {{ + let client = $self.clone(); + let options = $options; + $crate::clients::pagination::ListIterator::new_single_page(Box::new( + move |_offset, _page_limit| { + let client = client.clone(); + let options = options.clone(); + Box::pin(async move { client.$list(options).await }) + }, + )) + }}; } pub(crate) use single_page_iterator; diff --git a/src/clients/store_collection.rs b/src/clients/store_collection.rs index b7cf59a..9b9815c 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -1,7 +1,7 @@ //! Client for browsing the Apify Store (`/v2/store`). use crate::clients::base::{list_resource, ResourceContext}; -use crate::clients::pagination::{list_iterator, ListIterator}; +use crate::clients::pagination::{list_iterator, single_page_iterator, ListIterator}; use crate::common::{PaginationList, QueryParams}; use crate::error::ApifyClientResult; use crate::http_client::HttpClient; @@ -18,22 +18,22 @@ pub type StoreActorIterator = ListIterator; /// Options for searching the Apify Store. #[derive(Debug, Default, Clone)] pub struct StoreListOptions { - /// Number of items to skip. The API ignores it when `search` is used. + /// Number of items to skip. The API ignores it when a non-empty `search` is used. pub offset: Option, - /// Item limit. The default and the maximum are 1000. When `search` is used, they are 100, and - /// a larger value is reduced to 100. 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 + /// Item limit. The default and the maximum are 1000. When a non-empty `search` is used, + /// they are 100, and a larger value is reduced to 100. 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, - /// Search query. With a non-empty one, the API ranks the results by relevance and returns a single page of - /// at most 100 items: `offset` is ignored and there is no second page. To narrow the results, - /// use `category`, `username`, or `pricing_model`. + /// Search query. With a non-empty query, the API ranks the results by relevance and returns a + /// single page of at most 100 items: `offset` is ignored and there is no second page. To + /// narrow the results, use `category`, `username`, or `pricing_model`. pub search: Option, /// Deprecated and ignored by the API, which accepts it for backward compatibility. Results - /// are ordered by relevance when `search` is used, and by Store position otherwise. Sort the - /// results on the client if you need a different order. + /// are ordered by relevance when a non-empty `search` is used, and by Store position + /// otherwise. Sort the results on the client if you need a different order. #[deprecated(note = "the API ignores `sortBy`: sort the results on the client")] pub sort_by: Option, /// Filter by category. Accepts one or more category IDs separated by commas, case-insensitive @@ -100,20 +100,11 @@ impl StoreCollectionClient { /// ignores `offset`, so the iterator fetches that one page and stops. `with_chunk_size` has no /// effect then, and `options.limit` is sent as given. pub fn iterate(&self, options: StoreListOptions) -> StoreActorIterator { - // The API treats an empty search as no search, and pages through the Store as usual. - if !options - .search - .as_deref() - .is_some_and(|search| !search.is_empty()) - { - return list_iterator!(self, options, list); + // The API treats an empty search as no search and pages through the Store as usual. + match options.search.as_deref() { + Some(search) if !search.is_empty() => single_page_iterator!(self, options, list), + _ => list_iterator!(self, options, list), } - let client = self.clone(); - ListIterator::new_single_page(Box::new(move |_offset, _page_limit| { - let client = client.clone(); - let options = options.clone(); - Box::pin(async move { client.list(options).await }) - })) } #[allow(deprecated)] // `sort_by` is deprecated, but it is still sent as the caller set it. From 50880a860e8f58cf8aa7fb1c46935884003dfb8e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:16:56 +0000 Subject: [PATCH 05/11] docs: describe both arms of single_page_iterator --- src/clients/pagination.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/clients/pagination.rs b/src/clients/pagination.rs index e5aec6f..ff361f0 100644 --- a/src/clients/pagination.rs +++ b/src/clients/pagination.rs @@ -53,9 +53,11 @@ macro_rules! list_iterator { } pub(crate) use list_iterator; -/// Generates the body of the `iterate()` method of a collection whose endpoint is not -/// offset-paginated: it has a no-argument `list()` method and returns every item in one response. -/// The resulting [`ListIterator`] calls `list` exactly once and then completes. +/// Generates the body of the `iterate()` method of a collection that is read in a single request. +/// Without more arguments, the endpoint is not offset-paginated and the collection has a +/// no-argument `list()` method. With `options` and a list method name, the call is the paginated +/// `list(options)`, made for a request that ignores `offset`, such as a Store search. The +/// resulting [`ListIterator`] calls `list` exactly once and then completes. macro_rules! single_page_iterator { ($self:expr) => {{ let client = $self.clone(); @@ -66,8 +68,6 @@ macro_rules! single_page_iterator { }, )) }}; - // A listing that takes options and ignores `offset` for some of them: `list(options)` is - // called exactly once with the caller's options as given. ($self:expr, $options:expr, $list:ident) => {{ let client = $self.clone(); let options = $options; @@ -138,9 +138,9 @@ pub struct ListIterator { remaining: Option, /// Page size to request per fetch; `None` = let the API choose its default page size. chunk_size: Option, - /// When `true`, the underlying endpoint is not offset-paginated, or ignores `offset` (a Store - /// search): the first fetch returns the whole result set, so the iterator stops after it - /// rather than requesting a second page. + /// When `true`, the underlying endpoint is not offset-paginated, or ignores `offset` for the + /// request (a Store search): the first fetch returns the only page, so the iterator stops + /// after it rather than requesting a second page. single_page: bool, /// Set once the listing has been fully consumed. exhausted: bool, @@ -164,9 +164,9 @@ impl ListIterator { /// Builds an iterator over an endpoint that is **not** offset-paginated (it returns every /// item in one response, e.g. an Actor version's environment variables) or that ignores - /// `offset` for the request at hand (a Store search). `fetch` is called - /// exactly once; the iterator does not attempt a second page, so it does not depend on the - /// endpoint reporting a page `limit` and cannot refetch the same items. + /// `offset` for the request at hand (a Store search). `fetch` is called exactly once; the + /// iterator does not attempt a second page, so it does not depend on the endpoint reporting a + /// page `limit` and cannot refetch the same items. pub(crate) fn new_single_page(fetch: PageFetcher) -> Self { Self { single_page: true, From fe621386b0c8e842b2fd438dcc0dfcce05fc43cb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:19:13 +0000 Subject: [PATCH 06/11] docs: clarify the single-page branch of the list iterator --- src/clients/pagination.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/clients/pagination.rs b/src/clients/pagination.rs index ff361f0..e39c2a5 100644 --- a/src/clients/pagination.rs +++ b/src/clients/pagination.rs @@ -55,9 +55,10 @@ pub(crate) use list_iterator; /// Generates the body of the `iterate()` method of a collection that is read in a single request. /// Without more arguments, the endpoint is not offset-paginated and the collection has a -/// no-argument `list()` method. With `options` and a list method name, the call is the paginated -/// `list(options)`, made for a request that ignores `offset`, such as a Store search. The -/// resulting [`ListIterator`] calls `list` exactly once and then completes. +/// no-argument `list()` method. With `options` and a list method name, it calls `$list(options)` +/// once with the options as given (no `offset` or `limit` override), for a request that ignores +/// `offset`, such as a Store search. The resulting [`ListIterator`] calls `list` exactly once and +/// then completes. macro_rules! single_page_iterator { ($self:expr) => {{ let client = $self.clone(); @@ -238,7 +239,7 @@ impl ListIterator { // Only a page that scanned nothing, or the caller's cap, ends the walk, which costs one // extra request at the end. if self.single_page { - // Non-paginated endpoint: everything came back in one response. + // Single-page listing: the first fetch is the only page. self.exhausted = true; } else if scanned == 0 { self.exhausted = true; From 97efad1187455e83332d610770a59636551b20f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:27:43 +0000 Subject: [PATCH 07/11] feat!: split Store search from the Store listing and sync log redirection with the reference client Store: list and iterate lose search, sort_by and allows_agentic_users; search is a new single-request method. Task call redirects the run log. Streamed log takes since, exposes last_redirected_at and reopens a broken stream. Sync with spec v2-2026-12-02T102104Z. --- CHANGELOG.md | 31 +++- docs/README.md | 4 +- docs/actors.md | 2 +- docs/builds.md | 2 +- docs/misc.md | 61 ++++--- docs/runs.md | 15 +- docs/tasks.md | 2 +- examples/log_redirection.rs | 2 +- examples/run_store_actor.rs | 12 +- src/clients/actor.rs | 47 +++--- src/clients/build.rs | 4 + src/clients/pagination.rs | 37 ++--- src/clients/run.rs | 41 ++++- src/clients/store_collection.rs | 164 ++++++++++++++----- src/clients/streamed_log.rs | 276 ++++++++++++++++++++++++++------ src/clients/task.rs | 31 ++-- src/lib.rs | 7 +- src/version.rs | 2 +- tests/store.rs | 61 ++++--- tests/task.rs | 9 +- tests/unit_call.rs | 231 ++++++++++++++++++++++++-- tests/unit_http.rs | 51 ++++-- 22 files changed, 834 insertions(+), 258 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed5145a..8fdd202 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,17 +4,32 @@ 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-11-27 +## [0.19.0] - 2026-12-03 -### Fixed -- `StoreCollectionClient::iterate` with a non-empty `search` fetches the single page the API - returns and stops, instead of repeating the same Actors. - -### Changed -- Documented the Store search, `limit`, `category`, and `sort_by` semantics on `StoreListOptions` - and in the docs, and deprecated `StoreListOptions::sort_by`, which the API ignores. +### 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`, a `DateTime`. 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. - `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 diff --git a/docs/README.md b/docs/README.md index e75fb3c..3a66e13 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 d7e0f6b..46ddc31 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -39,7 +39,7 @@ 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 +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. 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 8b1a71e..29ccd78 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -6,22 +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`, -`include_input_schema`. +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. -With a non-empty `search`, the API ranks the results by relevance and returns a single page of at -most 100 items: `offset` is ignored, a larger `limit` is reduced to 100, and there is no second -page. Without it, a page has at most 1000 items, or 10 with `include_input_schema`. `sort_by` is -deprecated: the API accepts it and ignores it, so sort the results on the client if you need a -different order. `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. +```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` @@ -59,11 +88,7 @@ while let Some(actor) = iter.next().await? { # } ``` -With a non-empty `search`, the API returns a single page and ignores `offset`, so the iterator -fetches that one page of at most 100 Actors and stops; `with_chunk_size` has no effect then. An -empty `search` is the same as none. - -`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..08ceec2 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,9 +42,14 @@ 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 +`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. `ActorClient::call` and +`TaskClient::call` do all of this for the run they wait 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. @@ -57,7 +62,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/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..314262f 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 — that 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..01d8b3a 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,27 @@ 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: + /// - `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. + /// + /// Time spent retrying under [`TaskStartOptions::wait_for_resources`] does not count toward + /// it, since that budget only starts once the run has actually started. + pub wait_secs: Option, + /// Where to redirect the log of the run while it is waited for. Redirects to the standard + /// output by default; [`LogRedirect::Disabled`] turns that off. A redirection that ends early + /// on an error does not fail the call: a `Log redirection stopped due to error: ..` message + /// goes to the sink. + pub log: LogRedirect, +} + impl From for ActorStartOptions { fn from(options: TaskStartOptions) -> Self { Self { @@ -349,27 +370,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/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/pagination.rs b/src/clients/pagination.rs index e39c2a5..6a52bf5 100644 --- a/src/clients/pagination.rs +++ b/src/clients/pagination.rs @@ -30,8 +30,7 @@ type PageFetcher = Box) -> PageFuture + Send + Syn /// Collections whose listing does not fit this shape build their iterator directly instead: /// the run listing takes a separate `filter` argument, dataset items use `list_items::`, and /// the listings that are not paginated (an Actor's versions and a version's env vars) use -/// `single_page_iterator!`. The Store listing uses this macro, except for a non-empty search, -/// which returns one page and ignores `offset`, so it uses `single_page_iterator!` as well. +/// `single_page_iterator!`. macro_rules! list_iterator { ($self:expr, $options:expr, $list:ident) => {{ let client = $self.clone(); @@ -53,12 +52,9 @@ macro_rules! list_iterator { } pub(crate) use list_iterator; -/// Generates the body of the `iterate()` method of a collection that is read in a single request. -/// Without more arguments, the endpoint is not offset-paginated and the collection has a -/// no-argument `list()` method. With `options` and a list method name, it calls `$list(options)` -/// once with the options as given (no `offset` or `limit` override), for a request that ignores -/// `offset`, such as a Store search. The resulting [`ListIterator`] calls `list` exactly once and -/// then completes. +/// Generates the body of the `iterate()` method of a collection whose endpoint is not +/// offset-paginated: it has a no-argument `list()` method and returns every item in one response. +/// The resulting [`ListIterator`] calls `list` exactly once and then completes. macro_rules! single_page_iterator { ($self:expr) => {{ let client = $self.clone(); @@ -69,17 +65,6 @@ macro_rules! single_page_iterator { }, )) }}; - ($self:expr, $options:expr, $list:ident) => {{ - let client = $self.clone(); - let options = $options; - $crate::clients::pagination::ListIterator::new_single_page(Box::new( - move |_offset, _page_limit| { - let client = client.clone(); - let options = options.clone(); - Box::pin(async move { client.$list(options).await }) - }, - )) - }}; } pub(crate) use single_page_iterator; @@ -139,9 +124,8 @@ pub struct ListIterator { remaining: Option, /// Page size to request per fetch; `None` = let the API choose its default page size. chunk_size: Option, - /// When `true`, the underlying endpoint is not offset-paginated, or ignores `offset` for the - /// request (a Store search): the first fetch returns the only page, so the iterator stops - /// after it rather than requesting a second page. + /// When `true`, the underlying endpoint is not offset-paginated: the first fetch returns the + /// whole result set, so the iterator stops after it rather than requesting a second page. single_page: bool, /// Set once the listing has been fully consumed. exhausted: bool, @@ -164,10 +148,9 @@ impl ListIterator { } /// Builds an iterator over an endpoint that is **not** offset-paginated (it returns every - /// item in one response, e.g. an Actor version's environment variables) or that ignores - /// `offset` for the request at hand (a Store search). `fetch` is called exactly once; the - /// iterator does not attempt a second page, so it does not depend on the endpoint reporting a - /// page `limit` and cannot refetch the same items. + /// item in one response, e.g. an Actor version's environment variables). `fetch` is called + /// exactly once; the iterator does not attempt a second page, so it does not depend on the + /// endpoint reporting a page `limit` and cannot refetch the same items. pub(crate) fn new_single_page(fetch: PageFetcher) -> Self { Self { single_page: true, @@ -239,7 +222,7 @@ impl ListIterator { // Only a page that scanned nothing, or the caller's cap, ends the walk, which costs one // extra request at the end. if self.single_page { - // Single-page listing: the first fetch is the only page. + // Non-paginated endpoint: everything came back in one response. self.exhausted = true; } else if scanned == 0 { self.exhausted = true; diff --git a/src/clients/run.rs b/src/clients/run.rs index 14ff9c6..807a700 100644 --- a/src/clients/run.rs +++ b/src/clients/run.rs @@ -430,6 +430,9 @@ impl RunClient { RunDatasetItemsIterator::new(self.clone(), options) } + /// When the log stream is cut off while the run is still going, the stream is reopened and + /// the redirection resumes after the last redirected message. + /// /// Returns the redirection of the run's log, or `None` if `options.to_log` is /// [`LogRedirect::Disabled`] or, for [`LogRedirect::Default`], the run does not exist. With a /// [`LogRedirect::Sink`] nothing is requested, so a missing run shows up as the error of @@ -446,7 +449,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 +478,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 9b9815c..2028f97 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, single_page_iterator, ListIterator}; +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,27 +15,19 @@ 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. The API ignores it when a non-empty `search` is used. + /// Number of items to skip. pub offset: Option, - /// Item limit. The default and the maximum are 1000. When a non-empty `search` is used, - /// they are 100, and a larger value is reduced to 100. With `include_input_schema`, they are + /// 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, - /// Search query. With a non-empty query, the API ranks the results by relevance and returns a - /// single page of at most 100 items: `offset` is ignored and there is no second page. To - /// narrow the results, use `category`, `username`, or `pricing_model`. - pub search: Option, - /// Deprecated and ignored by the API, which accepts it for backward compatibility. Results - /// are ordered by relevance when a non-empty `search` is used, and by Store position - /// otherwise. Sort the results on the client if you need a different order. - #[deprecated(note = "the API ignores `sortBy`: sort the results on the client")] - pub sort_by: Option, /// 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. @@ -48,9 +40,6 @@ pub struct StoreListOptions { /// 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, - /// If `true`, returns only Actors that allow agentic users. If `false`, returns only Actors - /// that do not allow agentic 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 @@ -59,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, @@ -74,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. @@ -82,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 } @@ -95,33 +138,70 @@ impl StoreCollectionClient { /// [`list`](Self::list) where `limit` is a single page's size. Set the per-page fetch size /// with [`with_chunk_size`](crate::ListIterator::with_chunk_size); see /// [`ListIterator`] for details. - /// - /// With a non-empty `options.search`, the API returns a single page of at most 100 Actors and - /// ignores `offset`, so the iterator fetches that one page and stops. `with_chunk_size` has no - /// effect then, and `options.limit` is sent as given. pub fn iterate(&self, options: StoreListOptions) -> StoreActorIterator { - // The API treats an empty search as no search and pages through the Store as usual. - match options.search.as_deref() { - Some(search) if !search.is_empty() => single_page_iterator!(self, options, list), - _ => list_iterator!(self, options, list), - } + list_iterator!(self, options, list) } - #[allow(deprecated)] // `sort_by` is deprecated, but it is still sent as the caller set it. - 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..b98b3a0 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}; @@ -25,6 +26,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 +76,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 +112,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 +146,18 @@ 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. +/// /// 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 +175,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 +217,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 }); @@ -256,28 +272,34 @@ 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. + if !received_any { + 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 +317,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 +333,35 @@ async fn redirect( } Some(Err(_)) if is_stopping(&control) => break, Some(Err(error)) => { + let transport_failure = + matches!(error, ApifyClientError::Http(_) | ApifyClientError::Timeout); + if received_any && transport_failure && 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 { 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 +374,35 @@ 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, } 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, } } @@ -369,13 +423,28 @@ 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 + } + + /// 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.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 +461,43 @@ 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) || 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 +519,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 +544,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 +593,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 +604,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/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 600d168..96b57f4 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")] @@ -59,38 +59,49 @@ async fn list_store_with_input_schema() { assert!(page.items.len() <= 3); } -/// Simple GET: the deprecated `sort_by` is accepted by the Store endpoint, which ignores it, so -/// the order of the result is not asserted. +/// Simple GET: a search returns the best matching Actors as a single page of at most `limit`. #[tokio::test(flavor = "multi_thread")] -#[allow(deprecated)] // The test covers the deprecated option. -async fn list_store_accepts_the_deprecated_sort_by() { +async fn search_store() { let client = require_client!(); - let page = client + let result = client .store() - .list(StoreListOptions { - limit: Some(10), - sort_by: Some("popularity".to_string()), + .search(StoreSearchOptions { + search: "web scraper".to_string(), + limit: Some(5), ..Default::default() }) .await - .expect("listing the store with the deprecated sort_by should succeed"); - assert!(!page.items.is_empty(), "the Store lists Actors"); + .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"); } -/// Convenience: iterating a search fetches its single page and ends, without repeating Actors. +/// A search takes the same filters as a listing, and the API reduces a `limit` above 100. #[tokio::test(flavor = "multi_thread")] -async fn iterate_store_search_ends_with_unique_actors() { +async fn search_store_with_a_filter_and_a_large_limit() { let client = require_client!(); - let mut iter = client.store().iterate(StoreListOptions { - search: Some("web scraper".to_string()), - ..Default::default() - }); - let mut ids = std::collections::HashSet::new(); - let mut seen = 0; - while let Some(actor) = iter.next().await.expect("iterate the store search") { - seen += 1; - assert!(ids.insert(actor.id), "an Actor was yielded twice"); - } - assert!(seen > 0, "the search yields at least one Actor"); - assert!(seen <= 100, "a search returns at most 100 Actors"); + 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"); +} + +/// An empty query is not a search: the client rejects it before any request. +#[tokio::test(flavor = "multi_thread")] +async fn search_store_rejects_an_empty_query() { + let client = require_client!(); + let result = client.store().search(StoreSearchOptions::default()).await; + assert!(result.is_err(), "an empty search is rejected"); } 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..7ee76b5 100644 --- a/tests/unit_call.rs +++ b/tests/unit_call.rs @@ -16,9 +16,10 @@ 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 serde_json::{json, Value}; @@ -37,6 +38,17 @@ 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, and the error it ends with, if any. +type ScriptedStream = Vec, ApifyClientError>>; + type Route = dyn Fn(&HttpRequest, usize) -> Result + Send + Sync; /// A backend that answers by request, and records every request. @@ -45,6 +57,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 +78,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 +108,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 +139,20 @@ 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) = scripted { + self.requests.lock().unwrap().push(request); + return Ok(StreamingHttpResponse { + status: 200, + headers: Default::default(), + body: Box::pin(futures_util::stream::iter(chunks)), + }); + } + } let failing = self .failing_log_stream .as_ref() @@ -124,7 +169,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 +225,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 +280,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 +455,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 +500,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 +518,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 +542,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 +559,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 +643,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 +651,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 +686,161 @@ 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], |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")) + ); +} diff --git a/tests/unit_http.rs b/tests/unit_http.rs index dcf607d..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, StoreListOptions, TaskStartOptions, WaitForResources, + LogRedirect, RequestCompression, StoreListOptions, StoreSearchOptions, TaskStartOptions, + WaitForResources, }; use common::mock_backend::{client_with, MockBackend, MockOutcome}; use futures_util::StreamExt; @@ -1699,39 +1700,55 @@ async fn iterate_steps_by_the_count_the_api_reports_when_it_exceeds_the_items_re assert!(urls[2].contains("offset=6"), "{urls:?}"); } -/// With `search` the API returns one page and ignores `offset`, so the iterator stops after it -/// instead of requesting the same Actors again. +/// 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 iterating_a_store_search_fetches_a_single_page() { +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,"items":[{"id":"a"},{"id":"b"}]}}"#.to_vec(), + 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 actors = client + let result = client .store() - .iterate(StoreListOptions { - search: Some("scraper".to_string()), + .search(StoreSearchOptions { + search: "scraper".to_string(), limit: Some(10), + category: Some("AI_AND_ML".to_string()), ..Default::default() }) - .collect_all() .await .expect("ok"); - let ids: Vec<&str> = actors.iter().map(|actor| actor.id.as_str()).collect(); + 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 treats an empty `search` as no search and pages through the Store, so the iterator -/// keeps paging instead of stopping after the first page. +/// The API answers an empty `search` with the Store listing, so it is not a search. #[tokio::test] -async fn iterating_an_empty_store_search_pages_normally() { +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, @@ -1751,7 +1768,7 @@ async fn iterating_an_empty_store_search_pages_normally() { let actors = client .store() .iterate(StoreListOptions { - search: Some(String::new()), + username: Some("apify".to_string()), ..Default::default() }) .with_chunk_size(2) @@ -1761,7 +1778,13 @@ async fn iterating_an_empty_store_search_pages_normally() { 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. From 66180f3581b8f192aa2049a85e29b0d0f2c2e97b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:37:37 +0000 Subject: [PATCH 08/11] fix: read the log tail when stopping after a broken stream and address review feedback Stopping while a broken log stream waits to be reopened reads the rest of the log in one request. Documents what a signed public storage URL grants, shares the transport error check, and tidies docs and tests. --- CHANGELOG.md | 7 ++++-- README.md | 4 ++-- docs/actors.md | 4 ++-- docs/runs.md | 9 +++---- docs/storages.md | 4 ++-- examples/run_store_actor.rs | 2 +- src/clients/actor.rs | 16 ++++--------- src/clients/dataset.rs | 5 ++++ src/clients/key_value_store.rs | 2 ++ src/clients/run.rs | 3 --- src/clients/store_collection.rs | 2 +- src/clients/streamed_log.rs | 34 ++++++++++++++++++++------ src/http_client.rs | 2 +- tests/store.rs | 8 ------- tests/unit_call.rs | 42 +++++++++++++++++++++++++++++++++ 15 files changed, 99 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fdd202..a66fa02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,16 +15,19 @@ to [Semantic Versioning](https://semver.org/). - `StreamedLog::last_redirected_at` and `StreamedLogOptions::since`. ### Changed -- **Breaking:** `StoreListOptions` loses `search`, `sort_by` and `allows_agentic_users`. Use +- **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`, a `DateTime`. Use +- **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` 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 diff --git a/README.md b/README.md index 1ef751e..b06a2a8 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ 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 @@ -215,7 +215,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/actors.md b/docs/actors.md index 46ddc31..acaeb54 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -39,8 +39,8 @@ 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` (inside `TaskCallOptions` for `call`), which has the same -fields except `content_type` and `force_permission_level`, because `POST /actor-tasks/{id}/runs` +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 | diff --git a/docs/runs.md b/docs/runs.md index 08ceec2..9b7b599 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -48,10 +48,11 @@ timestamp of the last redirected message, so a redirection that was interrupted 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. `ActorClient::call` and -`TaskClient::call` do all of this for the run they wait 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 +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 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/examples/run_store_actor.rs b/examples/run_store_actor.rs index 314262f..a1028a6 100644 --- a/examples/run_store_actor.rs +++ b/examples/run_store_actor.rs @@ -32,7 +32,7 @@ async fn main() -> Result<(), Box> { .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 results — 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 = found .items diff --git a/src/clients/actor.rs b/src/clients/actor.rs index 01d8b3a..f70484a 100644 --- a/src/clients/actor.rs +++ b/src/clients/actor.rs @@ -158,19 +158,11 @@ pub struct TaskStartOptions { pub struct TaskCallOptions { /// The options of the run start. pub start: TaskStartOptions, - /// The wait budget, in seconds: - /// - `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. - /// - /// Time spent retrying under [`TaskStartOptions::wait_for_resources`] does not count toward - /// it, since that budget only starts once the run has actually started. + /// 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. Redirects to the standard - /// output by default; [`LogRedirect::Disabled`] turns that off. A redirection that ends early - /// on an error does not fail the call: a `Log redirection stopped due to error: ..` message - /// goes to the sink. + /// 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, } diff --git a/src/clients/dataset.rs b/src/clients/dataset.rs index 3065031..b530aca 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, 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 807a700..92f4800 100644 --- a/src/clients/run.rs +++ b/src/clients/run.rs @@ -430,9 +430,6 @@ impl RunClient { RunDatasetItemsIterator::new(self.clone(), options) } - /// When the log stream is cut off while the run is still going, the stream is reopened and - /// the redirection resumes after the last redirected message. - /// /// Returns the redirection of the run's log, or `None` if `options.to_log` is /// [`LogRedirect::Disabled`] or, for [`LogRedirect::Default`], the run does not exist. With a /// [`LogRedirect::Sink`] nothing is requested, so a missing run shows up as the error of diff --git a/src/clients/store_collection.rs b/src/clients/store_collection.rs index 2028f97..06f5077 100644 --- a/src/clients/store_collection.rs +++ b/src/clients/store_collection.rs @@ -148,7 +148,7 @@ impl StoreCollectionClient { /// 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 + /// 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). /// diff --git a/src/clients/streamed_log.rs b/src/clients/streamed_log.rs index b98b3a0..1e797c1 100644 --- a/src/clients/streamed_log.rs +++ b/src/clients/streamed_log.rs @@ -19,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 @@ -149,7 +150,8 @@ struct Running { /// 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. +/// 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 { @@ -294,8 +296,14 @@ async fn redirect( loop { if is_stopping(&control) { // 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. - if !received_any { + // 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), @@ -333,9 +341,7 @@ async fn redirect( } Some(Err(_)) if is_stopping(&control) => break, Some(Err(error)) => { - let transport_failure = - matches!(error, ApifyClientError::Http(_) | ApifyClientError::Timeout); - if received_any && transport_failure && messages.replay_caught_up() { + if received_any && is_error_retryable(&error) && messages.replay_caught_up() { messages.prepare_reopen(); broke_off = true; break; @@ -387,6 +393,8 @@ struct MessageSplitter { /// `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 { @@ -403,6 +411,7 @@ impl MessageSplitter { redirected_at_last_timestamp: 0, replayed_until: None, replay_skip_count: 0, + awaiting_replay: false, } } @@ -428,12 +437,19 @@ impl MessageSplitter { 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(); } @@ -468,7 +484,11 @@ impl MessageSplitter { return true; }; let time = time.with_timezone(&Utc); - if self.is_replayed(time) || self.since.is_some_and(|since| time < since) { + 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) { 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/tests/store.rs b/tests/store.rs index 96b57f4..bec283a 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -97,11 +97,3 @@ async fn search_store_with_a_filter_and_a_large_limit() { ); assert_eq!(result.limit, 100, "the API reduces the limit to 100"); } - -/// An empty query is not a search: the client rejects it before any request. -#[tokio::test(flavor = "multi_thread")] -async fn search_store_rejects_an_empty_query() { - let client = require_client!(); - let result = client.store().search(StoreSearchOptions::default()).await; - assert!(result.is_err(), "an empty search is rejected"); -} diff --git a/tests/unit_call.rs b/tests/unit_call.rs index 7ee76b5..6f88229 100644 --- a/tests/unit_call.rs +++ b/tests/unit_call.rs @@ -844,3 +844,45 @@ async fn since_redirects_the_messages_stamped_at_that_time_or_later() { 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], |_, _| { + 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")) + ); +} From 2a045d98f9b2cf4336ecb1eed329856c2d33c517 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:43:14 +0000 Subject: [PATCH 09/11] fix: read the rest of the log when a stop cuts a replaying stream short Also documents the public URL format parameter and rewraps the changed docs. --- CHANGELOG.md | 11 ++++--- docs/actors.md | 6 ++-- docs/runs.md | 4 +-- src/clients/dataset.rs | 4 +++ src/clients/streamed_log.rs | 8 +++-- tests/unit_call.rs | 62 +++++++++++++++++++++++++++++++++---- 6 files changed, 77 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a66fa02..e7041d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,13 +21,14 @@ to [Semantic Versioning](https://semver.org/). - **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. +- **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` 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. +- 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 diff --git a/docs/actors.md b/docs/actors.md index acaeb54..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` (inside `TaskCallOptions` for `call`), 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 | |---|---|---| diff --git a/docs/runs.md b/docs/runs.md index 9b7b599..afa869e 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -52,8 +52,8 @@ given point, so the reopen downloads the whole log again, and the lines of a mes 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. +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}; diff --git a/src/clients/dataset.rs b/src/clients/dataset.rs index b530aca..b1842c5 100644 --- a/src/clients/dataset.rs +++ b/src/clients/dataset.rs @@ -467,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/streamed_log.rs b/src/clients/streamed_log.rs index 1e797c1..b24fcf9 100644 --- a/src/clients/streamed_log.rs +++ b/src/clients/streamed_log.rs @@ -227,8 +227,8 @@ 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 + /// 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 { @@ -355,6 +355,10 @@ async fn redirect( } } 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 { diff --git a/tests/unit_call.rs b/tests/unit_call.rs index 6f88229..0f905ef 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; @@ -21,6 +22,7 @@ use apify_client::{ 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"}}"#; @@ -46,8 +48,9 @@ fn task_call_options(wait_secs: Option) -> TaskCallOptions { } } -/// The chunks of one log stream, and the error it ends with, if any. -type ScriptedStream = Vec, ApifyClientError>>; +/// 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; @@ -144,12 +147,18 @@ impl HttpBackend for RouteBackend { let mut streams = self.scripted_log_streams.lock().unwrap(); (!streams.is_empty()).then(|| streams.remove(0)) }; - if let Some(chunks) = scripted { + 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: Box::pin(futures_util::stream::iter(chunks)), + body, }); } } @@ -781,7 +790,7 @@ async fn a_broken_log_stream_is_reopened_and_resumes_after_the_last_redirected_m Err(ApifyClientError::Http("connection reset".to_string())), ]; // The reopened stream carries the whole log. - let backend = RouteBackend::with_scripted_log_streams(vec![broken], |request, _| { + 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")); } @@ -853,7 +862,7 @@ async fn stopping_after_a_broken_log_stream_reads_the_rest_of_the_log() { 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], |_, _| { + 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); @@ -886,3 +895,44 @@ async fn stopping_after_a_broken_log_stream_reads_the_rest_of_the_log() { 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(), + ] + ); +} From 5666e6ae419ca1b86d142bb67f47269167dfe3ff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:46:51 +0000 Subject: [PATCH 10/11] docs: rewrap two changed doc lines --- README.md | 3 ++- src/clients/streamed_log.rs | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b06a2a8..cbc9571 100644 --- a/README.md +++ b/README.md @@ -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`, `TaskClient::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 diff --git a/src/clients/streamed_log.rs b/src/clients/streamed_log.rs index b24fcf9..65304d6 100644 --- a/src/clients/streamed_log.rs +++ b/src/clients/streamed_log.rs @@ -228,8 +228,9 @@ 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, 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. + /// 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( From b03f3f6b7bd757c923be03076dee02ef4f2b4132 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:49:04 +0000 Subject: [PATCH 11/11] docs: rewrap two lines over 100 columns --- docs/misc.md | 4 ++-- tests/unit_call.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/misc.md b/docs/misc.md index 29ccd78..e219868 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -31,8 +31,8 @@ The API ranks the results of a search by relevance and returns them as a single 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. +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}; diff --git a/tests/unit_call.rs b/tests/unit_call.rs index 0f905ef..323210b 100644 --- a/tests/unit_call.rs +++ b/tests/unit_call.rs @@ -761,7 +761,8 @@ async fn a_task_call_still_returns_the_run_when_the_redirection_cannot_be_set_up 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. + // 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"}}"#)