From 54976b213d01dc86883cc6de948207a6a2669d47 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:45:05 +0000 Subject: [PATCH 01/19] feat: sync Store, run origin and Actor version timeouts with the Apify API --- CHANGELOG.md | 19 ++++++ README.md | 6 +- docs/README.md | 2 +- docs/actors.md | 6 +- docs/misc.md | 26 ++++++-- pom.xml | 2 +- src/main/java/com/apify/client/Version.java | 2 +- .../client/actor/ActorCollectionClient.java | 6 +- .../client/actor/ActorVersionClient.java | 8 ++- .../actor/ActorVersionCollectionClient.java | 7 +- .../com/apify/client/run/ActorRunMeta.java | 5 +- .../client/store/ActorStoreListItem.java | 52 +++++++++++++-- .../apify/client/store/StoreActorStats.java | 49 ++++++++++++++ .../client/store/StoreCollectionClient.java | 30 +++++++++ .../apify/client/store/StoreListOptions.java | 36 ++++++++-- .../client/ClientBehaviourRegressionTest.java | 65 +++++++++++++++++++ .../com/apify/client/TimeoutTierTest.java | 16 +++++ .../integration/StoreIntegrationTest.java | 34 ++++++++++ 18 files changed, 339 insertions(+), 32 deletions(-) create mode 100644 src/main/java/com/apify/client/store/StoreActorStats.java diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e0c02..36bafac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,25 @@ All notable changes to the Apify Java client are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.15.0] - 2026-11-27 + +### Added + +- `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating` and `actorReviewCount`. +- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isWhiteListedForAgenticPayments`, `isVerified` and `badge`. + +### Changed + +- `ActorStoreListItem.getStats()` returns `StoreActorStats`, which matches the Store response. The Store no longer returns `totalBuilds`, `totalMetamorphs` and `lastRunStartedAt`. +- Synced with the published Apify OpenAPI specification (still `v2-2026-11-18T151559Z`): a Store search returns one page of at most 100 Actors ranked by relevance and ignores `offset`, `category` takes comma-separated category IDs, and `APIFY_AI` is a run origin. +- `StoreCollectionClient.iterate` sends one request for a search, since the Store has no second page for it. +- `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. +- Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). + +### Deprecated + +- `StoreListOptions.sortBy`: the API ignores it. + ## [0.14.1] - 2026-11-20 ### Changed diff --git a/README.md b/README.md index 5b0f45f..041228d 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Maven (Maven Central is a default repository, so no extra configuration is neede com.apify apify-client - 0.14.1 + 0.15.0 ``` @@ -35,7 +35,7 @@ repositories { } dependencies { - implementation 'com.apify:apify-client:0.14.1' + implementation 'com.apify:apify-client:0.15.0' } ``` @@ -437,7 +437,7 @@ try { The public `com.apify.client.Version` class (`import com.apify.client.Version;`) exposes two constants: -- `Version.CLIENT_VERSION`: the semantic version of this client (`0.14.1`). +- `Version.CLIENT_VERSION`: the semantic version of this client (`0.15.0`). - `Version.API_SPEC_VERSION`: the version of the [Apify OpenAPI specification](https://docs.apify.com/api/openapi.json) (its `info.version` field) that this client's endpoints, parameters, and models were last generated and checked against (`v2-2026-11-18T151559Z`). It is a snapshot, not a live compatibility diff --git a/docs/README.md b/docs/README.md index 703a7fb..a50ead6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -54,7 +54,7 @@ option types, so import each resource you use from its own package: | `com.apify.client.schedule` | `Schedule`, `ScheduleNotifications`, `ScheduleClient`, `ScheduleCollectionClient` | | `com.apify.client.webhook` | `Webhook`, `WebhookStats`, `WebhookLastDispatch`, `WebhookClient`, `WebhookCollectionClient`, `WebhookDispatchCollectionClient`, `NestedWebhookCollectionClient`, `WebhookDispatch`, `WebhookDispatchClient`, `WebhookDispatchCall`, `WebhookDispatchWebhookInfo`, `WebhookDispatchEventData` | | `com.apify.client.user` | `User`, `UserClient`, `UserProfile`, `UserProxy`, `UserPlan`, `ProxyGroup` | -| `com.apify.client.store` | `ActorStoreListItem`, `StoreCollectionClient`, `StoreListOptions`, `PricingInfo` | +| `com.apify.client.store` | `ActorStoreListItem`, `StoreActorStats`, `StoreCollectionClient`, `StoreListOptions`, `PricingInfo` | | `com.apify.client.log` | `LogClient`, `LogOptions`, `StreamedLog`, `StreamedLogOptions` | For example, the [top-level README's dataset snippet](../README.md#quick-start) needs diff --git a/docs/actors.md b/docs/actors.md index f98c38e..ab38e71 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -9,7 +9,7 @@ where `id` is an Actor ID or `username~name` (a `/` in the id is accepted and no |---|---| | `list(ActorListOptions)` | List the account's Actors. Completes with `PaginationList`. | | `iterate(ActorListOptions, Long chunkSize)` | Lazy `Flow.Publisher` over all matches; the options' `limit` caps the total yielded (`null`/unset or non-positive = all), `chunkSize` sets the page size (`null` = server default). | -| `create(Object)` | Create a new Actor from a JSON-serializable definition. Completes with `Actor`. | +| `create(Object)` | Create a new Actor from a JSON-serializable definition. Completes with `Actor`. Fails with a `ConflictError` (409, `actor-name-not-unique`) if you already have an Actor with that name. | `ActorListOptions` adds `my(Boolean)` (only Actors owned by the current user) and `sortBy(String)` (e.g. `createdAt`, `stats.lastRunStartedAt`) on top of the standard offset/limit/desc. @@ -232,14 +232,14 @@ and deletes a single version and exposes its environment variables. |---|---| | `list(ListOptions)` | List the Actor's versions. Completes with `PaginationList`. The endpoint takes no query parameters; `options` (`offset`/`limit`/`desc`) is accepted only for signature consistency with every other `list(ListOptions)` and has no effect; pass `null`. | | `iterate(ListOptions)` | Lazy `Flow.Publisher` over all versions; `limit` caps the total (`null`/unset or non-positive = all), applied client-side after the single fetch. `offset` has no effect and there is no page size to tune. | -| `create(Object version)` | Create a version. Completes with `ActorVersion`. | +| `create(Object version)` | Create a version. Completes with `ActorVersion`. Uses the long timeout tier, since the version can carry its source files. | ### `ActorVersionClient`: `client.actor(id).version(v)` | Method | Description | |---|---| | `get()` | Fetch the version. Completes with `Optional`. | -| `update(Object)` | Update the version. Completes with `ActorVersion`. | +| `update(Object)` | Update the version. Completes with `ActorVersion`. Uses the long timeout tier, since the version can carry its source files. | | `delete()` | Delete the version. | | `envVars()` | An `ActorEnvVarCollectionClient` for the version's environment variables. | | `envVar(String name)` | An `ActorEnvVarClient` for a single environment variable. | diff --git a/docs/misc.md b/docs/misc.md index 65450de..4ba3980 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -10,13 +10,21 @@ Browse public Actors in the Apify Store. `client.store()` returns a `StoreCollec | `iterate(StoreListOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all matches, fetching pages on demand. The options' `limit` caps the total number of rows read, which are the Actors yielded unless the API drops entries after counting them (`null`/unset or non-positive = all); `chunkSize` is the per-request page size (`null` = server default). | `StoreListOptions` fields: `offset` (number of Actors to skip), `limit` (maximum number of Actors to -return), `search` (full-text search query), `sortBy` (the sort field, e.g. `popularity`, `newest`), -`category` (filter Actors by category), `username` (filter Actors by owner username), `pricingModel` -(filter by pricing model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`; the deprecated rental model -`FLAT_PRICE_PER_MONTH` is no longer listed), +return; the API default and maximum is 1000, or 100 with `search`), `search` (search query), +`sortBy` (deprecated: the API ignores it, and orders the results by relevance with `search` and by +Store position otherwise, so sort them on the client), `category` (filter by one or more category IDs +such as `AI_AND_ML`, comma-separated and case-insensitive; an Actor must match all of them, and an +unknown category fails with a `400` error), `username` (filter Actors by owner username), +`pricingModel` (filter by pricing model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`; the +deprecated rental model `FLAT_PRICE_PER_MONTH` is no longer listed), `includeUnrunnableActors` (include Actors the current user cannot run), `allowsAgenticUsers` (only Actors that allow agentic users), `responseFormat` (the response shape: `full` or `agent`). +A `search` returns the Actors ranked by relevance as a single page of at most 100: the API ignores +`offset` and has no second page. `iterate` therefore sends one request for a search, with the +options' `limit` as its size, and `chunkSize` and `offset` have no effect. Narrow a search with +`category`, `username` or `pricingModel`. + ```java // Publishers.collect() drains the whole publisher; fine here since `limit` already caps it. // To stop early without fetching further pages, subscribe with your own Flow.Subscriber instead @@ -28,9 +36,13 @@ items.forEach(item -> System.out.println(item.getUsername() + "/" + item.getName ``` `ActorStoreListItem` fields: `getId()`, `getName()`, `getUsername()`, `getTitle()`, -`getDescription()`, `getStats()` (`ActorStats`; see [Actors](actors.md#actorclient)), -`getCurrentPricingInfo()` (`PricingInfo`: `getPricingModel()`), `getPictureUrl()`, -`getUserPictureUrl()`, `getUrl()`, `getReadmeSummary()`. Any field not covered by a typed getter is +`getUserFullName()`, `getDescription()`, `getCategories()` (`List` of category IDs), +`getNotice()`, `getStats()` (`StoreActorStats`: `getTotalUsers()`, `getTotalRuns()`, +`getTotalUsers7Days()`, `getTotalUsers30Days()`, `getTotalUsers90Days()`, `getActorReviewRating()`, +`getActorReviewCount()`), `getCurrentPricingInfo()` (`PricingInfo`: `getPricingModel()`), +`getIsWhiteListedForAgenticPayments()`, `getIsVerified()` (whether the developer has a verified +identity), `getBadge()`, `getPictureUrl()`, `getUserPictureUrl()`, `getUrl()`, +`getReadmeSummary()`. Any field not covered by a typed getter is still available via the inherited `getExtra()` (see [the docs index](README.md#model-fields-and-unmodeled-data-getextra)). diff --git a/pom.xml b/pom.xml index baf59cd..034c22e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.apify apify-client - 0.14.1 + 0.15.0 jar Apify Java Client diff --git a/src/main/java/com/apify/client/Version.java b/src/main/java/com/apify/client/Version.java index 0654df4..3bef73f 100644 --- a/src/main/java/com/apify/client/Version.java +++ b/src/main/java/com/apify/client/Version.java @@ -13,7 +13,7 @@ public final class Version { * The semantic version of this client library (see SemVer). * Changes to the public interface other than additive ones are considered breaking changes. */ - public static final String CLIENT_VERSION = "0.14.1"; + public static final String CLIENT_VERSION = "0.15.0"; /** * The version of the Apify OpenAPI specification this client was generated and verified against. diff --git a/src/main/java/com/apify/client/actor/ActorCollectionClient.java b/src/main/java/com/apify/client/actor/ActorCollectionClient.java index 75dc2ce..6dc815b 100644 --- a/src/main/java/com/apify/client/actor/ActorCollectionClient.java +++ b/src/main/java/com/apify/client/actor/ActorCollectionClient.java @@ -18,7 +18,11 @@ public ActorCollectionClient(HttpClientCore http, String baseUrl) { ActorListOptions::new); } - /** Creates a new Actor. {@code actor} is any JSON-serializable Actor definition. */ + /** + * Creates a new Actor. {@code actor} is any JSON-serializable Actor definition. Fails with a + * {@link com.apify.client.http.ConflictError} (409, {@code actor-name-not-unique}) if you already + * have an Actor with the same name. + */ public CompletableFuture create(Object actor) { return ctx.createResource(new QueryParams(), actor, Actor.class, Timeout.MEDIUM); } diff --git a/src/main/java/com/apify/client/actor/ActorVersionClient.java b/src/main/java/com/apify/client/actor/ActorVersionClient.java index e48b30c..cbb2cd0 100644 --- a/src/main/java/com/apify/client/actor/ActorVersionClient.java +++ b/src/main/java/com/apify/client/actor/ActorVersionClient.java @@ -1,5 +1,6 @@ package com.apify.client.actor; +import com.apify.client.http.Timeout; import com.apify.client.internal.HttpClientCore; import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; @@ -26,9 +27,12 @@ public CompletableFuture> get() { return ctx.getResource("", new QueryParams(), ActorVersion.class); } - /** Updates the version with the given fields and returns the updated object. */ + /** + * Updates the version with the given fields and returns the updated object. The request uses the + * long timeout tier, since the version can carry its source files. + */ public CompletableFuture update(Object newFields) { - return ctx.updateResource("", newFields, ActorVersion.class); + return ctx.updateResource("", newFields, ActorVersion.class, Timeout.LONG); } /** Deletes the version. */ diff --git a/src/main/java/com/apify/client/actor/ActorVersionCollectionClient.java b/src/main/java/com/apify/client/actor/ActorVersionCollectionClient.java index 65f47f8..335fa52 100644 --- a/src/main/java/com/apify/client/actor/ActorVersionCollectionClient.java +++ b/src/main/java/com/apify/client/actor/ActorVersionCollectionClient.java @@ -49,8 +49,11 @@ public Flow.Publisher iterate(ListOptions options) { return new ListPublisher<>(items); } - /** Creates a new Actor version. {@code version} is any JSON-serializable version definition. */ + /** + * Creates a new Actor version. {@code version} is any JSON-serializable version definition. The + * request uses the long timeout tier, since the version can carry its source files. + */ public CompletableFuture create(Object version) { - return ctx.createResource(new QueryParams(), version, ActorVersion.class); + return ctx.createResource(new QueryParams(), version, ActorVersion.class, Timeout.LONG); } } diff --git a/src/main/java/com/apify/client/run/ActorRunMeta.java b/src/main/java/com/apify/client/run/ActorRunMeta.java index e49b721..abcec3f 100644 --- a/src/main/java/com/apify/client/run/ActorRunMeta.java +++ b/src/main/java/com/apify/client/run/ActorRunMeta.java @@ -15,7 +15,10 @@ public final class ActorRunMeta extends ApifyResource { private String scheduledAct2Id; private String scheduledActorTaskId; - /** What triggered the run (e.g. {@code "WEB"}, {@code "API"}, {@code "SCHEDULER"}). */ + /** + * What triggered the run (e.g. {@code "WEB"}, {@code "API"}, {@code "SCHEDULER"}, {@code + * "APIFY_AI"} for a run started from the Apify AI chat). + */ public String getOrigin() { return origin; } diff --git a/src/main/java/com/apify/client/store/ActorStoreListItem.java b/src/main/java/com/apify/client/store/ActorStoreListItem.java index ed25137..0383367 100644 --- a/src/main/java/com/apify/client/store/ActorStoreListItem.java +++ b/src/main/java/com/apify/client/store/ActorStoreListItem.java @@ -1,8 +1,9 @@ package com.apify.client.store; import com.apify.client.ApifyResource; -import com.apify.client.actor.ActorStats; import com.apify.client.internal.NormalizedUrlDeserializer; +import java.util.Collections; +import java.util.List; import tools.jackson.databind.annotation.JsonDeserialize; /** An Actor as listed in the Apify Store. */ @@ -11,9 +12,15 @@ public final class ActorStoreListItem extends ApifyResource { private String name; private String username; private String title; + private String userFullName; private String description; - private ActorStats stats; + private List categories = List.of(); + private String notice; + private StoreActorStats stats; private PricingInfo currentPricingInfo; + private Boolean isWhiteListedForAgenticPayments; + private Boolean isVerified; + private String badge; private String pictureUrl; @JsonDeserialize(using = NormalizedUrlDeserializer.class) @@ -44,13 +51,35 @@ public String getTitle() { return title; } + /** The full name of the Actor's owner, if set. */ + public String getUserFullName() { + return userFullName; + } + /** A description of what the Actor does. */ public String getDescription() { return description; } - /** Usage and run statistics for the Actor. */ - public ActorStats getStats() { + /** + * The IDs of the Store categories the Actor belongs to, e.g. {@code "AI_AND_ML"}. Empty when the + * Actor has none. + */ + public List getCategories() { + return categories == null ? List.of() : Collections.unmodifiableList(categories); + } + + /** + * A warning displayed on the Actor's Store page: {@code "NONE"}, {@code + * "RESIDENTIAL_PROXY_REQUIRED"} or {@code "UNDER_MAINTENANCE"}. Can be set by the Actor's + * developer or automatically by Apify's quality checks. + */ + public String getNotice() { + return notice; + } + + /** Usage statistics and Apify Store metrics of the Actor. */ + public StoreActorStats getStats() { return stats; } @@ -59,6 +88,21 @@ public PricingInfo getCurrentPricingInfo() { return currentPricingInfo; } + /** Whether the Actor is whitelisted for agentic payment processing. */ + public Boolean getIsWhiteListedForAgenticPayments() { + return isWhiteListedForAgenticPayments; + } + + /** Whether the Actor's developer has a verified identity. */ + public Boolean getIsVerified() { + return isVerified; + } + + /** The badge shown for the Actor in the Store, if any. */ + public String getBadge() { + return badge; + } + /** URL of the Actor's picture, if set. */ public String getPictureUrl() { return pictureUrl; diff --git a/src/main/java/com/apify/client/store/StoreActorStats.java b/src/main/java/com/apify/client/store/StoreActorStats.java new file mode 100644 index 0000000..76810c8 --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreActorStats.java @@ -0,0 +1,49 @@ +package com.apify.client.store; + +import com.apify.client.ApifyResource; + +/** Actor usage statistics and Apify Store metrics returned by the Store endpoint. */ +public final class StoreActorStats extends ApifyResource { + private Long totalUsers; + private Long totalRuns; + private Long totalUsers7Days; + private Long totalUsers30Days; + private Long totalUsers90Days; + private Double actorReviewRating; + private Long actorReviewCount; + + /** The total number of Actor users, including its owner. */ + public Long getTotalUsers() { + return totalUsers; + } + + /** The total number of runs of the Actor. */ + public Long getTotalRuns() { + return totalRuns; + } + + /** The number of active users of the Actor in the last 7 days. */ + public Long getTotalUsers7Days() { + return totalUsers7Days; + } + + /** The number of active users of the Actor in the last 30 days. */ + public Long getTotalUsers30Days() { + return totalUsers30Days; + } + + /** The number of active users of the Actor in the last 90 days. */ + public Long getTotalUsers90Days() { + return totalUsers90Days; + } + + /** The average rating of the Actor in Apify Store. */ + public Double getActorReviewRating() { + return actorReviewRating; + } + + /** The number of reviews the Actor has received in Apify Store. */ + public Long getActorReviewCount() { + return actorReviewCount; + } +} diff --git a/src/main/java/com/apify/client/store/StoreCollectionClient.java b/src/main/java/com/apify/client/store/StoreCollectionClient.java index c80916b..62eb77f 100644 --- a/src/main/java/com/apify/client/store/StoreCollectionClient.java +++ b/src/main/java/com/apify/client/store/StoreCollectionClient.java @@ -1,9 +1,15 @@ package com.apify.client.store; +import com.apify.client.PaginationList; import com.apify.client.internal.AbstractCollectionClient; import com.apify.client.internal.ApiPaths; import com.apify.client.internal.HttpClientCore; +import com.apify.client.internal.ListPublisher; +import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Flow; /** A client for browsing the Apify Store ({@code GET /v2/store}). */ public final class StoreCollectionClient @@ -15,4 +21,28 @@ public StoreCollectionClient(HttpClientCore http, String baseUrl) { ActorStoreListItem.class, StoreListOptions::new); } + + /** + * As {@link AbstractCollectionClient#iterate(com.apify.client.internal.ListOptionsLike, Long)}, + * except that a search returns a single page: the API ignores {@code offset} and has no second + * page, so paging would read the same page forever. The request is then sent once, when {@code + * iterate} is called, with the options' {@code limit} (when positive) as its page size and cap; + * {@code chunkSize} and {@code offset} have no effect. + */ + @Override + public Flow.Publisher iterate(StoreListOptions options, Long chunkSize) { + StoreListOptions opts = options != null ? options : defaultOptions(); + if (!opts.hasSearch()) { + return super.iterate(opts, chunkSize); + } + Long limit = opts.limitValue(); + QueryParams params = new QueryParams(); + opts.applyFilters(params); + if (limit != null && limit > 0) { + params.addLong("limit", limit); + } + CompletableFuture> items = + listWithParams(params).thenApply(PaginationList::getItems); + return new ListPublisher<>(items); + } } diff --git a/src/main/java/com/apify/client/store/StoreListOptions.java b/src/main/java/com/apify/client/store/StoreListOptions.java index 69ce18e..945bcb2 100644 --- a/src/main/java/com/apify/client/store/StoreListOptions.java +++ b/src/main/java/com/apify/client/store/StoreListOptions.java @@ -17,34 +17,53 @@ public final class StoreListOptions implements ListOptionsLike { private String responseFormat; private Boolean includeInputSchema; - /** Number of Actors to skip. */ + /** Number of Actors to skip. The API ignores it when {@link #search(String)} is used. */ public StoreListOptions offset(Long offset) { this.offset = offset; return this; } /** - * Maximum number of Actors to return. Sent verbatim by {@code list(...)} (so {@code 0} returns - * zero Actors); in {@code iterate(...)} a non-positive/zero {@code limit} means "no cap" (all). + * Maximum number of Actors to return. The API default and maximum is {@code 1000}; when {@link + * #search(String)} is used, both are {@code 100} and a larger value is reduced to {@code 100}. + * Sent verbatim by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} + * a non-positive/zero {@code limit} means "no cap" (all). */ public StoreListOptions limit(Long limit) { this.limit = limit; return this; } - /** Full-text search query. */ + /** + * Search query. The API ranks the results by relevance and returns them as a single page of at + * most 100 Actors: {@link #offset(Long)} is ignored and there is no second page. Narrow the + * results with {@link #category(String)}, {@link #username(String)} or {@link + * #pricingModel(String)}. + */ public StoreListOptions search(String search) { this.search = search; return this; } - /** The sort field (e.g. {@code "popularity"}, {@code "newest"}). */ + /** + * Accepted for backward compatibility, but the API ignores it. The results are ordered by + * relevance when {@link #search(String)} is used and by Store position otherwise; sort them on + * the client for a different order. + * + * @deprecated the API ignores the value + */ + @Deprecated public StoreListOptions sortBy(String sortBy) { this.sortBy = sortBy; return this; } - /** Filter Actors by category. */ + /** + * Filter Actors by category. Accepts one or more category IDs (e.g. {@code "AI_AND_ML"}), + * separated by commas and case-insensitive; an Actor must match all of them. Legacy keys such as + * {@code social_media} are still accepted, and an unknown category fails with a {@code 400} + * error. + */ public StoreListOptions category(String category) { this.category = category; return this; @@ -94,6 +113,11 @@ public StoreListOptions includeInputSchema(Boolean includeInputSchema) { return this; } + /** Whether a non-empty search query is set, which makes the API return a single page. */ + boolean hasSearch() { + return search != null && !search.isEmpty(); + } + @Override public Long limitValue() { return limit; diff --git a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java index 7c5c38f..944dcab 100644 --- a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java +++ b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -526,6 +527,70 @@ void storeIterateWalksMultiplePages() { assertEquals(3, backend.calls, "two data pages plus the terminating empty page"); } + @Test + void storeSearchIterationSendsASingleRequestWithoutAnOffset() { + // The Store ignores `offset` for a search and has no second page, so paging would read the same + // page forever: the iteration must send one request and then complete. + MockTransport backend = + MockTransport.ofConstant( + 200, + "{\"data\":{\"items\":[{\"id\":\"a\"},{\"id\":\"b\"}],\"total\":2,\"offset\":0," + + "\"limit\":100,\"count\":2}}"); + StoreListOptions options = new StoreListOptions().search("crawler").offset(5L); + List items = + Publishers.collect(client(backend).store().iterate(options, 1L)).join(); + assertEquals(2, items.size()); + assertEquals(1, backend.calls, "a search is one page"); + assertTrue(backend.lastUrl.contains("search=crawler"), backend.lastUrl); + assertFalse(backend.lastUrl.contains("offset="), backend.lastUrl); + assertFalse(backend.lastUrl.contains("limit="), backend.lastUrl); + } + + @Test + void storeSearchIterationSendsTheLimitAsThePageSize() { + MockTransport backend = + MockTransport.ofConstant( + 200, + "{\"data\":{\"items\":[{\"id\":\"a\"}],\"total\":1,\"offset\":0,\"limit\":10,\"count\":1}}"); + Publishers.collect( + client(backend).store().iterate(new StoreListOptions().search("x").limit(10L), null)) + .join(); + assertEquals(1, backend.calls); + assertTrue(backend.lastUrl.contains("limit=10"), backend.lastUrl); + } + + @Test + void storeItemParsesTheStoreShape() { + MockTransport backend = + MockTransport.ofConstant( + 200, + "{\"data\":{\"items\":[{\"id\":\"a\",\"userFullName\":\"Jane Doe\"," + + "\"categories\":[\"AI_AND_ML\",\"GENERATE_LEADS\"],\"notice\":\"UNDER_MAINTENANCE\"," + + "\"stats\":{\"totalUsers\":6,\"totalRuns\":16,\"totalUsers7Days\":2," + + "\"totalUsers30Days\":6,\"totalUsers90Days\":6,\"actorReviewRating\":4.7," + + "\"actorReviewCount\":69},\"isWhiteListedForAgenticPayments\":true," + + "\"isVerified\":true,\"badge\":null}," + + "{\"id\":\"b\",\"categories\":null,\"stats\":{\"totalUsers\":1}}]," + + "\"total\":2,\"offset\":0,\"limit\":2,\"count\":2}}"); + List items = + client(backend).store().list(new StoreListOptions()).join().getItems(); + ActorStoreListItem first = items.get(0); + assertEquals("Jane Doe", first.getUserFullName()); + assertEquals(List.of("AI_AND_ML", "GENERATE_LEADS"), first.getCategories()); + assertEquals("UNDER_MAINTENANCE", first.getNotice()); + assertEquals(6L, first.getStats().getTotalUsers()); + assertEquals(16L, first.getStats().getTotalRuns()); + assertEquals(2L, first.getStats().getTotalUsers7Days()); + assertEquals(6L, first.getStats().getTotalUsers30Days()); + assertEquals(6L, first.getStats().getTotalUsers90Days()); + assertEquals(4.7, first.getStats().getActorReviewRating()); + assertEquals(69L, first.getStats().getActorReviewCount()); + assertEquals(Boolean.TRUE, first.getIsWhiteListedForAgenticPayments()); + assertEquals(Boolean.TRUE, first.getIsVerified()); + assertNull(first.getBadge()); + assertTrue(items.get(1).getCategories().isEmpty(), "null categories read as an empty list"); + } + @Test void storeIterateSkipsEntriesTheApiDroppedAfterCountingThem() { // The Store list can drop entries after counting them: a page that counted 2 rows returns 1 diff --git a/src/test/java/com/apify/client/TimeoutTierTest.java b/src/test/java/com/apify/client/TimeoutTierTest.java index 036fc97..cb5e397 100644 --- a/src/test/java/com/apify/client/TimeoutTierTest.java +++ b/src/test/java/com/apify/client/TimeoutTierTest.java @@ -79,6 +79,22 @@ void keyValueStoreUpdateAndRequestQueueUnlockFollowTheReferenceTiers() { assertEquals(secs(360), backend.lastTimeout); } + @Test + void actorVersionCreateAndUpdateUseTheLongTier() { + // A version can carry its source files, so uploading one gets the long tier like other uploads. + MockTransport backend = MockTransport.ofConstant(200, "{\"data\":{\"versionNumber\":\"0.0\"}}"); + client(backend).actor("a1").versions().create(Map.of("versionNumber", "0.0")).join(); + assertEquals(secs(360), backend.lastTimeout); + + backend = MockTransport.ofConstant(200, "{\"data\":{\"versionNumber\":\"0.0\"}}"); + client(backend).actor("a1").version("0.0").update(Map.of("buildTag", "latest")).join(); + assertEquals(secs(360), backend.lastTimeout); + + backend = MockTransport.ofConstant(200, "{\"data\":{\"versionNumber\":\"0.0\"}}"); + client(backend).actor("a1").version("0.0").get().join(); + assertEquals(secs(5), backend.lastTimeout, "reading a version stays on the short tier"); + } + @Test void startIsMediumExtendedByTheWaitForFinishHold() { MockTransport backend = MockTransport.ofConstant(201, RUN_JSON); diff --git a/src/test/java/com/apify/client/integration/StoreIntegrationTest.java b/src/test/java/com/apify/client/integration/StoreIntegrationTest.java index df562b2..49d4d48 100644 --- a/src/test/java/com/apify/client/integration/StoreIntegrationTest.java +++ b/src/test/java/com/apify/client/integration/StoreIntegrationTest.java @@ -1,8 +1,10 @@ package com.apify.client.integration; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.apify.client.ApifyClient; +import com.apify.client.Publishers; import com.apify.client.store.ActorStoreListItem; import com.apify.client.store.StoreListOptions; import java.util.concurrent.CompletableFuture; @@ -19,6 +21,38 @@ void listStore() { assertTrue(page.getItems().size() <= 5); } + @Test + void listStoreAcceptsTheDeprecatedSortBy() { + ApifyClient client = requireClient(); + // The API accepts `sortBy` for compatibility but ignores it, so the order is not asserted. + @SuppressWarnings("deprecation") + StoreListOptions options = new StoreListOptions().limit(5L).sortBy("popularity"); + var page = client.store().list(options).join(); + assertFalse(page.getItems().isEmpty()); + } + + @Test + void listStoreItemsCarryTheStoreStats() { + ApifyClient client = requireClient(); + var page = client.store().list(new StoreListOptions().limit(5L)).join(); + assertFalse(page.getItems().isEmpty()); + assertTrue( + page.getItems().stream() + .allMatch(item -> item.getStats() != null && item.getStats().getTotalUsers() != null), + "every listed Actor has stats.totalUsers"); + } + + @Test + void searchReturnsASinglePageAndIterationCompletes() { + ApifyClient client = requireClient(); + // A search is one page of at most 100 Actors, so iterating it without a limit must complete. + var items = + Publishers.collect(client.store().iterate(new StoreListOptions().search("crawler"), null)) + .join(); + assertFalse(items.isEmpty()); + assertTrue(items.size() <= 100, "a search returns at most 100 Actors, got " + items.size()); + } + @Test void listStoreWithInputSchema() { ApifyClient client = requireClient(); From 4f65616d1bd055608545f083447bfcf69404f23a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:08:18 +0000 Subject: [PATCH 02/19] feat: accept InputStream request bodies, add streamed record read, and address review feedback --- CHANGELOG.md | 15 +- docs/README.md | 2 +- docs/actors.md | 7 +- docs/misc.md | 14 +- docs/storages.md | 17 +- docs/tasks.md | 2 +- .../com/apify/client/actor/ActorClient.java | 10 +- .../apify/client/actor/ActorServerClient.java | 74 +++- .../actor/ActorServerRequestOptions.java | 13 +- .../apify/client/actor/ActorStartOptions.java | 3 +- .../apify/client/internal/HttpClientCore.java | 136 ++++++- .../java/com/apify/client/internal/Json.java | 8 + .../apify/client/internal/RequestPolicy.java | 15 + .../client/internal/ResourceContext.java | 56 +++ .../client/internal/RunStartSupport.java | 9 +- .../client/keyvalue/KeyValueStoreClient.java | 95 ++++- .../keyvalue/KeyValueStoreRecordStream.java | 46 +++ .../client/store/ActorStoreListItem.java | 2 +- .../apify/client/store/StoreListOptions.java | 2 +- .../com/apify/client/task/TaskClient.java | 5 +- .../java/com/apify/client/MockTransport.java | 1 + .../java/com/apify/client/StreamBodyTest.java | 373 ++++++++++++++++++ .../java/com/apify/client/TestHttpServer.java | 33 +- .../KeyValueStoreIntegrationTest.java | 28 ++ 24 files changed, 895 insertions(+), 71 deletions(-) create mode 100644 src/main/java/com/apify/client/keyvalue/KeyValueStoreRecordStream.java create mode 100644 src/test/java/com/apify/client/StreamBodyTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 36bafac..92c99e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,16 +9,21 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Added -- `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating` and `actorReviewCount`. -- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isWhiteListedForAgenticPayments`, `isVerified` and `badge`. +- `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating`, and `actorReviewCount`. +- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isWhiteListedForAgenticPayments`, `isVerified`, and `badge`. +- `KeyValueStoreClient.setRecord` overloads that take an `InputStream`. The stream is sent without being held in memory, and the upload is not retried or compressed. +- `KeyValueStoreClient.getRecordStream` and `KeyValueStoreRecordStream`, which read a record as an `InputStream`. +- `InputStream` as the input of `ActorClient.start`, `ActorClient.call`, `TaskClient.start`, and `TaskClient.call`, and as the body of `ActorServerClient.request` and `requestStream`. A stream is sent once, with no retry. +- `APIFY_AI` run origin. ### Changed -- `ActorStoreListItem.getStats()` returns `StoreActorStats`, which matches the Store response. The Store no longer returns `totalBuilds`, `totalMetamorphs` and `lastRunStartedAt`. -- Synced with the published Apify OpenAPI specification (still `v2-2026-11-18T151559Z`): a Store search returns one page of at most 100 Actors ranked by relevance and ignores `offset`, `category` takes comma-separated category IDs, and `APIFY_AI` is a run origin. -- `StoreCollectionClient.iterate` sends one request for a search, since the Store has no second page for it. +- **Breaking:** `ActorStoreListItem.getStats()` returns `StoreActorStats` instead of `ActorStats`. The Store no longer returns `totalBuilds`, `totalMetamorphs`, and `lastRunStartedAt`. +- **Breaking:** `StoreCollectionClient.iterate` sends one request when `search` is set, since the Store returns a single page of at most 100 Actors for a search and ignores `offset`. `chunkSize` and `offset` have no effect for a search. +- `StoreListOptions.category` takes comma-separated category IDs. - `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. - Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). +- `ActorClient.validateInput` and `RunClient.metamorph` throw `IllegalArgumentException` for an `InputStream` input, instead of serializing it to JSON. ### Deprecated diff --git a/docs/README.md b/docs/README.md index a50ead6..f3e08ed 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,7 +48,7 @@ option types, so import each resource you use from its own package: | `com.apify.client.build` | `Build`, `BuildClient`, `BuildCollectionClient`, `BuildActVersion`, `ActorDefinition`, `ActorDefinitionMeta`, `ActorDefinitionStorages`, `BuildMeta`, `BuildStats`, `BuildOptions`, `BuildUsage` | | `com.apify.client.run` | `ActorRun`, `ActorRunStats`, `ActorRunOptions`, `ActorRunMeta`, `ActorRunStandby`, `ActorRunUsage`, `RunClient`, `RunCollectionClient`, `RunListOptions`, `LastRunOptions`, `MetamorphOptions`, `RunChargeOptions`, `RunResurrectOptions`, `SetStatusMessageOptions` | | `com.apify.client.dataset` | `Dataset`, `DatasetClient`, `DatasetCollectionClient`, `DatasetListItemsOptions`, `DatasetDownloadOptions`, `DownloadItemsFormat` | -| `com.apify.client.keyvalue` | `KeyValueStore`, `KeyValueStoreClient`, `KeyValueStoreCollectionClient`, `KeyValueStoreRecord`, `KeyValueStoreKeysPage`, `KeyValueStoreKey`, `GetRecordOptions`, `SetRecordOptions`, `ListKeysOptions` | +| `com.apify.client.keyvalue` | `KeyValueStore`, `KeyValueStoreClient`, `KeyValueStoreCollectionClient`, `KeyValueStoreRecord`, `KeyValueStoreRecordStream`, `KeyValueStoreKeysPage`, `KeyValueStoreKey`, `GetRecordOptions`, `SetRecordOptions`, `ListKeysOptions` | | `com.apify.client.requestqueue` | `RequestQueue`, `RequestQueueClient`, `RequestQueueCollectionClient`, `RequestQueueRequest`, `RequestQueueHead`, `LockedRequestQueueHead`, `RequestQueueOperationInfo`, `RequestLockInfo`, `UnlockRequestsResult`, `RequestsList`, `BatchAddResult`, `BatchDeleteResult`, `DeletedRequestInfo`, `ListRequestsOptions`, `BatchAddRequestsOptions` | | `com.apify.client.task` | `Task`, `TaskStats`, `TaskOptions`, `TaskClient`, `TaskCollectionClient`, `TaskStartOptions`, `TaskCallOptions` | | `com.apify.client.schedule` | `Schedule`, `ScheduleNotifications`, `ScheduleClient`, `ScheduleCollectionClient` | diff --git a/docs/actors.md b/docs/actors.md index ab38e71..0d27433 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -46,7 +46,7 @@ Actor created = client.actors().create(Map.of( | `get()` | Fetch the Actor. Completes with `Optional`. | | `update(Object)` | Update the Actor with the given fields. Completes with `Actor`. | | `delete()` | Delete the Actor. | -| `start(Object input, ActorStartOptions)` | Start a run, returning immediately. Completes with `ActorRun`. The `input` is any JSON-serializable value, or a `byte[]`/`String` that is sent as it is (set the matching `ActorStartOptions.contentType(...)`), or `null`. | +| `start(Object input, ActorStartOptions)` | Start a run, returning immediately. Completes with `ActorRun`. The `input` is any JSON-serializable value, or a `byte[]`, `String` or `InputStream` that is sent as it is (set the matching `ActorStartOptions.contentType(...)`), or `null`. A stream is read once, so its start is sent once: it is not retried, even with `waitForResources`. | | `call(Object input, ActorStartOptions, Long waitSecs)` | Start a run and poll until it finishes (`null` waits indefinitely); does **not** stream the run's log. Completes with `ActorRun`. | | `call(Object input, ActorCallOptions, Long waitSecs)` | As above, additionally streaming the run's log for the duration of the wait by default. Use `ActorCallOptions.disableLogStreaming()` to opt out, or `logOptions(StreamedLogOptions)` for a custom destination. | | `validateInput(Object input)` / `validateInput(Object input, ValidateInputOptions)` | Validate an input against the Actor's input schema. Completes with `boolean`. `ValidateInputOptions` fields (optional): `build` (`String`), `contentType` (`String`). | @@ -131,8 +131,9 @@ Actor's `standbyUrl` and `actorStandby` fields. `ActorServerRequestOptions` fields (all optional): `method(String)` (`GET` by default; also `HEAD`, `POST`, `PUT`, `DELETE`, `OPTIONS`, `TRACE`, `PATCH`), `param(String, Object)`/`params(Map)` (query parameters, converted as for API calls: `null` is left out, a boolean is sent as `1`/`0`, a -collection comma-joined), `header(String, String)`/`headers(Map)`, `body(Object)` (a `byte[]` or -`String` is sent as it is; anything else is serialized to JSON and sent as `application/json` +collection comma-joined), `header(String, String)`/`headers(Map)`, `body(Object)` (a `byte[]`, +`String` or `InputStream` is sent as it is, and a stream is sent once, with no retry and no +compression; anything else is serialized to JSON and sent as `application/json` unless you set a `Content-Type` header), `parentRequestId(String)` (see [Calling a Server Actor from a Server Actor](#calling-a-server-actor-from-a-server-actor)), `compression(HttpCompressor)` and `timeout(Timeout)` diff --git a/docs/misc.md b/docs/misc.md index 4ba3980..6a32172 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -7,7 +7,7 @@ Browse public Actors in the Apify Store. `client.store()` returns a `StoreCollec | Method | Description | |---|---| | `list(StoreListOptions)` | A page of Store Actors. Completes with `PaginationList`. | -| `iterate(StoreListOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all matches, fetching pages on demand. The options' `limit` caps the total number of rows read, which are the Actors yielded unless the API drops entries after counting them (`null`/unset or non-positive = all); `chunkSize` is the per-request page size (`null` = server default). | +| `iterate(StoreListOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all matches, fetching pages on demand. The options' `limit` caps the total number of rows read, which are the Actors yielded unless the API drops entries after counting them (`null`/unset or non-positive = all); `chunkSize` is the per-request page size (`null` = server default). With `search` there is a single page instead: see below. | `StoreListOptions` fields: `offset` (number of Actors to skip), `limit` (maximum number of Actors to return; the API default and maximum is 1000, or 100 with `search`), `search` (search query), @@ -21,18 +21,22 @@ deprecated rental model `FLAT_PRICE_PER_MONTH` is no longer listed), Actors that allow agentic users), `responseFormat` (the response shape: `full` or `agent`). A `search` returns the Actors ranked by relevance as a single page of at most 100: the API ignores -`offset` and has no second page. `iterate` therefore sends one request for a search, with the -options' `limit` as its size, and `chunkSize` and `offset` have no effect. Narrow a search with -`category`, `username` or `pricingModel`. +`offset` and has no second page. `iterate` therefore sends one request for a search, when you call +`iterate` rather than on first demand, with the options' `limit` as its size. `chunkSize` and +`offset` have no effect. Narrow a search with `category`, `username`, or `pricingModel`. ```java // Publishers.collect() drains the whole publisher; fine here since `limit` already caps it. // To stop early without fetching further pages, subscribe with your own Flow.Subscriber instead // (request(1) at a time, cancel() once you have enough); see IterateStore.java in the examples. List items = - Publishers.collect(client.store().iterate(new StoreListOptions().search("crawler").limit(20L), 10L)) + Publishers.collect(client.store().iterate(new StoreListOptions().username("apify").limit(20L), 10L)) .join(); items.forEach(item -> System.out.println(item.getUsername() + "/" + item.getName())); + +// A search is one page of at most 100 Actors. +List found = + Publishers.collect(client.store().iterate(new StoreListOptions().search("crawler"), null)).join(); ``` `ActorStoreListItem` fields: `getId()`, `getName()`, `getUsername()`, `getTitle()`, diff --git a/docs/storages.md b/docs/storages.md index 552dbeb..0c5cfed 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -142,6 +142,8 @@ datasets. | `getRecord(String key)` / `getRecord(String key, GetRecordOptions)` | Fetch a record. Completes with `Optional`. | | `setRecord(String key, byte[] value, String contentType)` | Store raw bytes. Completes with no value (`CompletableFuture`). | | `setRecord(String key, byte[] value, String contentType, SetRecordOptions)` | Store raw bytes with write options (`SetRecordOptions`: `timeoutSecs` (`Long`) or `timeout` (`Timeout`: a tier, an exact duration or `NO_TIMEOUT`; the default is the `LONG` tier), `doNotRetryTimeouts` (`Boolean`), `contentEncoding` (`String`, see below)). Completes with no value. | +| `getRecordStream(String key)` / `getRecordStream(String key, GetRecordOptions)` | As `getRecord`, but completes with an `Optional` whose `getValue()` is a live `InputStream`, so a large record is processed in chunks. Close the record (or read its stream to the end) when done. Throws on any error response other than a 404, which completes with empty. | +| `setRecord(String key, InputStream value, String contentType)` / `setRecord(String key, InputStream value, String contentType, SetRecordOptions)` | Store the bytes read from a stream, without holding them in memory, so a large file can be uploaded. The stream is closed once it is read. It can be read once, so the upload is sent once: it is not retried or compressed, and `doNotRetryTimeouts` has no effect. Completes with no value. | | `setRecordJson(String key, Object value)` | Store JSON. Completes with no value. | | `deleteRecord(String key)` | Delete a record. Completes with no value. | | `getRecordPublicUrl(String key)` | A public (optionally signed) record URL. Completes with `String`. | @@ -184,7 +186,20 @@ client.keyValueStore("my-store") .join(); ``` -`KeyValueStoreRecord` exposes `getKey()`, `getValue()` (raw bytes) and `getContentType()`. +Copy a large record without reading it into memory by passing the stream of one call to the other: + +```java +try (KeyValueStoreRecordStream source = + client.keyValueStore("my-store").getRecordStream("video.mp4").join().orElseThrow()) { + client.keyValueStore("other-store") + .setRecord("video.mp4", source.getValue(), source.getContentType()) + .join(); +} +``` + +`KeyValueStoreRecord` exposes `getKey()`, `getValue()` (raw bytes) and `getContentType()`; +`KeyValueStoreRecordStream` exposes `getKey()`, `getValue()` (the `InputStream`), `getContentType()` +and `close()`. `KeyValueStoreKeysPage` exposes `getItems()` (a list of `KeyValueStoreKey` with `getKey()`/`getSize()`), `isTruncated()`, `getExclusiveStartKey()` and `getNextExclusiveStartKey()`. diff --git a/docs/tasks.md b/docs/tasks.md index 1d41a7c..44e7989 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -25,7 +25,7 @@ Task task = client.tasks().create(Map.of( |---|---| | `get()` / `update(Object)` / `delete()` | CRUD. Complete with `Optional` / `Task` / no value. | | `publish()` / `unpublish()` | Publish/unpublish the task on its public landing page, by setting `isPublic` through `update(Object)`. Both require write permission to both the task and its Actor; `publish()` additionally requires the task's Actor to be public and a configured `publicConfig`. `unpublish()` preserves `publicConfig` so the task can be republished without re-entering it. Complete with the updated `Task`. | -| `start(Object input, TaskStartOptions)` | Start a task run (input overrides stored input; `null` uses it). Completes with `ActorRun`. | +| `start(Object input, TaskStartOptions)` | Start a task run (input overrides stored input; `null` uses it). Completes with `ActorRun`. As for an Actor, the `input` can be a `byte[]`, `String` or `InputStream` that is sent as it is; a stream is sent once, with no retry. | | `call(Object input, TaskStartOptions, Long waitSecs)` | Start and poll until finished; does **not** stream the run's log. Completes with `ActorRun`. | | `call(Object input, TaskCallOptions, Long waitSecs)` | As above, additionally streaming the run's log for the duration of the wait by default. Use `TaskCallOptions.disableLogStreaming()` to opt out, or `logOptions(StreamedLogOptions)` for a custom destination. | | `getInput()` | The stored input. Completes with `JsonNode`; throws `NotFoundError` if the task is gone (no separate "input absent" state). | diff --git a/src/main/java/com/apify/client/actor/ActorClient.java b/src/main/java/com/apify/client/actor/ActorClient.java index 65c8572..61ea096 100644 --- a/src/main/java/com/apify/client/actor/ActorClient.java +++ b/src/main/java/com/apify/client/actor/ActorClient.java @@ -16,6 +16,7 @@ import com.apify.client.run.RunClient; import com.apify.client.run.RunCollectionClient; import com.apify.client.webhook.NestedWebhookCollectionClient; +import java.io.InputStream; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; @@ -73,8 +74,13 @@ public CompletableFuture delete() { /** * Starts the Actor and completes with the created run as soon as it exists (no waiting). {@code - * input} is any JSON-serializable value, a {@code byte[]} or {@link String} that is sent as it is - * (set the content type with the options' {@code contentType}), or {@code null} for no input. + * input} is any JSON-serializable value, a {@code byte[]}, {@link String} or {@link InputStream} + * that is sent as it is (set the content type with the options' {@code contentType}), or {@code + * null} for no input. + * + *

An {@code InputStream} is read as it is sent, closed afterwards and never held in memory. It + * can be read once, so the start is sent once: a failed request is not retried, and a rejection + * for lack of resources is thrown even if {@code waitForResources} is set. */ public CompletableFuture start(Object input, ActorStartOptions options) { return RunStartSupport.start( diff --git a/src/main/java/com/apify/client/actor/ActorServerClient.java b/src/main/java/com/apify/client/actor/ActorServerClient.java index bbf9590..6635089 100644 --- a/src/main/java/com/apify/client/actor/ActorServerClient.java +++ b/src/main/java/com/apify/client/actor/ActorServerClient.java @@ -11,6 +11,8 @@ import com.apify.client.internal.QueryParams; import com.apify.client.internal.RequestPolicy; import com.apify.client.internal.ResourceContext; +import java.io.InputStream; +import java.net.http.HttpResponse; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; @@ -209,6 +211,20 @@ public CompletableFuture> getOpenApiSpec(Timeout timeout) { */ public CompletableFuture request(String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); + RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); + if (opts.bodyValue() instanceof InputStream stream) { + return getUrl() + .thenCompose( + serverUrl -> + http.callWithStream( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + stream, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy)); + } byte[] body = Json.toRequestBody(opts.bodyValue()); return getUrl() .thenCompose( @@ -221,7 +237,7 @@ public CompletableFuture request(String path, ActorServerRequestOpt opts.headersValue(), opts.timeoutValue(), false, - RequestPolicy.server(opts.compressionValue()))); + policy)); } /** A {@code GET} request to {@code path} on the Actor's server; see {@link #request}. */ @@ -246,22 +262,40 @@ public CompletableFuture request() { public CompletableFuture requestStream( String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); - byte[] body = Json.toRequestBody(opts.bodyValue()); - return getUrl() - .thenCompose( - serverUrl -> - http.streamRequest( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - body, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - RequestPolicy.server(opts.compressionValue()))) - .thenApply( - response -> - new ActorServerStreamResponse( - response.statusCode(), response.headers(), response.body())); + RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); + CompletableFuture> exchange; + if (opts.bodyValue() instanceof InputStream stream) { + exchange = + getUrl() + .thenCompose( + serverUrl -> + http.streamRequest( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + stream, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy)); + } else { + byte[] body = Json.toRequestBody(opts.bodyValue()); + exchange = + getUrl() + .thenCompose( + serverUrl -> + http.streamRequest( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + body, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy)); + } + return exchange.thenApply( + response -> + new ActorServerStreamResponse( + response.statusCode(), response.headers(), response.body())); } /** Fetches the Actor and checks that it is a Server Actor. */ @@ -394,7 +428,11 @@ private static String contentTypeOf(ActorServerRequestOptions options) { return set; } Object body = options.bodyValue(); - boolean sentAsIs = body == null || body instanceof byte[] || body instanceof String; + boolean sentAsIs = + body == null + || body instanceof byte[] + || body instanceof String + || body instanceof InputStream; return sentAsIs ? null : ResourceContext.CONTENT_TYPE_JSON; } } diff --git a/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java b/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java index 410a8af..620c972 100644 --- a/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java +++ b/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java @@ -3,6 +3,7 @@ import com.apify.client.http.HttpCompressor; import com.apify.client.http.Timeout; import com.apify.client.internal.QueryParams; +import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; @@ -85,10 +86,14 @@ public ActorServerRequestOptions headers(Map headers) { } /** - * The request body: a {@code byte[]} or a {@link String} is sent as it is (set its {@code - * Content-Type} with {@link #header}), and anything else, a {@link Map}, a list or a POJO, is - * serialized to JSON and sent as {@code application/json} unless a {@code Content-Type} header is - * set. + * The request body: a {@code byte[]}, a {@link String} or an {@link InputStream} is sent as it is + * (set its {@code Content-Type} with {@link #header}), and anything else, a {@link Map}, a list + * or a POJO, is serialized to JSON and sent as {@code application/json} unless a {@code + * Content-Type} header is set. + * + *

An {@code InputStream} is read as it is sent and closed afterwards, so it is never held in + * memory. It can be read once, so the request is sent once, with no retry (not even for a 429 or + * 503 response) and no compression. */ public ActorServerRequestOptions body(Object body) { this.body = body; diff --git a/src/main/java/com/apify/client/actor/ActorStartOptions.java b/src/main/java/com/apify/client/actor/ActorStartOptions.java index 888fb81..28b4388 100644 --- a/src/main/java/com/apify/client/actor/ActorStartOptions.java +++ b/src/main/java/com/apify/client/actor/ActorStartOptions.java @@ -101,7 +101,8 @@ public ActorStartOptions webhooks(List webhooks) { * API rejects it with {@code actor-memory-limit-exceeded} or {@code * concurrent-runs-limit-exceeded}), waiting 10 seconds between attempts. {@code true} retries * until the run starts ({@link #WAIT_FOR_RESOURCES_INDEFINITELY}); {@code false} (the default) - * does not retry and throws the error immediately. + * does not retry and throws the error immediately. An input that is an {@link + * java.io.InputStream} can be read once, so its start is never retried. */ public ActorStartOptions waitForResources(boolean waitForResources) { this.waitForResourcesSecs = waitForResources ? WAIT_FOR_RESOURCES_INDEFINITELY : null; diff --git a/src/main/java/com/apify/client/internal/HttpClientCore.java b/src/main/java/com/apify/client/internal/HttpClientCore.java index 0e5c685..e7ec91c 100644 --- a/src/main/java/com/apify/client/internal/HttpClientCore.java +++ b/src/main/java/com/apify/client/internal/HttpClientCore.java @@ -35,6 +35,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -346,7 +347,7 @@ public CompletableFuture call( return attemptWithRetry( method, url, - prepared.body(), + bytesPublisher(prepared.body()), contentType, prepared.headers(), baseTimeout, @@ -358,6 +359,55 @@ public CompletableFuture call( retry.minDelayBetweenRetries); } + /** + * Sends a request whose body is read from {@code body}, with auth and the User-Agent applied. A + * stream can be read once, so the request is sent exactly once: it is never retried or + * compressed, and a redirect that needs the body again fails the request instead of sending an + * empty body. {@code body} is closed once it is read. + */ + public CompletableFuture callWithStream( + String method, + String url, + InputStream body, + String contentType, + Map extraHeaders, + Timeout timeout, + RequestPolicy policy) { + return attemptWithRetry( + method, + url, + streamPublisher(body), + contentType, + extraHeaders, + resolveTimeout(timeout), + false, + policy.forStreamBody(), + extractPath(url), + 1, + 1, + retry.minDelayBetweenRetries); + } + + /** + * A single-use body publisher that reads {@code body}. A second subscription, which the JDK makes + * to send the body again for a 307 or 308 redirect, gets a stream that fails to read instead of + * the exhausted {@code body}, so the data is never silently replaced with an empty body. + */ + private static HttpRequest.BodyPublisher streamPublisher(InputStream body) { + AtomicBoolean handedOut = new AtomicBoolean(); + return HttpRequest.BodyPublishers.ofInputStream( + () -> handedOut.compareAndSet(false, true) ? body : new SentStream()); + } + + /** The body of a stream request that was already sent: reading it fails. */ + private static final class SentStream extends InputStream { + @Override + public int read() throws IOException { + throw new IOException( + "The request body is a stream that was already sent and cannot be sent again"); + } + } + /** A request body, as it is sent, with the headers that go with it. */ private record PreparedBody(byte[] body, Map headers) {} @@ -397,7 +447,7 @@ private PreparedBody prepareBody( private CompletableFuture attemptWithRetry( String method, String url, - byte[] body, + HttpRequest.BodyPublisher body, String contentType, Map headers, Duration baseTimeout, @@ -458,7 +508,7 @@ private record AttemptOutcome( private CompletableFuture attempt( String method, String url, - byte[] body, + HttpRequest.BodyPublisher body, String contentType, Map extraHeaders, Duration timeout, @@ -527,10 +577,26 @@ private HttpRequest buildRequest( Map extraHeaders, Duration timeout, RequestPolicy policy) { - HttpRequest.BodyPublisher publisher = - body != null - ? HttpRequest.BodyPublishers.ofByteArray(body) - : HttpRequest.BodyPublishers.noBody(); + return buildPublisherRequest( + method, url, bytesPublisher(body), contentType, extraHeaders, timeout, policy); + } + + /** A replayable body publisher for {@code body}, or an empty one for {@code null}. */ + private static HttpRequest.BodyPublisher bytesPublisher(byte[] body) { + return body != null + ? HttpRequest.BodyPublishers.ofByteArray(body) + : HttpRequest.BodyPublishers.noBody(); + } + + /** As {@link #buildRequest}, for a body that is already a publisher. */ + private HttpRequest buildPublisherRequest( + String method, + String url, + HttpRequest.BodyPublisher publisher, + String contentType, + Map extraHeaders, + Duration timeout, + RequestPolicy policy) { HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url)).method(method, publisher); if (timeout != null) { b.timeout(timeout); @@ -572,13 +638,13 @@ private static void moveAuthorization(Map headers, String name) private CompletableFuture doAttempt( String method, String url, - byte[] body, + HttpRequest.BodyPublisher body, String contentType, Map extraHeaders, Duration timeout, RequestPolicy policy) { HttpRequest request = - buildRequest(method, url, body, contentType, extraHeaders, timeout, policy); + buildPublisherRequest(method, url, body, contentType, extraHeaders, timeout, policy); return CancellableFuture.wrap(transport.sendAsync(request, policy.followRedirects())) .thenApply(resp -> new ApiResponse(resp.statusCode(), resp.headers(), resp.body())); } @@ -877,6 +943,33 @@ public CompletableFuture> streamRequest( retry.minDelayBetweenRetries); } + /** + * As {@link #streamRequest(String, String, byte[], String, Map, Timeout, RequestPolicy)}, for a + * body that is read from {@code body}. A stream can be read once, so the request is sent exactly + * once: it is never retried or compressed, and a redirect that needs the body again fails the + * request instead of sending an empty body. + */ + public CompletableFuture> streamRequest( + String method, + String url, + InputStream body, + String contentType, + Map extraHeaders, + Timeout timeout, + RequestPolicy policy) { + RequestPolicy singleAttempt = policy.forStreamBody(); + HttpRequest request = + buildPublisherRequest( + method, + url, + streamPublisher(body), + contentType, + extraHeaders, + attemptTimeout(resolveTimeout(timeout), 1), + singleAttempt); + return openStream(request, singleAttempt.followRedirects()); + } + /** * Opens one attempt of {@link #streamRequest} and, when the response has a status the policy * retries and attempts are left, closes it and schedules the next attempt after a backoff delay. @@ -959,6 +1052,29 @@ private CompletableFuture> openStream( */ public CompletableFuture streamOrThrow(String url) { CancellableFuture result = new CancellableFuture<>(); + CompletableFuture> response = streamResponseOrThrow(url); + result.link(response); + response.whenComplete( + (resp, err) -> { + if (err == null) { + if (!result.complete(resp.body())) { + closeQuietly(resp.body()); + } + } else if (err instanceof CancellationException) { + result.cancel(true); + } else { + result.completeExceptionally(err); + } + }); + return result; + } + + /** + * As {@link #streamOrThrow(String)}, but completes with the whole response, so the caller can + * read its headers as well as its body stream. + */ + public CompletableFuture> streamResponseOrThrow(String url) { + CancellableFuture> result = new CancellableFuture<>(); CompletableFuture> stream = streamAsync(url); result.link(stream); stream.whenComplete( @@ -976,7 +1092,7 @@ public CompletableFuture streamOrThrow(String url) { byte[] body = drainQuietly(resp.body()); result.completeExceptionally( buildApiError(resp.statusCode(), body, 1, "GET", extractPath(url))); - } else if (!result.complete(resp.body())) { + } else if (!result.complete(resp)) { closeQuietly(resp.body()); } }); diff --git a/src/main/java/com/apify/client/internal/Json.java b/src/main/java/com/apify/client/internal/Json.java index 4c16d5b..a1ab2c6 100644 --- a/src/main/java/com/apify/client/internal/Json.java +++ b/src/main/java/com/apify/client/internal/Json.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; +import java.io.InputStream; import java.nio.charset.StandardCharsets; import tools.jackson.core.JacksonException; import tools.jackson.core.type.TypeReference; @@ -75,11 +76,18 @@ public static byte[] toBytes(Object value) { * input read from a file, or the exact bytes of a non-JSON content type, are not wrapped in a * second layer of JSON. Anything else is serialized to JSON. A {@code null} payload sends no * body. + * + * @throws IllegalArgumentException if the payload is an {@link InputStream}, which only the + * methods that document stream bodies send as a stream; it would otherwise be serialized to + * meaningless JSON */ public static byte[] toRequestBody(Object payload) { if (payload == null) { return null; } + if (payload instanceof InputStream) { + throw new IllegalArgumentException("An InputStream body is not supported by this method"); + } if (payload instanceof byte[] bytes) { return bytes; } diff --git a/src/main/java/com/apify/client/internal/RequestPolicy.java b/src/main/java/com/apify/client/internal/RequestPolicy.java index 51a819c..bbd17ac 100644 --- a/src/main/java/com/apify/client/internal/RequestPolicy.java +++ b/src/main/java/com/apify/client/internal/RequestPolicy.java @@ -71,4 +71,19 @@ public static RequestPolicy server(HttpCompressor compressor) { /* compress= */ compressor != null, /* compressor= */ compressor); } + + /** + * This policy for a request whose body is a stream, which is not compressed since that would need + * the whole stream in memory. + */ + RequestPolicy forStreamBody() { + return new RequestPolicy( + authorizationHeader, + throwOnErrorStatus, + retryableStatus, + retryTransportErrors, + followRedirects, + /* compress= */ false, + compressor); + } } diff --git a/src/main/java/com/apify/client/internal/ResourceContext.java b/src/main/java/com/apify/client/internal/ResourceContext.java index a3dc385..deb9ab2 100644 --- a/src/main/java/com/apify/client/internal/ResourceContext.java +++ b/src/main/java/com/apify/client/internal/ResourceContext.java @@ -5,7 +5,9 @@ import com.apify.client.http.ApifyApiException; import com.apify.client.http.ApifyTransportException; import com.apify.client.http.Timeout; +import java.io.InputStream; import java.net.URLEncoder; +import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Map; @@ -404,6 +406,43 @@ public CompletableFuture postWithBody( .thenApply(resp -> Json.parseData(resp.body(), dataType)); } + /** + * POST whose body is read from a stream, unwrapping the data envelope. The stream can be read + * once, so the request is sent exactly once; see {@link HttpClientCore#callWithStream}. + */ + public CompletableFuture postWithStreamBody( + String subPath, + QueryParams params, + InputStream body, + String contentType, + Class dataClass, + Timeout timeout) { + String u = mergedParams(params).applyToUrl(subUrl(subPath)); + return http.callWithStream("POST", u, body, contentType, null, timeout, RequestPolicy.API) + .thenApply(resp -> Json.parseData(resp.body(), dataClass)); + } + + /** + * GET returning the live response, its body unread. Completes with {@code null} on not-found. The + * caller closes the body stream. + */ + public CompletableFuture> getStream( + String subPath, QueryParams params) { + String u = mergedParams(params).applyToUrl(subUrl(subPath)); + return http.streamResponseOrThrow(u) + .handle( + (resp, error) -> { + if (error == null) { + return resp; + } + Throwable cause = HttpClientCore.unwrapCompletion(error); + if (cause instanceof ApifyApiException apiError && isNotFound(apiError)) { + return null; + } + throw asRuntimeException(cause); + }); + } + /** * POST with a raw body, parsing the response body directly without unwrapping a {@code * {"data": ...}} envelope. Used by endpoints (e.g. actor input validation) whose response is a @@ -515,6 +554,23 @@ public CompletableFuture headExists( }); } + /** + * PUT whose body is read from a stream (used for key-value-store record uploads). The stream can + * be read once, so the request is sent exactly once; see {@link HttpClientCore#callWithStream}. + */ + public CompletableFuture putStream( + String subPath, + QueryParams params, + InputStream body, + String contentType, + Map extraHeaders, + Timeout timeout) { + String u = mergedParams(params).applyToUrl(subUrl(subPath)); + return http.callWithStream( + "PUT", u, body, contentType, extraHeaders, timeout, RequestPolicy.API) + .thenApply(resp -> null); + } + /** PUT with raw bytes and a content type (used for key-value-store record uploads). */ public CompletableFuture putRaw( String subPath, QueryParams params, byte[] body, String contentType) { diff --git a/src/main/java/com/apify/client/internal/RunStartSupport.java b/src/main/java/com/apify/client/internal/RunStartSupport.java index 5cd606b..2d4c7e5 100644 --- a/src/main/java/com/apify/client/internal/RunStartSupport.java +++ b/src/main/java/com/apify/client/internal/RunStartSupport.java @@ -8,6 +8,7 @@ import com.apify.client.log.StreamedLogOptions; import com.apify.client.run.ActorRun; import com.apify.client.run.RunClient; +import java.io.InputStream; import java.time.Duration; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -87,7 +88,6 @@ private static CompletableFuture start( Timeout timeout) { QueryParams params = new QueryParams(); applyParams.accept(params); - byte[] body = Json.toRequestBody(input); Timeout requestTimeout = timeout; if (requestTimeout == null) { HttpClientCore.WaitHold hold = @@ -95,6 +95,13 @@ private static CompletableFuture start( params.setLong("waitForFinish", hold.waitForFinishSecs()); requestTimeout = hold.timeout(); } + if (input instanceof InputStream stream) { + // A stream is consumed by the first attempt, so the start is sent once and a rejection for + // lack of resources is thrown instead of retried, whatever waitForResources says. + return ctx.postWithStreamBody( + "runs", params, stream, contentType, ActorRun.class, requestTimeout); + } + byte[] body = Json.toRequestBody(input); if (waitForResourcesSecs == null) { return ctx.postWithBody("runs", params, body, contentType, ActorRun.class, requestTimeout); } diff --git a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java index fb89fc5..62bcaed 100644 --- a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java +++ b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java @@ -9,6 +9,7 @@ import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; import com.apify.client.internal.Signatures; +import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Optional; @@ -309,6 +310,35 @@ public CompletableFuture> getRecord( }); } + /** + * As {@link #getRecord(String)}, but completes with the record's body as a live {@link + * InputStream} instead of buffering it, so a large record can be processed in chunks or passed on + * to {@link #setRecord(String, InputStream, String)} without being held in memory. Completes with + * empty if the record does not exist. The caller closes the returned record, or reads its stream + * to the end. Like {@link com.apify.client.dataset.DatasetClient#streamItems}, this bypasses the + * retrying transport, so an error status is thrown as an {@link + * com.apify.client.http.ApifyApiException} without a retry. + */ + public CompletableFuture> getRecordStream(String key) { + return getRecordStream(key, new GetRecordOptions().attachment(true)); + } + + /** As {@link #getRecordStream(String)}, with explicit options (attachment, signature). */ + public CompletableFuture> getRecordStream( + String key, GetRecordOptions options) { + QueryParams params = new QueryParams(); + options.apply(params); + return ctx.getStream("records/" + ResourceContext.encodePathSegment(key), params) + .thenApply( + resp -> { + if (resp == null) { + return Optional.empty(); + } + String contentType = resp.headers().firstValue(HttpHeaders.CONTENT_TYPE).orElse(null); + return Optional.of(new KeyValueStoreRecordStream(key, resp.body(), contentType)); + }); + } + /** Stores a record with raw bytes and the given content type. */ public CompletableFuture setRecord(String key, byte[] value, String contentType) { return setRecord(key, value, contentType, new SetRecordOptions()); @@ -322,27 +352,66 @@ public CompletableFuture setRecord(String key, byte[] value, String conten */ public CompletableFuture setRecord( String key, byte[] value, String contentType, SetRecordOptions options) { - // The trimmed value is validated and sent. - String contentEncoding = options.contentEncodingValue(); - if (contentEncoding != null) { - contentEncoding = contentEncoding.trim(); - if (contentEncoding.isEmpty()) { - throw new IllegalArgumentException("contentEncoding must not be blank"); - } - } - Map extraHeaders = - contentEncoding == null ? null : Map.of(HttpHeaders.CONTENT_ENCODING, contentEncoding); - Timeout timeout = options.timeoutValue() != null ? options.timeoutValue() : Timeout.LONG; return ctx.putRaw( "records/" + ResourceContext.encodePathSegment(key), new QueryParams(), value, contentType, - extraHeaders, - timeout, + contentEncodingHeader(options), + timeoutOf(options), options.doNotRetryTimeoutsValue()); } + /** + * The {@code Content-Encoding} header of a record upload, or {@code null} for none. The trimmed + * value is validated and sent. + */ + private static Map contentEncodingHeader(SetRecordOptions options) { + String contentEncoding = options.contentEncodingValue(); + if (contentEncoding == null) { + return null; + } + contentEncoding = contentEncoding.trim(); + if (contentEncoding.isEmpty()) { + throw new IllegalArgumentException("contentEncoding must not be blank"); + } + return Map.of(HttpHeaders.CONTENT_ENCODING, contentEncoding); + } + + /** The timeout of a record upload: the option, or the long tier. */ + private static Timeout timeoutOf(SetRecordOptions options) { + return options.timeoutValue() != null ? options.timeoutValue() : Timeout.LONG; + } + + /** + * Stores a record whose bytes are read from {@code value}, never held in memory whole, so a large + * file can be uploaded. The stream is closed once it is read. It can be read once, so the upload + * is sent once: it is not retried on failure or compressed, and a redirect that needs the body + * again fails the request. To upload a file with retries, read it into a {@code byte[]} and use + * {@link #setRecord(String, byte[], String)} instead. + */ + public CompletableFuture setRecord(String key, InputStream value, String contentType) { + return setRecord(key, value, contentType, new SetRecordOptions()); + } + + /** + * As {@link #setRecord(String, InputStream, String)}, honoring the given write options ({@code + * timeoutSecs} and {@code contentEncoding}; {@code doNotRetryTimeouts} has no effect, since a + * stream is never retried). + * + * @throws IllegalArgumentException if {@code options.contentEncoding()} is set but blank + */ + public CompletableFuture setRecord( + String key, InputStream value, String contentType, SetRecordOptions options) { + return ctx.putStream( + "records/" + ResourceContext.encodePathSegment(key), + new QueryParams(), + value, + contentType, + contentEncodingHeader(options), + timeoutOf(options)); + } + /** Stores a record holding the JSON serialization of {@code value}. */ public CompletableFuture setRecordJson(String key, Object value) { return setRecord(key, Json.toBytes(value), ResourceContext.CONTENT_TYPE_JSON_CHARSET); diff --git a/src/main/java/com/apify/client/keyvalue/KeyValueStoreRecordStream.java b/src/main/java/com/apify/client/keyvalue/KeyValueStoreRecordStream.java new file mode 100644 index 0000000..948778f --- /dev/null +++ b/src/main/java/com/apify/client/keyvalue/KeyValueStoreRecordStream.java @@ -0,0 +1,46 @@ +package com.apify.client.keyvalue; + +import java.io.IOException; +import java.io.InputStream; + +/** + * A record retrieved from a key-value store whose {@link #getValue() value} is a live stream, so a + * large record is processed in chunks instead of being held in memory. Close the record when done, + * or read its stream to the end, to release the connection. + */ +public final class KeyValueStoreRecordStream implements AutoCloseable { + private final String key; + private final InputStream value; + private final String contentType; + + KeyValueStoreRecordStream(String key, InputStream value, String contentType) { + this.key = key; + this.value = value; + this.contentType = contentType; + } + + /** The record key. */ + public String getKey() { + return key; + } + + /** The record bytes, as they arrive. The same stream is returned on every call. */ + public InputStream getValue() { + return value; + } + + /** The record's MIME type, as reported by the API. */ + public String getContentType() { + return contentType; + } + + /** + * Closes the stream of the record. + * + * @throws IOException if the stream fails to close + */ + @Override + public void close() throws IOException { + value.close(); + } +} diff --git a/src/main/java/com/apify/client/store/ActorStoreListItem.java b/src/main/java/com/apify/client/store/ActorStoreListItem.java index 0383367..4b3ad50 100644 --- a/src/main/java/com/apify/client/store/ActorStoreListItem.java +++ b/src/main/java/com/apify/client/store/ActorStoreListItem.java @@ -71,7 +71,7 @@ public List getCategories() { /** * A warning displayed on the Actor's Store page: {@code "NONE"}, {@code - * "RESIDENTIAL_PROXY_REQUIRED"} or {@code "UNDER_MAINTENANCE"}. Can be set by the Actor's + * "RESIDENTIAL_PROXY_REQUIRED"}, or {@code "UNDER_MAINTENANCE"}. Can be set by the Actor's * developer or automatically by Apify's quality checks. */ public String getNotice() { diff --git a/src/main/java/com/apify/client/store/StoreListOptions.java b/src/main/java/com/apify/client/store/StoreListOptions.java index 945bcb2..02707c8 100644 --- a/src/main/java/com/apify/client/store/StoreListOptions.java +++ b/src/main/java/com/apify/client/store/StoreListOptions.java @@ -37,7 +37,7 @@ public StoreListOptions limit(Long limit) { /** * Search query. The API ranks the results by relevance and returns them as a single page of at * most 100 Actors: {@link #offset(Long)} is ignored and there is no second page. Narrow the - * results with {@link #category(String)}, {@link #username(String)} or {@link + * results with {@link #category(String)}, {@link #username(String)}, or {@link * #pricingModel(String)}. */ public StoreListOptions search(String search) { diff --git a/src/main/java/com/apify/client/task/TaskClient.java b/src/main/java/com/apify/client/task/TaskClient.java index 5206e66..e838ebb 100644 --- a/src/main/java/com/apify/client/task/TaskClient.java +++ b/src/main/java/com/apify/client/task/TaskClient.java @@ -76,7 +76,10 @@ public CompletableFuture unpublish() { /** * Starts the task and completes with the created run as soon as it exists (no waiting). {@code - * input} optionally overrides the task's stored input ({@code null} to use the stored input). + * input} optionally overrides the task's stored input ({@code null} to use the stored input). As + * for {@link com.apify.client.actor.ActorClient#start}, it can be a {@code byte[]}, {@link + * String} or {@link java.io.InputStream} that is sent as it is; a stream is sent once, with no + * retry. */ public CompletableFuture start(Object input, TaskStartOptions options) { return RunStartSupport.start( diff --git a/src/test/java/com/apify/client/MockTransport.java b/src/test/java/com/apify/client/MockTransport.java index 12e9be0..50f7115 100644 --- a/src/test/java/com/apify/client/MockTransport.java +++ b/src/test/java/com/apify/client/MockTransport.java @@ -225,6 +225,7 @@ public synchronized CompletableFuture> sendStreamingAs calls++; lastUrl = request.uri().toString(); lastMethod = request.method(); + lastHeaders = request.headers(); HttpResponse response; if (streamQueue.isEmpty()) { Scripted r = responses.get(0); diff --git a/src/test/java/com/apify/client/StreamBodyTest.java b/src/test/java/com/apify/client/StreamBodyTest.java new file mode 100644 index 0000000..63e04af --- /dev/null +++ b/src/test/java/com/apify/client/StreamBodyTest.java @@ -0,0 +1,373 @@ +package com.apify.client; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.apify.client.actor.ActorServerRequestOptions; +import com.apify.client.actor.ActorStartOptions; +import com.apify.client.http.ApifyApiException; +import com.apify.client.http.ApifyTransportException; +import com.apify.client.http.ServerError; +import com.apify.client.keyvalue.KeyValueStoreRecordStream; +import com.apify.client.keyvalue.SetRecordOptions; +import com.apify.client.run.ActorRun; +import com.apify.client.run.MetamorphOptions; +import com.apify.client.task.TaskStartOptions; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletionException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests of the request bodies that are {@link InputStream}s and of the streamed record read, + * against a local HTTP server, so the chunked upload, the headers and the redirects are real + * network behavior. Token-free. + */ +class StreamBodyTest { + + private static final String RECORD_PATH = "/v2/key-value-stores/s1/records/key"; + private static final String RUN_JSON = "{\"data\":{\"id\":\"r1\",\"status\":\"READY\"}}"; + private static final String MEMORY_LIMIT_JSON = + "{\"error\":{\"type\":\"actor-memory-limit-exceeded\",\"message\":\"not enough memory\"}}"; + + /** A body larger than the compression threshold that compresses well. */ + private static final byte[] LARGE_BODY = "a".repeat(20_000).getBytes(StandardCharsets.UTF_8); + + private TestHttpServer server; + + /** + * The statuses the server answers record uploads with, one per request, before it answers 200. + */ + private final List uploadStatuses = Collections.synchronizedList(new ArrayList<>()); + + @BeforeEach + void startServer() throws IOException { + server = new TestHttpServer(this::answer); + } + + @AfterEach + void stopServer() throws IOException { + server.close(); + } + + private TestHttpServer.Reply answer(TestHttpServer.Received request) { + String path = request.path(); + if (path.equals(RECORD_PATH) && request.method().equals("PUT") && !uploadStatuses.isEmpty()) { + return TestHttpServer.Reply.json(uploadStatuses.remove(0), "{\"error\":{\"type\":\"x\"}}"); + } + if (path.equals(RECORD_PATH) && request.method().equals("GET")) { + return TestHttpServer.Reply.of(200, "text/plain", "streamed record"); + } + if (path.endsWith("/records/missing")) { + return TestHttpServer.Reply.json( + 404, "{\"error\":{\"type\":\"record-not-found\",\"message\":\"no record\"}}"); + } + if (path.endsWith("/records/redirected")) { + return TestHttpServer.Reply.redirect(307, server.url() + RECORD_PATH); + } + if (path.equals("/v2/actors/memory-limited/runs")) { + return TestHttpServer.Reply.json(400, MEMORY_LIMIT_JSON); + } + if (path.endsWith("/runs")) { + return TestHttpServer.Reply.json(201, RUN_JSON); + } + if (path.equals("/v2/actors/server")) { + return TestHttpServer.Reply.json( + 200, + "{\"data\":{\"id\":\"server\",\"actorStandby\":{\"isEnabled\":true}," + + "\"standbyUrl\":\"" + + server.url() + + "/server\"}}"); + } + if (path.equals("/server/flaky")) { + return TestHttpServer.Reply.json(503, "{}"); + } + return TestHttpServer.Reply.json(200, "{}"); + } + + private ApifyClient client() { + return ApifyClient.builder() + .token("test-token") + .baseUrl(server.url()) + .maxRetries(3) + .minDelayBetweenRetries(Duration.ofMillis(1)) + .build(); + } + + private static InputStream streamOf(byte[] bytes) { + return new ByteArrayInputStream(bytes); + } + + private TestHttpServer.Received onlyRequestTo(String path) { + List matching = + server.received().stream().filter(r -> r.path().equals(path)).toList(); + assertEquals(1, matching.size(), "requests to " + path + ": " + matching); + return matching.get(0); + } + + private long requestsTo(String path) { + return server.received().stream().filter(r -> r.path().equals(path)).count(); + } + + private static Throwable rootOf(Throwable error) { + Throwable current = error; + while (current instanceof CompletionException && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + // ---- key-value store record upload ----------------------------------------------------------- + + @Test + void setRecordSendsTheStreamAsTheBodyWithItsContentType() { + byte[] bytes = {1, 2, 3, 4, 5}; + client() + .keyValueStore("s1") + .setRecord("key", streamOf(bytes), "application/octet-stream") + .join(); + + TestHttpServer.Received request = onlyRequestTo(RECORD_PATH); + assertEquals("PUT", request.method()); + assertArrayEquals(bytes, request.body()); + assertEquals("application/octet-stream", request.header("Content-Type")); + } + + @Test + void setRecordDoesNotCompressAStreamButCompressesTheSameBytesAsAnArray() { + client().keyValueStore("s1").setRecord("key", streamOf(LARGE_BODY), "text/plain").join(); + TestHttpServer.Received streamed = server.received().get(0); + assertNull(streamed.header("Content-Encoding"), "a stream is sent as it is"); + assertArrayEquals(LARGE_BODY, streamed.body()); + + client().keyValueStore("s1").setRecord("key", LARGE_BODY, "text/plain").join(); + TestHttpServer.Received buffered = server.received().get(1); + assertEquals("br", buffered.header("Content-Encoding"), "the default compression"); + } + + @Test + void setRecordForwardsTheContentEncodingOptionOfAStream() { + client() + .keyValueStore("s1") + .setRecord( + "key", + streamOf(new byte[] {1}), + "text/plain", + new SetRecordOptions().contentEncoding("br")) + .join(); + assertEquals("br", onlyRequestTo(RECORD_PATH).header("Content-Encoding")); + } + + @Test + void setRecordRejectsABlankContentEncodingOfAStream() { + assertThrows( + IllegalArgumentException.class, + () -> + client() + .keyValueStore("s1") + .setRecord( + "key", + streamOf(new byte[] {1}), + "text/plain", + new SetRecordOptions().contentEncoding(" "))); + assertTrue(server.received().isEmpty()); + } + + @Test + void setRecordDoesNotRetryAStreamOnAServerError() { + uploadStatuses.add(503); + CompletionException error = + assertThrows( + CompletionException.class, + () -> + client() + .keyValueStore("s1") + .setRecord("key", streamOf(new byte[] {1, 2}), "text/plain") + .join()); + assertInstanceOf(ServerError.class, rootOf(error)); + assertEquals(1, server.received().size(), "a stream cannot be sent twice, so no retry"); + } + + @Test + void setRecordRetriesTheSameBytesAsAnArray() { + uploadStatuses.add(503); + client().keyValueStore("s1").setRecord("key", new byte[] {1, 2}, "text/plain").join(); + assertEquals(2, server.received().size(), "an array is sent again after the 503"); + } + + @Test + void setRecordFailsInsteadOfSendingAnEmptyBodyWhenARedirectNeedsTheStreamAgain() { + CompletionException error = + assertThrows( + CompletionException.class, + () -> + client() + .keyValueStore("s1") + .setRecord("redirected", streamOf(new byte[] {1, 2, 3}), "text/plain") + .join()); + assertInstanceOf(ApifyTransportException.class, rootOf(error)); + assertEquals(0, requestsTo(RECORD_PATH), "the redirect target never receives an empty body"); + } + + // ---- streamed record read -------------------------------------------------------------------- + + @Test + void getRecordStreamCompletesWithTheLiveBodyAndItsContentType() throws IOException { + Optional record = + client().keyValueStore("s1").getRecordStream("key").join(); + + try (KeyValueStoreRecordStream stream = record.orElseThrow()) { + assertEquals("key", stream.getKey()); + assertEquals("text/plain", stream.getContentType()); + assertEquals( + "streamed record", new String(stream.getValue().readAllBytes(), StandardCharsets.UTF_8)); + } + assertTrue(onlyRequestTo(RECORD_PATH).query().contains("attachment=1")); + } + + @Test + void getRecordStreamCompletesWithEmptyForAMissingRecord() { + assertTrue(client().keyValueStore("s1").getRecordStream("missing").join().isEmpty()); + } + + @Test + void aRecordStreamCanBePassedStraightToSetRecord() throws IOException { + ApifyClient client = client(); + try (KeyValueStoreRecordStream source = + client.keyValueStore("s1").getRecordStream("key").join().orElseThrow()) { + client + .keyValueStore("s2") + .setRecord("copy", source.getValue(), source.getContentType()) + .join(); + } + TestHttpServer.Received upload = + server.received().stream().filter(r -> r.method().equals("PUT")).findFirst().orElseThrow(); + assertEquals("streamed record", upload.bodyText()); + assertEquals("text/plain", upload.header("Content-Type")); + } + + // ---- Actor and task input -------------------------------------------------------------------- + + @Test + void actorStartSendsAStreamInputAsItIs() { + byte[] input = "{\"query\":\"cats\"}".getBytes(StandardCharsets.UTF_8); + ActorRun run = client().actor("a1").start(streamOf(input), new ActorStartOptions()).join(); + + assertEquals("r1", run.getId()); + TestHttpServer.Received request = onlyRequestTo("/v2/actors/a1/runs"); + assertArrayEquals(input, request.body(), "the stream is not serialized to JSON"); + assertEquals("application/json", request.header("Content-Type")); + } + + @Test + void actorStartTakesTheContentTypeOfAStreamInputFromTheOptions() { + client() + .actor("a1") + .start(streamOf(new byte[] {1}), new ActorStartOptions().contentType("application/xml")) + .join(); + assertEquals("application/xml", onlyRequestTo("/v2/actors/a1/runs").header("Content-Type")); + } + + @Test + void actorStartDoesNotWaitForResourcesWithAStreamInput() { + CompletionException error = + assertThrows( + CompletionException.class, + () -> + client() + .actor("memory-limited") + .start(streamOf(new byte[] {1}), new ActorStartOptions().waitForResources(true)) + .join()); + ApifyApiException api = assertInstanceOf(ApifyApiException.class, rootOf(error)); + assertEquals("actor-memory-limit-exceeded", api.getType()); + assertEquals(1, server.received().size(), "a stream cannot be sent again, so no retry"); + } + + @Test + void taskStartSendsAStreamInputAsItIs() { + byte[] input = {9, 8, 7}; + client().task("t1").start(streamOf(input), new TaskStartOptions()).join(); + assertArrayEquals(input, onlyRequestTo("/v2/actor-tasks/t1/runs").body()); + } + + @Test + void methodsThatTakeNoStreamRejectOneInsteadOfSendingMeaninglessJson() { + assertThrows( + IllegalArgumentException.class, + () -> + client() + .run("r1") + .metamorph("other", streamOf(new byte[] {1}), new MetamorphOptions())); + assertThrows( + IllegalArgumentException.class, + () -> client().actor("a1").validateInput(streamOf(new byte[] {1}))); + assertTrue(server.received().isEmpty()); + } + + // ---- Server Actor request -------------------------------------------------------------------- + + @Test + void serverRequestSendsAStreamBodyAsItIs() { + byte[] body = "hello server".getBytes(StandardCharsets.UTF_8); + client() + .actor("server") + .server() + .request("/echo", new ActorServerRequestOptions().method("POST").body(streamOf(body))) + .join(); + TestHttpServer.Received request = onlyRequestTo("/server/echo"); + assertArrayEquals(body, request.body()); + assertNull(request.header("Content-Type"), "a stream is sent as it is, with no assumed type"); + } + + @Test + void serverRequestDoesNotRetryAStreamBodyOnA503() { + var response = + client() + .actor("server") + .server() + .request( + "/flaky", + new ActorServerRequestOptions().method("POST").body(streamOf(new byte[] {1}))) + .join(); + assertEquals(503, response.statusCode()); + assertEquals(1, requestsTo("/server/flaky")); + } + + @Test + void serverRequestRetriesABufferedBodyOnA503() { + client() + .actor("server") + .server() + .request("/flaky", new ActorServerRequestOptions().method("POST").body(new byte[] {1})) + .join(); + assertTrue(requestsTo("/server/flaky") > 1); + } + + @Test + void serverRequestStreamSendsAStreamBodyAsItIs() throws IOException { + byte[] body = "hello streamed".getBytes(StandardCharsets.UTF_8); + try (var response = + client() + .actor("server") + .server() + .requestStream( + "/echo", new ActorServerRequestOptions().method("POST").body(streamOf(body))) + .join()) { + assertEquals(200, response.statusCode()); + } + assertArrayEquals(body, onlyRequestTo("/server/echo").body()); + } +} diff --git a/src/test/java/com/apify/client/TestHttpServer.java b/src/test/java/com/apify/client/TestHttpServer.java index 298bc50..0d4599e 100644 --- a/src/test/java/com/apify/client/TestHttpServer.java +++ b/src/test/java/com/apify/client/TestHttpServer.java @@ -53,7 +53,11 @@ static Reply json(int status, String body) { } static Reply redirect(String location) { - return new Reply(302, Map.of("Location", location), new byte[0], false); + return redirect(302, location); + } + + static Reply redirect(int status, String location) { + return new Reply(status, Map.of("Location", location), new byte[0], false); } static Reply drop() { @@ -130,8 +134,13 @@ private static Received read(InputStream in) throws IOException { line.substring(colon + 1).trim(), (first, second) -> first + ", " + second); } - int length = Integer.parseInt(headers.getOrDefault("content-length", "0")); - byte[] body = in.readNBytes(length); + byte[] body; + if ("chunked".equalsIgnoreCase(headers.get("transfer-encoding"))) { + body = readChunked(in); + } else { + int length = Integer.parseInt(headers.getOrDefault("content-length", "0")); + body = in.readNBytes(length); + } String target = parts[1]; int question = target.indexOf('?'); String path = question < 0 ? target : target.substring(0, question); @@ -139,6 +148,24 @@ private static Received read(InputStream in) throws IOException { return new Received(parts[0], path, query, headers, body); } + /** Reads a body sent with {@code Transfer-Encoding: chunked}, as a streamed upload is. */ + private static byte[] readChunked(InputStream in) throws IOException { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + while (true) { + String sizeLine = readLine(in); + if (sizeLine == null) { + throw new IOException("The connection closed in the middle of a chunked body"); + } + int size = Integer.parseInt(sizeLine.split(";")[0].trim(), 16); + if (size == 0) { + readLine(in); // the empty line that ends the body + return body.toByteArray(); + } + body.writeBytes(in.readNBytes(size)); + readLine(in); // the line break after the chunk + } + } + private static String readLine(InputStream in) throws IOException { ByteArrayOutputStream line = new ByteArrayOutputStream(); int b; diff --git a/src/test/java/com/apify/client/integration/KeyValueStoreIntegrationTest.java b/src/test/java/com/apify/client/integration/KeyValueStoreIntegrationTest.java index 7374e26..92e3fcc 100644 --- a/src/test/java/com/apify/client/integration/KeyValueStoreIntegrationTest.java +++ b/src/test/java/com/apify/client/integration/KeyValueStoreIntegrationTest.java @@ -9,8 +9,10 @@ import com.apify.client.keyvalue.KeyValueStore; import com.apify.client.keyvalue.KeyValueStoreClient; import com.apify.client.keyvalue.KeyValueStoreRecord; +import com.apify.client.keyvalue.KeyValueStoreRecordStream; import com.apify.client.keyvalue.ListKeysOptions; import com.apify.client.keyvalue.SetRecordOptions; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; @@ -62,6 +64,32 @@ void recordKeyWithSpecialChars() { } } + @Test + void recordStreamRoundTrip() throws Exception { + ApifyClient client = requireClient(); + KeyValueStore store = client.keyValueStores().getOrCreate(uniqueName("kvs-stream")).join(); + try { + KeyValueStoreClient kvs = client.keyValueStore(store.getId()); + byte[] bytes = "streamed record bytes".repeat(1000).getBytes(StandardCharsets.UTF_8); + kvs.setRecord("source", new ByteArrayInputStream(bytes), "text/plain").join(); + + // Copy the record without reading it into memory: the stream another call returned goes + // straight into the upload. + try (KeyValueStoreRecordStream source = kvs.getRecordStream("source").join().orElseThrow()) { + assertTrue(source.getContentType().startsWith("text/plain"), source.getContentType()); + kvs.setRecord("copy", source.getValue(), source.getContentType()).join(); + } + + assertEquals( + new String(bytes, StandardCharsets.UTF_8), + new String( + kvs.getRecord("copy").join().orElseThrow().getValue(), StandardCharsets.UTF_8)); + assertTrue(kvs.getRecordStream("does-not-exist").join().isEmpty()); + } finally { + client.keyValueStore(store.getId()).delete().join(); + } + } + @Test void keyValueStoreCrudFlow() throws Exception { ApifyClient client = requireClient(); From c0f6ea9a8e73df2657071121a5f04edd1eb9b699 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:22:38 +0000 Subject: [PATCH 03/19] fix: retry streamed record reads, close stream bodies, and do not follow redirects for streams --- README.md | 5 +- docs/actors.md | 6 +- docs/storages.md | 8 +- docs/tasks.md | 2 +- .../com/apify/client/actor/ActorClient.java | 8 +- .../apify/client/actor/ActorServerClient.java | 114 +++++++------- .../actor/ActorServerRequestOptions.java | 12 +- .../apify/client/internal/HttpClientCore.java | 149 ++++++++---------- .../apify/client/internal/RequestPolicy.java | 7 +- .../client/internal/ResourceContext.java | 5 +- .../client/internal/RunStartSupport.java | 5 +- .../client/keyvalue/KeyValueStoreClient.java | 14 +- .../com/apify/client/task/TaskClient.java | 2 +- .../java/com/apify/client/StreamBodyTest.java | 127 ++++++++++++++- 14 files changed, 290 insertions(+), 174 deletions(-) diff --git a/README.md b/README.md index 041228d..f2bf09a 100644 --- a/README.md +++ b/README.md @@ -315,8 +315,9 @@ Two further methods, `sendAsync(HttpRequest, boolean followRedirects)` and `sendStreamingAsync(HttpRequest, boolean followRedirects)`, have default implementations that send the request through the methods above when `followRedirects` is `true` and **fail** the future with an `UnsupportedOperationException` when it is `false`. A request to an Actor's server (see -[Server Actors](docs/actors.md#server-actors)) is sent with `followRedirects` set to `false`, so -that the API token never follows a redirect to another host. Override both to support it: with +[Server Actors](docs/actors.md#server-actors)) and a request whose body is an `InputStream` are sent +with `followRedirects` set to `false`, so that the API token never follows a redirect to another +host and a stream is never sent twice. Override both to support it: with `false`, return a redirect response as it is. `DefaultHttpTransport` does, also when it wraps your own JDK `HttpClient` (it then copies the client's settings into one that does not follow redirects). diff --git a/docs/actors.md b/docs/actors.md index 0d27433..938e4e0 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -46,7 +46,7 @@ Actor created = client.actors().create(Map.of( | `get()` | Fetch the Actor. Completes with `Optional`. | | `update(Object)` | Update the Actor with the given fields. Completes with `Actor`. | | `delete()` | Delete the Actor. | -| `start(Object input, ActorStartOptions)` | Start a run, returning immediately. Completes with `ActorRun`. The `input` is any JSON-serializable value, or a `byte[]`, `String` or `InputStream` that is sent as it is (set the matching `ActorStartOptions.contentType(...)`), or `null`. A stream is read once, so its start is sent once: it is not retried, even with `waitForResources`. | +| `start(Object input, ActorStartOptions)` | Start a run, returning immediately. Completes with `ActorRun`. The `input` is any JSON-serializable value, or a `byte[]`, `String`, or `InputStream` that is sent as it is (set the matching `ActorStartOptions.contentType(...)`), or `null`. A stream is read once, so its start is sent once: it is not retried, even with `waitForResources`. | | `call(Object input, ActorStartOptions, Long waitSecs)` | Start a run and poll until it finishes (`null` waits indefinitely); does **not** stream the run's log. Completes with `ActorRun`. | | `call(Object input, ActorCallOptions, Long waitSecs)` | As above, additionally streaming the run's log for the duration of the wait by default. Use `ActorCallOptions.disableLogStreaming()` to opt out, or `logOptions(StreamedLogOptions)` for a custom destination. | | `validateInput(Object input)` / `validateInput(Object input, ValidateInputOptions)` | Validate an input against the Actor's input schema. Completes with `boolean`. `ValidateInputOptions` fields (optional): `build` (`String`), `contentType` (`String`). | @@ -132,8 +132,8 @@ Actor's `standbyUrl` and `actorStandby` fields. `POST`, `PUT`, `DELETE`, `OPTIONS`, `TRACE`, `PATCH`), `param(String, Object)`/`params(Map)` (query parameters, converted as for API calls: `null` is left out, a boolean is sent as `1`/`0`, a collection comma-joined), `header(String, String)`/`headers(Map)`, `body(Object)` (a `byte[]`, -`String` or `InputStream` is sent as it is, and a stream is sent once, with no retry and no -compression; anything else is serialized to JSON and sent as `application/json` +`String`, or `InputStream` is sent as it is, and a stream is sent once, with no retry, no +compression, and no redirect followed; anything else is serialized to JSON and sent as `application/json` unless you set a `Content-Type` header), `parentRequestId(String)` (see [Calling a Server Actor from a Server Actor](#calling-a-server-actor-from-a-server-actor)), `compression(HttpCompressor)` and `timeout(Timeout)` diff --git a/docs/storages.md b/docs/storages.md index 0c5cfed..9049510 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -142,8 +142,8 @@ datasets. | `getRecord(String key)` / `getRecord(String key, GetRecordOptions)` | Fetch a record. Completes with `Optional`. | | `setRecord(String key, byte[] value, String contentType)` | Store raw bytes. Completes with no value (`CompletableFuture`). | | `setRecord(String key, byte[] value, String contentType, SetRecordOptions)` | Store raw bytes with write options (`SetRecordOptions`: `timeoutSecs` (`Long`) or `timeout` (`Timeout`: a tier, an exact duration or `NO_TIMEOUT`; the default is the `LONG` tier), `doNotRetryTimeouts` (`Boolean`), `contentEncoding` (`String`, see below)). Completes with no value. | -| `getRecordStream(String key)` / `getRecordStream(String key, GetRecordOptions)` | As `getRecord`, but completes with an `Optional` whose `getValue()` is a live `InputStream`, so a large record is processed in chunks. Close the record (or read its stream to the end) when done. Throws on any error response other than a 404, which completes with empty. | -| `setRecord(String key, InputStream value, String contentType)` / `setRecord(String key, InputStream value, String contentType, SetRecordOptions)` | Store the bytes read from a stream, without holding them in memory, so a large file can be uploaded. The stream is closed once it is read. It can be read once, so the upload is sent once: it is not retried or compressed, and `doNotRetryTimeouts` has no effect. Completes with no value. | +| `getRecordStream(String key)` / `getRecordStream(String key, GetRecordOptions)` | As `getRecord`, but completes with an `Optional` whose `getValue()` is a live `InputStream`, so a large record is processed in chunks. Close the record (or read its stream to the end) when done. The request is retried like any other, until the headers arrive. Throws on an error response that is not retried (any more), except a 404, which completes with empty. A failure while reading the body is not retried. | +| `setRecord(String key, InputStream value, String contentType)` / `setRecord(String key, InputStream value, String contentType, SetRecordOptions)` | Store the bytes read from a stream, without holding them in memory, so a large file can be uploaded. The stream is closed when the call completes. It can be read once, so the upload is sent once: it is not retried, compressed, or sent again to follow a redirect, and `doNotRetryTimeouts` has no effect. Completes with no value. | | `setRecordJson(String key, Object value)` | Store JSON. Completes with no value. | | `deleteRecord(String key)` | Delete a record. Completes with no value. | | `getRecordPublicUrl(String key)` | A public (optionally signed) record URL. Completes with `String`. | @@ -197,8 +197,8 @@ try (KeyValueStoreRecordStream source = } ``` -`KeyValueStoreRecord` exposes `getKey()`, `getValue()` (raw bytes) and `getContentType()`; -`KeyValueStoreRecordStream` exposes `getKey()`, `getValue()` (the `InputStream`), `getContentType()` +`KeyValueStoreRecord` exposes `getKey()`, `getValue()` (raw bytes), and `getContentType()`; +`KeyValueStoreRecordStream` exposes `getKey()`, `getValue()` (the `InputStream`), `getContentType()`, and `close()`. `KeyValueStoreKeysPage` exposes `getItems()` (a list of `KeyValueStoreKey` with `getKey()`/`getSize()`), `isTruncated()`, `getExclusiveStartKey()` and `getNextExclusiveStartKey()`. diff --git a/docs/tasks.md b/docs/tasks.md index 44e7989..9b15804 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -25,7 +25,7 @@ Task task = client.tasks().create(Map.of( |---|---| | `get()` / `update(Object)` / `delete()` | CRUD. Complete with `Optional` / `Task` / no value. | | `publish()` / `unpublish()` | Publish/unpublish the task on its public landing page, by setting `isPublic` through `update(Object)`. Both require write permission to both the task and its Actor; `publish()` additionally requires the task's Actor to be public and a configured `publicConfig`. `unpublish()` preserves `publicConfig` so the task can be republished without re-entering it. Complete with the updated `Task`. | -| `start(Object input, TaskStartOptions)` | Start a task run (input overrides stored input; `null` uses it). Completes with `ActorRun`. As for an Actor, the `input` can be a `byte[]`, `String` or `InputStream` that is sent as it is; a stream is sent once, with no retry. | +| `start(Object input, TaskStartOptions)` | Start a task run (input overrides stored input; `null` uses it). Completes with `ActorRun`. As for an Actor, the `input` can be a `byte[]`, `String`, or `InputStream` that is sent as it is; a stream is sent once, with no retry. | | `call(Object input, TaskStartOptions, Long waitSecs)` | Start and poll until finished; does **not** stream the run's log. Completes with `ActorRun`. | | `call(Object input, TaskCallOptions, Long waitSecs)` | As above, additionally streaming the run's log for the duration of the wait by default. Use `TaskCallOptions.disableLogStreaming()` to opt out, or `logOptions(StreamedLogOptions)` for a custom destination. | | `getInput()` | The stored input. Completes with `JsonNode`; throws `NotFoundError` if the task is gone (no separate "input absent" state). | diff --git a/src/main/java/com/apify/client/actor/ActorClient.java b/src/main/java/com/apify/client/actor/ActorClient.java index 61ea096..749b04b 100644 --- a/src/main/java/com/apify/client/actor/ActorClient.java +++ b/src/main/java/com/apify/client/actor/ActorClient.java @@ -74,13 +74,13 @@ public CompletableFuture delete() { /** * Starts the Actor and completes with the created run as soon as it exists (no waiting). {@code - * input} is any JSON-serializable value, a {@code byte[]}, {@link String} or {@link InputStream} + * input} is any JSON-serializable value, a {@code byte[]}, {@link String}, or {@link InputStream} * that is sent as it is (set the content type with the options' {@code contentType}), or {@code * null} for no input. * - *

An {@code InputStream} is read as it is sent, closed afterwards and never held in memory. It - * can be read once, so the start is sent once: a failed request is not retried, and a rejection - * for lack of resources is thrown even if {@code waitForResources} is set. + *

An {@code InputStream} is read as it is sent, closed when the call completes, and never held + * in memory. It can be read once, so the start is sent once: a failed request is not retried, and + * a rejection for lack of resources is thrown even if {@code waitForResources} is set. */ public CompletableFuture start(Object input, ActorStartOptions options) { return RunStartSupport.start( diff --git a/src/main/java/com/apify/client/actor/ActorServerClient.java b/src/main/java/com/apify/client/actor/ActorServerClient.java index 6635089..09b8ff6 100644 --- a/src/main/java/com/apify/client/actor/ActorServerClient.java +++ b/src/main/java/com/apify/client/actor/ActorServerClient.java @@ -12,7 +12,6 @@ import com.apify.client.internal.RequestPolicy; import com.apify.client.internal.ResourceContext; import java.io.InputStream; -import java.net.http.HttpResponse; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; @@ -212,32 +211,30 @@ public CompletableFuture> getOpenApiSpec(Timeout timeout) { public CompletableFuture request(String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); - if (opts.bodyValue() instanceof InputStream stream) { - return getUrl() - .thenCompose( - serverUrl -> - http.callWithStream( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - stream, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - policy)); - } - byte[] body = Json.toRequestBody(opts.bodyValue()); + InputStream stream = opts.bodyValue() instanceof InputStream in ? in : null; + byte[] body = stream == null ? Json.toRequestBody(opts.bodyValue()) : null; return getUrl() .thenCompose( serverUrl -> - http.call( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - body, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - false, - policy)); + stream != null + ? http.callWithStream( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + stream, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy) + : http.call( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + body, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + false, + policy)) + .whenComplete((response, error) -> closeUnused(stream)); } /** A {@code GET} request to {@code path} on the Actor's server; see {@link #request}. */ @@ -263,39 +260,44 @@ public CompletableFuture requestStream( String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); - CompletableFuture> exchange; - if (opts.bodyValue() instanceof InputStream stream) { - exchange = - getUrl() - .thenCompose( - serverUrl -> - http.streamRequest( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - stream, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - policy)); - } else { - byte[] body = Json.toRequestBody(opts.bodyValue()); - exchange = - getUrl() - .thenCompose( - serverUrl -> - http.streamRequest( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - body, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - policy)); + InputStream stream = opts.bodyValue() instanceof InputStream in ? in : null; + byte[] body = stream == null ? Json.toRequestBody(opts.bodyValue()) : null; + return getUrl() + .thenCompose( + serverUrl -> + stream != null + ? http.streamRequest( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + stream, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy) + : http.streamRequest( + opts.methodValue(), + requestUrl(serverUrl, path, opts), + body, + contentTypeOf(opts), + opts.headersValue(), + opts.timeoutValue(), + policy)) + .whenComplete((response, error) -> closeUnused(stream)) + .thenApply( + response -> + new ActorServerStreamResponse( + response.statusCode(), response.headers(), response.body())); + } + + /** + * Closes a stream request body once the call completed. The transport closes it when it sends the + * request, so this matters when the request never got that far, for example because the Actor is + * not a Server Actor. + */ + private static void closeUnused(InputStream stream) { + if (stream != null) { + HttpClientCore.closeQuietly(stream); } - return exchange.thenApply( - response -> - new ActorServerStreamResponse( - response.statusCode(), response.headers(), response.body())); } /** Fetches the Actor and checks that it is a Server Actor. */ diff --git a/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java b/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java index 620c972..d96cdcc 100644 --- a/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java +++ b/src/main/java/com/apify/client/actor/ActorServerRequestOptions.java @@ -86,14 +86,14 @@ public ActorServerRequestOptions headers(Map headers) { } /** - * The request body: a {@code byte[]}, a {@link String} or an {@link InputStream} is sent as it is - * (set its {@code Content-Type} with {@link #header}), and anything else, a {@link Map}, a list - * or a POJO, is serialized to JSON and sent as {@code application/json} unless a {@code + * The request body: a {@code byte[]}, a {@link String}, or an {@link InputStream} is sent as it + * is (set its {@code Content-Type} with {@link #header}), and anything else, a {@link Map}, a + * list, or a POJO, is serialized to JSON and sent as {@code application/json} unless a {@code * Content-Type} header is set. * - *

An {@code InputStream} is read as it is sent and closed afterwards, so it is never held in - * memory. It can be read once, so the request is sent once, with no retry (not even for a 429 or - * 503 response) and no compression. + *

An {@code InputStream} is read as it is sent and closed when the call completes, so it is + * never held in memory. It can be read once, so the request is sent once, with no retry (not even + * for a 429 or 503 response), no compression, and no redirect followed. */ public ActorServerRequestOptions body(Object body) { this.body = body; diff --git a/src/main/java/com/apify/client/internal/HttpClientCore.java b/src/main/java/com/apify/client/internal/HttpClientCore.java index e7ec91c..9a05349 100644 --- a/src/main/java/com/apify/client/internal/HttpClientCore.java +++ b/src/main/java/com/apify/client/internal/HttpClientCore.java @@ -35,7 +35,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -361,9 +360,9 @@ public CompletableFuture call( /** * Sends a request whose body is read from {@code body}, with auth and the User-Agent applied. A - * stream can be read once, so the request is sent exactly once: it is never retried or - * compressed, and a redirect that needs the body again fails the request instead of sending an - * empty body. {@code body} is closed once it is read. + * stream can be read once, so the request is sent exactly once: it is never retried, compressed, + * or sent again to follow a redirect. {@code body} is closed when the call completes, whether it + * succeeded or not. */ public CompletableFuture callWithStream( String method, @@ -374,38 +373,19 @@ public CompletableFuture callWithStream( Timeout timeout, RequestPolicy policy) { return attemptWithRetry( - method, - url, - streamPublisher(body), - contentType, - extraHeaders, - resolveTimeout(timeout), - false, - policy.forStreamBody(), - extractPath(url), - 1, - 1, - retry.minDelayBetweenRetries); - } - - /** - * A single-use body publisher that reads {@code body}. A second subscription, which the JDK makes - * to send the body again for a 307 or 308 redirect, gets a stream that fails to read instead of - * the exhausted {@code body}, so the data is never silently replaced with an empty body. - */ - private static HttpRequest.BodyPublisher streamPublisher(InputStream body) { - AtomicBoolean handedOut = new AtomicBoolean(); - return HttpRequest.BodyPublishers.ofInputStream( - () -> handedOut.compareAndSet(false, true) ? body : new SentStream()); - } - - /** The body of a stream request that was already sent: reading it fails. */ - private static final class SentStream extends InputStream { - @Override - public int read() throws IOException { - throw new IOException( - "The request body is a stream that was already sent and cannot be sent again"); - } + method, + url, + HttpRequest.BodyPublishers.ofInputStream(() -> body), + contentType, + extraHeaders, + resolveTimeout(timeout), + false, + policy.forStreamBody(), + extractPath(url), + 1, + 1, + retry.minDelayBetweenRetries) + .whenComplete((response, error) -> closeQuietly(body)); } /** A request body, as it is sent, with the headers that go with it. */ @@ -910,12 +890,12 @@ public CompletableFuture> streamAsync(String url) { /** * Opens a live streaming response to a request, as {@link #call(String, String, byte[], String, - * Map, Timeout, boolean, RequestPolicy)} would send it, but without turning an error status into - * an exception: every response is handed back with its body unread, for the caller to inspect and - * close. A status the policy retries is retried with the client's retry settings, each discarded - * response closed, and the last one is handed back once the retries run out. A transport error is - * never retried. The future completes exceptionally with an {@link ApifyTransportException} on a - * transport failure. + * Map, Timeout, boolean, RequestPolicy)} would send it. A status the policy retries is retried + * with the client's retry settings, each discarded response closed, and so is a transport error + * if the policy retries those. The last response is handed back with its body unread, for the + * caller to inspect and close, unless the policy throws on an error status: it is then drained + * and thrown as an {@link ApifyApiException}. The future completes exceptionally with an {@link + * ApifyTransportException} on a transport failure that is not retried (any more). */ public CompletableFuture> streamRequest( String method, @@ -946,8 +926,8 @@ public CompletableFuture> streamRequest( /** * As {@link #streamRequest(String, String, byte[], String, Map, Timeout, RequestPolicy)}, for a * body that is read from {@code body}. A stream can be read once, so the request is sent exactly - * once: it is never retried or compressed, and a redirect that needs the body again fails the - * request instead of sending an empty body. + * once: it is never retried, compressed, or sent again to follow a redirect. {@code body} is + * closed when the response arrives or the request fails. */ public CompletableFuture> streamRequest( String method, @@ -962,12 +942,13 @@ public CompletableFuture> streamRequest( buildPublisherRequest( method, url, - streamPublisher(body), + HttpRequest.BodyPublishers.ofInputStream(() -> body), contentType, extraHeaders, attemptTimeout(resolveTimeout(timeout), 1), singleAttempt); - return openStream(request, singleAttempt.followRedirects()); + return openStream(request, singleAttempt.followRedirects()) + .whenComplete((response, error) -> closeQuietly(body)); } /** @@ -994,14 +975,26 @@ private CompletableFuture> streamAttempt( attemptTimeout(baseTimeout, attempt), policy); return openStream(request, policy.followRedirects()) - .thenCompose( - response -> { - boolean retryable = - isStatusRetryable(response.statusCode(), policy) && attempt < maxAttempts; - if (!retryable) { - return CompletableFuture.completedFuture(response); + .handle( + (response, error) -> { + boolean retryable; + if (error == null) { + retryable = + isStatusRetryable(response.statusCode(), policy) && attempt < maxAttempts; + if (!retryable) { + return finishStreamAttempt(method, url, policy, attempt, response); + } + closeQuietly(response.body()); + } else { + Throwable cause = unwrapCompletion(error); + retryable = + policy.retryTransportErrors() + && attempt < maxAttempts + && !(cause instanceof CancellationException); + if (!retryable) { + return CompletableFuture.>failedFuture(cause); + } } - closeQuietly(response.body()); Duration nextDelay = minDuration(delay.multipliedBy(BACKOFF_FACTOR), retry.maxDelayBetweenRetries); return Async.delay(randomizedDelay(delay)) @@ -1017,7 +1010,27 @@ private CompletableFuture> streamAttempt( attempt + 1, maxAttempts, nextDelay)); - }); + }) + .thenCompose(next -> next); + } + + /** + * The outcome of the last attempt of a streamed request: the response, or, when the policy throws + * on an error status, the {@link ApifyApiException} that describes it, with the response drained + * and closed. + */ + private CompletableFuture> finishStreamAttempt( + String method, + String url, + RequestPolicy policy, + int attempt, + HttpResponse response) { + if (!policy.throwOnErrorStatus() || response.statusCode() < MAX_SUCCESS_STATUS) { + return CompletableFuture.completedFuture(response); + } + byte[] body = drainQuietly(response.body()); + return failedFuture( + buildApiError(response.statusCode(), body, attempt, method, extractPath(url))); } private CompletableFuture> openStream( @@ -1052,29 +1065,6 @@ private CompletableFuture> openStream( */ public CompletableFuture streamOrThrow(String url) { CancellableFuture result = new CancellableFuture<>(); - CompletableFuture> response = streamResponseOrThrow(url); - result.link(response); - response.whenComplete( - (resp, err) -> { - if (err == null) { - if (!result.complete(resp.body())) { - closeQuietly(resp.body()); - } - } else if (err instanceof CancellationException) { - result.cancel(true); - } else { - result.completeExceptionally(err); - } - }); - return result; - } - - /** - * As {@link #streamOrThrow(String)}, but completes with the whole response, so the caller can - * read its headers as well as its body stream. - */ - public CompletableFuture> streamResponseOrThrow(String url) { - CancellableFuture> result = new CancellableFuture<>(); CompletableFuture> stream = streamAsync(url); result.link(stream); stream.whenComplete( @@ -1092,14 +1082,15 @@ public CompletableFuture> streamResponseOrThrow(String byte[] body = drainQuietly(resp.body()); result.completeExceptionally( buildApiError(resp.statusCode(), body, 1, "GET", extractPath(url))); - } else if (!result.complete(resp)) { + } else if (!result.complete(resp.body())) { closeQuietly(resp.body()); } }); return result; } - private static void closeQuietly(InputStream in) { + /** Closes {@code in}, ignoring a failure to close it. */ + public static void closeQuietly(InputStream in) { try { in.close(); } catch (IOException e) { diff --git a/src/main/java/com/apify/client/internal/RequestPolicy.java b/src/main/java/com/apify/client/internal/RequestPolicy.java index bbd17ac..6bb591d 100644 --- a/src/main/java/com/apify/client/internal/RequestPolicy.java +++ b/src/main/java/com/apify/client/internal/RequestPolicy.java @@ -73,8 +73,9 @@ public static RequestPolicy server(HttpCompressor compressor) { } /** - * This policy for a request whose body is a stream, which is not compressed since that would need - * the whole stream in memory. + * This policy for a request whose body is a stream, which can be read once: the request is not + * compressed, since that would need the whole stream in memory, and does not follow a redirect, + * since that would send the body again. */ RequestPolicy forStreamBody() { return new RequestPolicy( @@ -82,7 +83,7 @@ RequestPolicy forStreamBody() { throwOnErrorStatus, retryableStatus, retryTransportErrors, - followRedirects, + /* followRedirects= */ false, /* compress= */ false, compressor); } diff --git a/src/main/java/com/apify/client/internal/ResourceContext.java b/src/main/java/com/apify/client/internal/ResourceContext.java index deb9ab2..c33efc9 100644 --- a/src/main/java/com/apify/client/internal/ResourceContext.java +++ b/src/main/java/com/apify/client/internal/ResourceContext.java @@ -423,13 +423,14 @@ public CompletableFuture postWithStreamBody( } /** - * GET returning the live response, its body unread. Completes with {@code null} on not-found. The + * GET returning the live response, its body unread. Retries like any other request, throws on an + * error status that is not retried (any more), and completes with {@code null} on not-found. The * caller closes the body stream. */ public CompletableFuture> getStream( String subPath, QueryParams params) { String u = mergedParams(params).applyToUrl(subUrl(subPath)); - return http.streamResponseOrThrow(u) + return http.streamRequest("GET", u, (byte[]) null, null, null, Timeout.LONG, RequestPolicy.API) .handle( (resp, error) -> { if (error == null) { diff --git a/src/main/java/com/apify/client/internal/RunStartSupport.java b/src/main/java/com/apify/client/internal/RunStartSupport.java index 2d4c7e5..4101428 100644 --- a/src/main/java/com/apify/client/internal/RunStartSupport.java +++ b/src/main/java/com/apify/client/internal/RunStartSupport.java @@ -55,8 +55,9 @@ private RunStartSupport() {} /** * Starts a run on {@code ctx}'s {@code runs} sub-resource and completes with the created run as - * soon as it exists (no waiting). {@code input} is any JSON-serializable value, a {@code byte[]} - * or {@link String} sent as it is, or {@code null} for no input. {@code applyParams} applies + * soon as it exists (no waiting). {@code input} is any JSON-serializable value, a {@code byte[]}, + * {@link String}, or {@link InputStream} sent as it is, or {@code null} for no input. A stream + * start is sent once and skips the {@code waitForResources} retry. {@code applyParams} applies * every start-option query parameter (build, memory, timeout, ...) the caller's options type * configures; {@code contentType} is the input body's content type. * diff --git a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java index 62bcaed..07717e7 100644 --- a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java +++ b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java @@ -315,9 +315,9 @@ public CompletableFuture> getRecord( * InputStream} instead of buffering it, so a large record can be processed in chunks or passed on * to {@link #setRecord(String, InputStream, String)} without being held in memory. Completes with * empty if the record does not exist. The caller closes the returned record, or reads its stream - * to the end. Like {@link com.apify.client.dataset.DatasetClient#streamItems}, this bypasses the - * retrying transport, so an error status is thrown as an {@link - * com.apify.client.http.ApifyApiException} without a retry. + * to the end. The request is retried like any other, until the response headers arrive; an error + * status that is not retried (any more) is thrown as an {@link + * com.apify.client.http.ApifyApiException}. A failure while reading the body is not retried. */ public CompletableFuture> getRecordStream(String key) { return getRecordStream(key, new GetRecordOptions().attachment(true)); @@ -385,10 +385,10 @@ private static Timeout timeoutOf(SetRecordOptions options) { /** * Stores a record whose bytes are read from {@code value}, never held in memory whole, so a large - * file can be uploaded. The stream is closed once it is read. It can be read once, so the upload - * is sent once: it is not retried on failure or compressed, and a redirect that needs the body - * again fails the request. To upload a file with retries, read it into a {@code byte[]} and use - * {@link #setRecord(String, byte[], String)} instead. + * file can be uploaded. The stream is closed when the call completes. It can be read once, so the + * upload is sent once: it is not retried on failure, compressed, or sent again to follow a + * redirect. To upload a file with retries, read it into a {@code byte[]} and use {@link + * #setRecord(String, byte[], String)} instead. */ public CompletableFuture setRecord(String key, InputStream value, String contentType) { return setRecord(key, value, contentType, new SetRecordOptions()); diff --git a/src/main/java/com/apify/client/task/TaskClient.java b/src/main/java/com/apify/client/task/TaskClient.java index e838ebb..db5b81d 100644 --- a/src/main/java/com/apify/client/task/TaskClient.java +++ b/src/main/java/com/apify/client/task/TaskClient.java @@ -78,7 +78,7 @@ public CompletableFuture unpublish() { * Starts the task and completes with the created run as soon as it exists (no waiting). {@code * input} optionally overrides the task's stored input ({@code null} to use the stored input). As * for {@link com.apify.client.actor.ActorClient#start}, it can be a {@code byte[]}, {@link - * String} or {@link java.io.InputStream} that is sent as it is; a stream is sent once, with no + * String}, or {@link java.io.InputStream} that is sent as it is; a stream is sent once, with no * retry. */ public CompletableFuture start(Object input, TaskStartOptions options) { diff --git a/src/test/java/com/apify/client/StreamBodyTest.java b/src/test/java/com/apify/client/StreamBodyTest.java index 63e04af..72a60d5 100644 --- a/src/test/java/com/apify/client/StreamBodyTest.java +++ b/src/test/java/com/apify/client/StreamBodyTest.java @@ -10,7 +10,8 @@ import com.apify.client.actor.ActorServerRequestOptions; import com.apify.client.actor.ActorStartOptions; import com.apify.client.http.ApifyApiException; -import com.apify.client.http.ApifyTransportException; +import com.apify.client.http.ForbiddenError; +import com.apify.client.http.ServerActorException; import com.apify.client.http.ServerError; import com.apify.client.keyvalue.KeyValueStoreRecordStream; import com.apify.client.keyvalue.SetRecordOptions; @@ -27,6 +28,8 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -48,6 +51,13 @@ class StreamBodyTest { private TestHttpServer server; + /** + * Counts the reads of the records that fail once, so the first read fails and the retry works. + */ + private final AtomicInteger flakyReads = new AtomicInteger(); + + private final AtomicInteger droppedReads = new AtomicInteger(); + /** * The statuses the server answers record uploads with, one per request, before it answers 200. */ @@ -71,6 +81,22 @@ private TestHttpServer.Reply answer(TestHttpServer.Received request) { if (path.equals(RECORD_PATH) && request.method().equals("GET")) { return TestHttpServer.Reply.of(200, "text/plain", "streamed record"); } + if (path.endsWith("/records/flaky") && flakyReads.getAndIncrement() == 0) { + return TestHttpServer.Reply.json(503, "{\"error\":{\"type\":\"x\"}}"); + } + if (path.endsWith("/records/dropped") && droppedReads.getAndIncrement() == 0) { + return TestHttpServer.Reply.drop(); + } + if (path.endsWith("/records/flaky") || path.endsWith("/records/dropped")) { + return TestHttpServer.Reply.of(200, "text/plain", "after retry"); + } + if (path.endsWith("/records/forbidden")) { + return TestHttpServer.Reply.json( + 403, "{\"error\":{\"type\":\"forbidden\",\"message\":\"no access\"}}"); + } + if (path.equals("/v2/actors/plain")) { + return TestHttpServer.Reply.json(200, "{\"data\":{\"id\":\"plain\"}}"); + } if (path.endsWith("/records/missing")) { return TestHttpServer.Reply.json( 404, "{\"error\":{\"type\":\"record-not-found\",\"message\":\"no record\"}}"); @@ -209,7 +235,7 @@ void setRecordRetriesTheSameBytesAsAnArray() { } @Test - void setRecordFailsInsteadOfSendingAnEmptyBodyWhenARedirectNeedsTheStreamAgain() { + void setRecordDoesNotFollowARedirectWithAStream() { CompletionException error = assertThrows( CompletionException.class, @@ -218,8 +244,71 @@ void setRecordFailsInsteadOfSendingAnEmptyBodyWhenARedirectNeedsTheStreamAgain() .keyValueStore("s1") .setRecord("redirected", streamOf(new byte[] {1, 2, 3}), "text/plain") .join()); - assertInstanceOf(ApifyTransportException.class, rootOf(error)); - assertEquals(0, requestsTo(RECORD_PATH), "the redirect target never receives an empty body"); + assertEquals(307, assertInstanceOf(ApifyApiException.class, rootOf(error)).getStatusCode()); + assertEquals(0, requestsTo(RECORD_PATH), "the redirect target is never contacted"); + } + + // ---- closing the stream ---------------------------------------------------------------------- + + /** A stream that records whether it was closed. */ + private static final class TrackedStream extends ByteArrayInputStream { + private final AtomicBoolean closed = new AtomicBoolean(); + + TrackedStream() { + super(new byte[] {1, 2, 3}); + } + + @Override + public void close() throws IOException { + closed.set(true); + super.close(); + } + } + + @Test + void aStreamBodyIsClosedAfterASuccessfulCall() { + TrackedStream stream = new TrackedStream(); + client().keyValueStore("s1").setRecord("key", stream, "text/plain").join(); + assertTrue(stream.closed.get()); + } + + @Test + void aStreamBodyIsClosedAfterAFailedCall() { + uploadStatuses.add(503); + TrackedStream stream = new TrackedStream(); + assertThrows( + CompletionException.class, + () -> client().keyValueStore("s1").setRecord("key", stream, "text/plain").join()); + assertTrue(stream.closed.get()); + } + + @Test + void aStreamBodyIsClosedWhenTheConnectionFails() throws IOException { + String unreachable = server.url(); + server.close(); + ApifyClient client = + ApifyClient.builder().token("t").baseUrl(unreachable).maxRetries(0).build(); + TrackedStream stream = new TrackedStream(); + assertThrows( + CompletionException.class, + () -> client.actor("a1").start(stream, new ActorStartOptions()).join()); + assertTrue(stream.closed.get()); + } + + @Test + void aStreamBodyIsClosedWhenTheActorIsNotAServerActor() { + TrackedStream stream = new TrackedStream(); + CompletionException error = + assertThrows( + CompletionException.class, + () -> + client() + .actor("plain") + .server() + .request("/", new ActorServerRequestOptions().method("POST").body(stream)) + .join()); + assertInstanceOf(ServerActorException.class, rootOf(error)); + assertTrue(stream.closed.get()); } // ---- streamed record read -------------------------------------------------------------------- @@ -243,6 +332,36 @@ void getRecordStreamCompletesWithEmptyForAMissingRecord() { assertTrue(client().keyValueStore("s1").getRecordStream("missing").join().isEmpty()); } + @Test + void getRecordStreamRetriesARetryableStatus() throws IOException { + try (KeyValueStoreRecordStream record = + client().keyValueStore("s1").getRecordStream("flaky").join().orElseThrow()) { + assertEquals( + "after retry", new String(record.getValue().readAllBytes(), StandardCharsets.UTF_8)); + } + assertEquals(2, requestsTo("/v2/key-value-stores/s1/records/flaky")); + } + + @Test + void getRecordStreamRetriesATransportError() throws IOException { + try (KeyValueStoreRecordStream record = + client().keyValueStore("s1").getRecordStream("dropped").join().orElseThrow()) { + assertEquals( + "after retry", new String(record.getValue().readAllBytes(), StandardCharsets.UTF_8)); + } + assertEquals(2, requestsTo("/v2/key-value-stores/s1/records/dropped")); + } + + @Test + void getRecordStreamThrowsOnAnErrorStatusThatIsNotRetried() { + CompletionException error = + assertThrows( + CompletionException.class, + () -> client().keyValueStore("s1").getRecordStream("forbidden").join()); + assertInstanceOf(ForbiddenError.class, rootOf(error)); + assertEquals(1, requestsTo("/v2/key-value-stores/s1/records/forbidden")); + } + @Test void aRecordStreamCanBePassedStraightToSetRecord() throws IOException { ApifyClient client = client(); From 1932a17662e3b10c923cbd85d65f99e0253985e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:36:31 +0000 Subject: [PATCH 04/19] fix: guard stream bodies against a second send, retry log and dataset streams, and document the transport requirement --- CHANGELOG.md | 7 +- docs/storages.md | 2 +- .../apify/client/actor/ActorServerClient.java | 4 +- .../apify/client/dataset/DatasetClient.java | 7 +- .../com/apify/client/http/HttpTransport.java | 14 +-- .../apify/client/internal/HttpClientCore.java | 67 +++++++------- .../client/internal/ResourceContext.java | 4 +- .../client/keyvalue/KeyValueStoreClient.java | 2 +- .../java/com/apify/client/log/LogClient.java | 6 +- .../client/ClientBehaviourRegressionTest.java | 26 ++++++ .../java/com/apify/client/StreamBodyTest.java | 88 ++++++++++++++++++- 11 files changed, 174 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c99e1..326e37e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,9 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating`, and `actorReviewCount`. - `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isWhiteListedForAgenticPayments`, `isVerified`, and `badge`. -- `KeyValueStoreClient.setRecord` overloads that take an `InputStream`. The stream is sent without being held in memory, and the upload is not retried or compressed. -- `KeyValueStoreClient.getRecordStream` and `KeyValueStoreRecordStream`, which read a record as an `InputStream`. -- `InputStream` as the input of `ActorClient.start`, `ActorClient.call`, `TaskClient.start`, and `TaskClient.call`, and as the body of `ActorServerClient.request` and `requestStream`. A stream is sent once, with no retry. +- `KeyValueStoreClient.setRecord` overloads that take an `InputStream`. The stream is sent without being held in memory, and the upload is not retried or compressed. Like a request to an Actor's server, it needs an `HttpTransport` that can disable redirects. +- `KeyValueStoreClient.getRecordStream` and `KeyValueStoreRecordStream`, which read a record as an `InputStream`. The request is retried like any other. +- `InputStream` as the input of `ActorClient.start`, `ActorClient.call`, `TaskClient.start`, and `TaskClient.call`, and as the body of `ActorServerClient.request` and `requestStream`. A stream is sent once, with no retry, and needs an `HttpTransport` that can disable redirects. - `APIFY_AI` run origin. ### Changed @@ -21,6 +21,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - **Breaking:** `ActorStoreListItem.getStats()` returns `StoreActorStats` instead of `ActorStats`. The Store no longer returns `totalBuilds`, `totalMetamorphs`, and `lastRunStartedAt`. - **Breaking:** `StoreCollectionClient.iterate` sends one request when `search` is set, since the Store returns a single page of at most 100 Actors for a search and ignores `offset`. `chunkSize` and `offset` have no effect for a search. - `StoreListOptions.category` takes comma-separated category IDs. +- `LogClient.stream` and `DatasetClient.streamItems` retry the request like any other, until the response headers arrive. - `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. - Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). - `ActorClient.validateInput` and `RunClient.metamorph` throw `IllegalArgumentException` for an `InputStream` input, instead of serializing it to JSON. diff --git a/docs/storages.md b/docs/storages.md index 9049510..65c1dcf 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -142,7 +142,7 @@ datasets. | `getRecord(String key)` / `getRecord(String key, GetRecordOptions)` | Fetch a record. Completes with `Optional`. | | `setRecord(String key, byte[] value, String contentType)` | Store raw bytes. Completes with no value (`CompletableFuture`). | | `setRecord(String key, byte[] value, String contentType, SetRecordOptions)` | Store raw bytes with write options (`SetRecordOptions`: `timeoutSecs` (`Long`) or `timeout` (`Timeout`: a tier, an exact duration or `NO_TIMEOUT`; the default is the `LONG` tier), `doNotRetryTimeouts` (`Boolean`), `contentEncoding` (`String`, see below)). Completes with no value. | -| `getRecordStream(String key)` / `getRecordStream(String key, GetRecordOptions)` | As `getRecord`, but completes with an `Optional` whose `getValue()` is a live `InputStream`, so a large record is processed in chunks. Close the record (or read its stream to the end) when done. The request is retried like any other, until the headers arrive. Throws on an error response that is not retried (any more), except a 404, which completes with empty. A failure while reading the body is not retried. | +| `getRecordStream(String key)` / `getRecordStream(String key, GetRecordOptions)` | As `getRecord`, but completes with an `Optional` whose `getValue()` is a live `InputStream`, so a large record is processed in chunks. Close the record (or read its stream to the end) when done. The request is retried like any other, until the headers arrive. Throws on an error response that is not retried, or the last one once the retries run out, except a 404, which completes with empty. A failure while reading the body is not retried. | | `setRecord(String key, InputStream value, String contentType)` / `setRecord(String key, InputStream value, String contentType, SetRecordOptions)` | Store the bytes read from a stream, without holding them in memory, so a large file can be uploaded. The stream is closed when the call completes. It can be read once, so the upload is sent once: it is not retried, compressed, or sent again to follow a redirect, and `doNotRetryTimeouts` has no effect. Completes with no value. | | `setRecordJson(String key, Object value)` | Store JSON. Completes with no value. | | `deleteRecord(String key)` | Delete a record. Completes with no value. | diff --git a/src/main/java/com/apify/client/actor/ActorServerClient.java b/src/main/java/com/apify/client/actor/ActorServerClient.java index 09b8ff6..c9d035a 100644 --- a/src/main/java/com/apify/client/actor/ActorServerClient.java +++ b/src/main/java/com/apify/client/actor/ActorServerClient.java @@ -290,8 +290,8 @@ public CompletableFuture requestStream( } /** - * Closes a stream request body once the call completed. The transport closes it when it sends the - * request, so this matters when the request never got that far, for example because the Actor is + * Closes a stream request body when the call completes. The client closes it itself once the + * request is made, so this matters when the request never was, for example because the Actor is * not a Server Actor. */ private static void closeUnused(InputStream stream) { diff --git a/src/main/java/com/apify/client/dataset/DatasetClient.java b/src/main/java/com/apify/client/dataset/DatasetClient.java index 71a143a..a8b89d0 100644 --- a/src/main/java/com/apify/client/dataset/DatasetClient.java +++ b/src/main/java/com/apify/client/dataset/DatasetClient.java @@ -216,9 +216,10 @@ public CompletableFuture downloadItems( * As {@link #downloadItems}, but resolves to the response body as a live {@link InputStream} * instead of fully buffering it, so a large export can be processed in chunks without holding all * of it in memory. The caller is responsible for closing the returned stream (or reading it to - * the end). Like {@link com.apify.client.log.LogClient#stream}, this bypasses the - * buffered/retrying transport, so a non-2xx response is read to completion and thrown as an - * {@link com.apify.client.http.ApifyApiException} rather than retried. + * the end). The request is retried like any other, until the response headers arrive; an error + * status that is not retried, or the last one once the retries run out, is read to completion and + * thrown as an {@link com.apify.client.http.ApifyApiException}. A failure while reading the body + * is not retried. */ public CompletableFuture streamItems( DownloadItemsFormat format, DatasetDownloadOptions options) { diff --git a/src/main/java/com/apify/client/http/HttpTransport.java b/src/main/java/com/apify/client/http/HttpTransport.java index 8a3b3f4..beb3b87 100644 --- a/src/main/java/com/apify/client/http/HttpTransport.java +++ b/src/main/java/com/apify/client/http/HttpTransport.java @@ -44,12 +44,15 @@ public interface HttpTransport { * As {@link #sendAsync(HttpRequest)}, but a transport that is asked not to follow redirects * returns a redirect response as it is, since the request carries a token that must not follow a * redirect to another host. A request to an Actor's server is sent this way (see {@link - * com.apify.client.actor.ActorServerClient#request}). + * com.apify.client.actor.ActorServerClient#request}), and so is a request whose body is an {@link + * InputStream}, which can be sent only once (for example {@link + * com.apify.client.keyvalue.KeyValueStoreClient#setRecord(String, InputStream, String)}). * *

The default implementation sends the request as {@link #sendAsync(HttpRequest)} does when * {@code followRedirects} is {@code true}, and otherwise completes the returned future * exceptionally with an {@link UnsupportedOperationException}: a transport that cannot hold back - * redirects must not be trusted with such a request. Override it to support them. + * redirects must not be trusted with such a request. Override it to support them; without that, a + * request with a stream body fails. * * @param followRedirects whether the transport may follow redirects */ @@ -77,8 +80,9 @@ default CompletableFuture> sendStreamingAsync( private static UnsupportedOperationException redirectsCannotBeDisabled() { return new UnsupportedOperationException( "This HttpTransport does not support disabling redirects, which a request to an Actor's" - + " server needs so that the API token never follows a redirect to another host." - + " Override sendAsync(HttpRequest, boolean) and sendStreamingAsync(HttpRequest," - + " boolean) to support it."); + + " server needs so that the API token never follows a redirect to another host," + + " and a request with an InputStream body needs so that the stream is never sent" + + " twice. Override sendAsync(HttpRequest, boolean) and" + + " sendStreamingAsync(HttpRequest, boolean) to support it."); } } diff --git a/src/main/java/com/apify/client/internal/HttpClientCore.java b/src/main/java/com/apify/client/internal/HttpClientCore.java index 9a05349..6e27904 100644 --- a/src/main/java/com/apify/client/internal/HttpClientCore.java +++ b/src/main/java/com/apify/client/internal/HttpClientCore.java @@ -35,6 +35,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -361,8 +362,8 @@ public CompletableFuture call( /** * Sends a request whose body is read from {@code body}, with auth and the User-Agent applied. A * stream can be read once, so the request is sent exactly once: it is never retried, compressed, - * or sent again to follow a redirect. {@code body} is closed when the call completes, whether it - * succeeded or not. + * or sent again to follow a redirect or answer an authentication challenge. {@code body} is + * closed when the call completes, whether it succeeded or not. */ public CompletableFuture callWithStream( String method, @@ -375,7 +376,7 @@ public CompletableFuture callWithStream( return attemptWithRetry( method, url, - HttpRequest.BodyPublishers.ofInputStream(() -> body), + streamPublisher(body), contentType, extraHeaders, resolveTimeout(timeout), @@ -388,6 +389,26 @@ public CompletableFuture callWithStream( .whenComplete((response, error) -> closeQuietly(body)); } + /** + * A single-use body publisher that reads {@code body}. The JDK subscribes again to send the body + * once more in some cases, a 401 or 407 challenge answered by an authenticator for one, and + * {@code body} is then already read. A later subscription gets a stream that fails to read, so + * the request fails instead of silently sending an empty body. + */ + private static HttpRequest.BodyPublisher streamPublisher(InputStream body) { + AtomicBoolean handedOut = new AtomicBoolean(); + return HttpRequest.BodyPublishers.ofInputStream( + () -> handedOut.compareAndSet(false, true) ? body : new SentStream()); + } + + /** The body of a stream request that was already sent: reading it fails. */ + private static final class SentStream extends InputStream { + @Override + public int read() throws IOException { + throw new IOException("The request body is a stream, which cannot be sent a second time"); + } + } + /** A request body, as it is sent, with the headers that go with it. */ private record PreparedBody(byte[] body, Map headers) {} @@ -877,25 +898,14 @@ public static String extractPath(String url) { } } - /** - * Opens a live streaming response (single attempt, no retry). Used by log streaming. The returned - * future completes exceptionally with an {@link ApifyTransportException} on a transport failure; - * a non-2xx status is returned as a normal response for the caller (log streaming) to inspect, - * matching {@link HttpTransport}'s contract. - */ - public CompletableFuture> streamAsync(String url) { - HttpRequest request = buildRequest("GET", url, null, null, null, resolveTimeout(Timeout.LONG)); - return openStream(request, true); - } - /** * Opens a live streaming response to a request, as {@link #call(String, String, byte[], String, * Map, Timeout, boolean, RequestPolicy)} would send it. A status the policy retries is retried - * with the client's retry settings, each discarded response closed, and so is a transport error - * if the policy retries those. The last response is handed back with its body unread, for the + * with the client's retry settings, closing each discarded response; a transport error is retried + * too if the policy says so. The last response is handed back with its body unread, for the * caller to inspect and close, unless the policy throws on an error status: it is then drained * and thrown as an {@link ApifyApiException}. The future completes exceptionally with an {@link - * ApifyTransportException} on a transport failure that is not retried (any more). + * ApifyTransportException} on a transport failure once the retries run out. */ public CompletableFuture> streamRequest( String method, @@ -942,7 +952,7 @@ public CompletableFuture> streamRequest( buildPublisherRequest( method, url, - HttpRequest.BodyPublishers.ofInputStream(() -> body), + streamPublisher(body), contentType, extraHeaders, attemptTimeout(resolveTimeout(timeout), 1), @@ -1057,17 +1067,18 @@ private CompletableFuture> openStream( } /** - * As {@link #streamAsync(String)}, additionally inspecting the response itself: a non-2xx status - * is drained and thrown as the matching {@link ApifyApiException} subclass (single attempt - this - * bypasses the retrying transport, so the attempt number is always 1), while a success response - * completes with its live body stream. Shared by every streaming resource method (log streaming, + * Opens a live {@code GET} stream and completes with its body: the request is retried like any + * other, until the response headers arrive, and an error status that is not retried (or the last + * one) is drained and thrown as the matching {@link ApifyApiException} subclass. A failure while + * the body is read is not retried. Shared by every streaming resource method (log streaming, * dataset export streaming) so the drain-and-throw logic lives in one place. */ public CompletableFuture streamOrThrow(String url) { CancellableFuture result = new CancellableFuture<>(); - CompletableFuture> stream = streamAsync(url); - result.link(stream); - stream.whenComplete( + CompletableFuture> response = + streamRequest("GET", url, (byte[]) null, null, null, Timeout.LONG, RequestPolicy.API); + result.link(response); + response.whenComplete( (resp, err) -> { if (err != null) { Throwable cause = unwrapCompletion(err); @@ -1076,12 +1087,6 @@ public CompletableFuture streamOrThrow(String url) { } else { result.completeExceptionally(cause); } - return; - } - if (resp.statusCode() >= MAX_SUCCESS_STATUS) { - byte[] body = drainQuietly(resp.body()); - result.completeExceptionally( - buildApiError(resp.statusCode(), body, 1, "GET", extractPath(url))); } else if (!result.complete(resp.body())) { closeQuietly(resp.body()); } diff --git a/src/main/java/com/apify/client/internal/ResourceContext.java b/src/main/java/com/apify/client/internal/ResourceContext.java index c33efc9..6ff7c3e 100644 --- a/src/main/java/com/apify/client/internal/ResourceContext.java +++ b/src/main/java/com/apify/client/internal/ResourceContext.java @@ -424,8 +424,8 @@ public CompletableFuture postWithStreamBody( /** * GET returning the live response, its body unread. Retries like any other request, throws on an - * error status that is not retried (any more), and completes with {@code null} on not-found. The - * caller closes the body stream. + * error status once the retries run out or for a status that is not retried, and completes with + * {@code null} on not-found. The caller closes the body stream. */ public CompletableFuture> getStream( String subPath, QueryParams params) { diff --git a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java index 07717e7..1475a65 100644 --- a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java +++ b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java @@ -316,7 +316,7 @@ public CompletableFuture> getRecord( * to {@link #setRecord(String, InputStream, String)} without being held in memory. Completes with * empty if the record does not exist. The caller closes the returned record, or reads its stream * to the end. The request is retried like any other, until the response headers arrive; an error - * status that is not retried (any more) is thrown as an {@link + * status that is not retried, or the last one once the retries run out, is thrown as an {@link * com.apify.client.http.ApifyApiException}. A failure while reading the body is not retried. */ public CompletableFuture> getRecordStream(String key) { diff --git a/src/main/java/com/apify/client/log/LogClient.java b/src/main/java/com/apify/client/log/LogClient.java index 9515ee5..8604a61 100644 --- a/src/main/java/com/apify/client/log/LogClient.java +++ b/src/main/java/com/apify/client/log/LogClient.java @@ -78,9 +78,9 @@ public CompletableFuture> getAsBytes(LogOptions options) { * Opens a live, streaming connection to the log and completes with a stream over the log bytes. * The caller is responsible for closing the returned {@link InputStream}. * - *

Unlike {@link #get()}, this bypasses the buffered/retrying transport so the log can be - * followed in real time as the run produces it (the {@code stream=1} query parameter). Because - * the response is consumed incrementally, it is not retried. + *

Unlike {@link #get()}, this does not buffer the response, so the log can be followed in real + * time as the run produces it (the {@code stream=1} query parameter). The request is retried like + * any other, until the response headers arrive; a failure while the body is read is not retried. */ public CompletableFuture stream() { return stream(new LogOptions()); diff --git a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java index 944dcab..75de210 100644 --- a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java +++ b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java @@ -1201,6 +1201,32 @@ void streamItemsThrowsOnNonSuccessStatus() { assertEquals(404, ex.getStatusCode()); } + @Test + void streamItemsRetriesARetryableStatusUntilTheHeadersArrive() throws java.io.IOException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(503, "{\"error\":{\"type\":\"x\",\"message\":\"busy\"}}"); + backend.scriptStream(200, "a;b\n1;2\n"); + java.io.InputStream stream = + TestAsync.await( + client(backend, 2) + .dataset("d1") + .streamItems(DownloadItemsFormat.CSV, new DatasetDownloadOptions())); + assertEquals( + "a;b\n1;2\n", new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + assertEquals(2, backend.calls, "the 503 is retried"); + } + + @Test + void logStreamRetriesARetryableStatusUntilTheHeadersArrive() throws java.io.IOException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(503, "{\"error\":{\"type\":\"x\",\"message\":\"busy\"}}"); + backend.scriptStream(200, "log line\n"); + java.io.InputStream stream = TestAsync.await(client(backend, 2).run("r1").log().stream()); + assertEquals( + "log line\n", new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + assertEquals(2, backend.calls, "the 503 is retried"); + } + @Test void logGetAsBytesReturnsRawBytes() { MockTransport backend = MockTransport.ofConstant(200, "log line 1\nlog line 2\n"); diff --git a/src/test/java/com/apify/client/StreamBodyTest.java b/src/test/java/com/apify/client/StreamBodyTest.java index 72a60d5..d0bfe64 100644 --- a/src/test/java/com/apify/client/StreamBodyTest.java +++ b/src/test/java/com/apify/client/StreamBodyTest.java @@ -10,6 +10,8 @@ import com.apify.client.actor.ActorServerRequestOptions; import com.apify.client.actor.ActorStartOptions; import com.apify.client.http.ApifyApiException; +import com.apify.client.http.ApifyTransportException; +import com.apify.client.http.DefaultHttpTransport; import com.apify.client.http.ForbiddenError; import com.apify.client.http.ServerActorException; import com.apify.client.http.ServerError; @@ -21,11 +23,15 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.http.HttpClient; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicBoolean; @@ -94,6 +100,12 @@ private TestHttpServer.Reply answer(TestHttpServer.Received request) { return TestHttpServer.Reply.json( 403, "{\"error\":{\"type\":\"forbidden\",\"message\":\"no access\"}}"); } + if (path.equals("/v2/actors/dead")) { + return TestHttpServer.Reply.json( + 200, + "{\"data\":{\"id\":\"dead\",\"actorStandby\":{\"isEnabled\":true}," + + "\"standbyUrl\":\"http://127.0.0.1:1/server\"}}"); + } if (path.equals("/v2/actors/plain")) { return TestHttpServer.Reply.json(200, "{\"data\":{\"id\":\"plain\"}}"); } @@ -248,6 +260,51 @@ void setRecordDoesNotFollowARedirectWithAStream() { assertEquals(0, requestsTo(RECORD_PATH), "the redirect target is never contacted"); } + @Test + void aStreamBodyIsNotSentAgainToAnswerAnAuthenticationChallenge() throws IOException { + // The JDK client answers a 401 challenge by sending the request, body included, a second time. + // The stream is already read by then, so the call must fail instead of sending an empty body. + server.close(); + try (TestHttpServer challenging = + new TestHttpServer( + request -> + request.header("Authorization") == null + || !request.header("Authorization").startsWith("Basic") + ? new TestHttpServer.Reply( + 401, Map.of("WWW-Authenticate", "Basic realm=\"x\""), new byte[0], false) + : TestHttpServer.Reply.json(200, "{}"))) { + HttpClient jdk = + HttpClient.newBuilder() + .authenticator( + new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication("user", "pass".toCharArray()); + } + }) + .build(); + ApifyClient client = + ApifyClient.builder() + .token("t") + .baseUrl(challenging.url()) + .httpTransport(new DefaultHttpTransport(jdk)) + .maxRetries(0) + .build(); + + assertThrows( + CompletionException.class, + () -> + client + .keyValueStore("s1") + .setRecord("key", streamOf(new byte[] {1, 2, 3}), "text/plain") + .join()); + assertTrue( + challenging.received().stream() + .noneMatch(r -> r.header("Authorization") != null && r.body().length == 0), + "no empty body is sent with the credentials"); + } + } + // ---- closing the stream ---------------------------------------------------------------------- /** A stream that records whether it was closed. */ @@ -266,10 +323,23 @@ public void close() throws IOException { } @Test - void aStreamBodyIsClosedAfterASuccessfulCall() { + void aStreamBodyIsClosedAndTheErrorNamesTheCauseWhenTheTransportCannotDisableRedirects() { + // A transport that implements only the two required methods cannot hold back redirects, so a + // request with a stream body fails before the stream is read. + MockTransport transport = MockTransport.ofConstant(200, "{}"); + ApifyClient client = ApifyClient.builder().token("t").httpTransport(transport).build(); TrackedStream stream = new TrackedStream(); - client().keyValueStore("s1").setRecord("key", stream, "text/plain").join(); + CompletionException error = + assertThrows( + CompletionException.class, + () -> client.keyValueStore("s1").setRecord("key", stream, "text/plain").join()); + UnsupportedOperationException cause = + assertInstanceOf( + UnsupportedOperationException.class, + assertInstanceOf(ApifyTransportException.class, rootOf(error)).getCause()); + assertTrue(cause.getMessage().contains("InputStream"), cause.getMessage()); assertTrue(stream.closed.get()); + assertEquals(0, transport.calls); } @Test @@ -295,6 +365,20 @@ void aStreamBodyIsClosedWhenTheConnectionFails() throws IOException { assertTrue(stream.closed.get()); } + @Test + void aStreamBodyOfRequestStreamIsClosedWhenTheServerIsUnreachable() { + TrackedStream stream = new TrackedStream(); + assertThrows( + CompletionException.class, + () -> + client() + .actor("dead") + .server() + .requestStream("/", new ActorServerRequestOptions().method("POST").body(stream)) + .join()); + assertTrue(stream.closed.get()); + } + @Test void aStreamBodyIsClosedWhenTheActorIsNotAServerActor() { TrackedStream stream = new TrackedStream(); From c868713468983968fb5dc697150804b498478487 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:47:57 +0000 Subject: [PATCH 05/19] docs: align stream retry docs and Javadoc wording --- README.md | 2 +- docs/misc.md | 2 +- docs/storages.md | 2 +- .../apify/client/actor/ActorServerClient.java | 6 +++--- .../com/apify/client/http/HttpTransport.java | 5 +++-- .../apify/client/internal/HttpClientCore.java | 21 ++++++++++--------- 6 files changed, 20 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index f2bf09a..ea25c64 100644 --- a/README.md +++ b/README.md @@ -309,7 +309,7 @@ both non-blocking. `HttpRequest` and `HttpResponse` below are the JDK's `java | Method | Signature | Contract | |---|---|---| | `sendAsync` | `CompletableFuture> sendAsync(HttpRequest request)` | Sends the single, fully-prepared request (auth, `User-Agent` and any other headers are already set by the client) and completes the future with the response with its body fully buffered as `byte[]`. Used for every non-streaming call. | -| `sendStreamingAsync` | `CompletableFuture> sendStreamingAsync(HttpRequest request)` | Sends the request and completes the future with the response body as a live `InputStream` for incremental consumption, used by log streaming (`LogClient.stream(...)`) and dataset export streaming (`DatasetClient.streamItems(...)`). The *caller* (the client) is responsible for closing the returned stream; an implementation must not close it itself before completing the future. | +| `sendStreamingAsync` | `CompletableFuture> sendStreamingAsync(HttpRequest request)` | Sends the request and completes the future with the response body as a live `InputStream` for incremental consumption, used by log streaming (`LogClient.stream(...)`), dataset export streaming (`DatasetClient.streamItems(...)`), record streaming (`KeyValueStoreClient.getRecordStream(...)`), and Server Actor response streaming (`ActorServerClient.requestStream(...)`). The *caller* (the client) is responsible for closing the returned stream; an implementation must not close it itself before completing the future. | Two further methods, `sendAsync(HttpRequest, boolean followRedirects)` and `sendStreamingAsync(HttpRequest, boolean followRedirects)`, have default implementations that send diff --git a/docs/misc.md b/docs/misc.md index 6a32172..518d54f 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -110,7 +110,7 @@ Access a build's or run's log directly, or via `client.run(id).log()` / `client. |---|---| | `get()` / `get(LogOptions)` | The whole log as text. Completes with `Optional` when addressed by an explicit id (`client.log(id)`); on `run.log()`/`build.log()` (no log id of its own), a 404 is ambiguous and throws `NotFoundError` instead; see [Fetching single resources](../README.md#fetching-single-resources). | | `getAsBytes()` / `getAsBytes(LogOptions)` | As `get()`, but completes with `Optional` (the raw bytes, not decoded as text). Same 404 handling as `get()`. | -| `stream()` / `stream(LogOptions)` | A live `InputStream` over the log (for redirection). Completes with `InputStream`; throws on any error response, including a 404. | +| `stream()` / `stream(LogOptions)` | A live `InputStream` over the log (for redirection). Completes with `InputStream`. The request is retried like any other, until the headers arrive; it throws on an error response that is not retried, or the last one once the retries run out, including a 404. | `LogOptions` fields: `raw(Boolean)`, `download(Boolean)`. diff --git a/docs/storages.md b/docs/storages.md index 65c1dcf..b56fa1a 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -52,7 +52,7 @@ any field not covered by a typed getter above is still available via the inherit | `iterateItems(DatasetListItemsOptions)` / `iterateItems(DatasetListItemsOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all items; the options' `limit` caps the dataset *rows* read (`null`/unset or non-positive = all), the optional `chunkSize` sets the per-request page size. Dataset items have no default page limit, so without `chunkSize` the whole dataset (or all `limit` rows) is loaded in one response: pass `chunkSize` to iterate a large dataset. | | `iterateItems(DatasetListItemsOptions, Long chunkSize, Class)` | As above, decoded into `T`. Returns `Flow.Publisher`. For typed iteration in one response, pass a `null` chunk size: `iterateItems(opts, null, T.class)`. | | `downloadItems(DownloadItemsFormat, DatasetDownloadOptions)` | Serialized bytes. `DownloadItemsFormat` is one of `JSON`, `JSONL`, `CSV`, `XLSX`, `XML`, `RSS`, `HTML`. Completes with `byte[]`. | -| `streamItems(DownloadItemsFormat, DatasetDownloadOptions)` | As above, but resolves to a live `InputStream` over the export instead of fully buffering it, so a large export is processed in chunks. The caller closes the stream (or reads it to the end). Throws on any error response, including a 404. | +| `streamItems(DownloadItemsFormat, DatasetDownloadOptions)` | As above, but resolves to a live `InputStream` over the export instead of fully buffering it, so a large export is processed in chunks. The caller closes the stream (or reads it to the end). The request is retried like any other, until the headers arrive; it throws on an error response that is not retried, or the last one once the retries run out, including a 404. | | `pushItems(Object)` | Push a single item (a `Map`, a POJO, a `JsonNode` object, ...), a list/array of items, or a `String` that already is the JSON serialization of either (sent as it is). The API accepts only an object or an array of objects, so anything else (a number, a plain string, an array of strings) throws `IllegalArgumentException` before a request is sent. A push that times out is not retried, so items cannot be stored twice. Completes with no value (`CompletableFuture`). | | `getStatistics()` | Dataset statistics. Completes with `JsonNode`; throws `NotFoundError` if the dataset is gone (no separate "statistics absent" state). | | `createItemsPublicUrl(DatasetListItemsOptions, Long expiresInSecs)` | A public (optionally signed) items URL, served as `json`. `expiresInSecs` must be positive and at most `4611686018427387` when set. Completes with `String`. | diff --git a/src/main/java/com/apify/client/actor/ActorServerClient.java b/src/main/java/com/apify/client/actor/ActorServerClient.java index c9d035a..8fe2899 100644 --- a/src/main/java/com/apify/client/actor/ActorServerClient.java +++ b/src/main/java/com/apify/client/actor/ActorServerClient.java @@ -290,9 +290,9 @@ public CompletableFuture requestStream( } /** - * Closes a stream request body when the call completes. The client closes it itself once the - * request is made, so this matters when the request never was, for example because the Actor is - * not a Server Actor. + * Closes a stream body when the URL lookup fails, before the request is made, for example because + * the Actor is not a Server Actor. Once the request is made, {@code HttpClientCore} closes the + * stream when the call completes. */ private static void closeUnused(InputStream stream) { if (stream != null) { diff --git a/src/main/java/com/apify/client/http/HttpTransport.java b/src/main/java/com/apify/client/http/HttpTransport.java index beb3b87..98797e0 100644 --- a/src/main/java/com/apify/client/http/HttpTransport.java +++ b/src/main/java/com/apify/client/http/HttpTransport.java @@ -35,8 +35,9 @@ public interface HttpTransport { /** * Sends a request and completes the returned future with the response body as a live {@link - * InputStream}, for incremental consumption (used by log streaming). The caller closes the - * stream. Completes exceptionally the same way as {@link #sendAsync(HttpRequest)}. + * InputStream}, for incremental consumption (used by log, dataset export, key-value store record, + * and Server Actor response streaming). The caller closes the stream. Completes exceptionally the + * same way as {@link #sendAsync(HttpRequest)}. */ CompletableFuture> sendStreamingAsync(HttpRequest request); diff --git a/src/main/java/com/apify/client/internal/HttpClientCore.java b/src/main/java/com/apify/client/internal/HttpClientCore.java index 6e27904..0a1b2e2 100644 --- a/src/main/java/com/apify/client/internal/HttpClientCore.java +++ b/src/main/java/com/apify/client/internal/HttpClientCore.java @@ -390,10 +390,10 @@ public CompletableFuture callWithStream( } /** - * A single-use body publisher that reads {@code body}. The JDK subscribes again to send the body - * once more in some cases, a 401 or 407 challenge answered by an authenticator for one, and - * {@code body} is then already read. A later subscription gets a stream that fails to read, so - * the request fails instead of silently sending an empty body. + * A single-use body publisher that reads {@code body}. The JDK can subscribe again to send the + * body once more, for example to answer a 401 or 407 challenge with an authenticator, and {@code + * body} is then already read. A later subscription gets a stream that fails to read, so the + * request fails instead of silently sending an empty body. */ private static HttpRequest.BodyPublisher streamPublisher(InputStream body) { AtomicBoolean handedOut = new AtomicBoolean(); @@ -936,8 +936,9 @@ public CompletableFuture> streamRequest( /** * As {@link #streamRequest(String, String, byte[], String, Map, Timeout, RequestPolicy)}, for a * body that is read from {@code body}. A stream can be read once, so the request is sent exactly - * once: it is never retried, compressed, or sent again to follow a redirect. {@code body} is - * closed when the response arrives or the request fails. + * once: it is never retried, compressed, or sent again to follow a redirect or answer an + * authentication challenge. {@code body} is closed when the response arrives or the request + * fails. */ public CompletableFuture> streamRequest( String method, @@ -1068,10 +1069,10 @@ private CompletableFuture> openStream( /** * Opens a live {@code GET} stream and completes with its body: the request is retried like any - * other, until the response headers arrive, and an error status that is not retried (or the last - * one) is drained and thrown as the matching {@link ApifyApiException} subclass. A failure while - * the body is read is not retried. Shared by every streaming resource method (log streaming, - * dataset export streaming) so the drain-and-throw logic lives in one place. + * other, until the response headers arrive, and an error status that is not retried, or the last + * one once the retries run out, is drained and thrown as the matching {@link ApifyApiException} + * subclass. A failure while the body is read is not retried. Shared by log streaming and dataset + * export streaming, so the drain-and-throw logic lives in one place. */ public CompletableFuture streamOrThrow(String url) { CancellableFuture result = new CancellableFuture<>(); From 231ef75fc28e992afb0a5f25f7b1e09bdbbd0691 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:49:48 +0000 Subject: [PATCH 06/19] docs: list the callers of the one-argument transport methods correctly --- README.md | 4 ++-- src/main/java/com/apify/client/http/HttpTransport.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ea25c64..ecc53e6 100644 --- a/README.md +++ b/README.md @@ -308,8 +308,8 @@ both non-blocking. `HttpRequest` and `HttpResponse` below are the JDK's `java | Method | Signature | Contract | |---|---|---| -| `sendAsync` | `CompletableFuture> sendAsync(HttpRequest request)` | Sends the single, fully-prepared request (auth, `User-Agent` and any other headers are already set by the client) and completes the future with the response with its body fully buffered as `byte[]`. Used for every non-streaming call. | -| `sendStreamingAsync` | `CompletableFuture> sendStreamingAsync(HttpRequest request)` | Sends the request and completes the future with the response body as a live `InputStream` for incremental consumption, used by log streaming (`LogClient.stream(...)`), dataset export streaming (`DatasetClient.streamItems(...)`), record streaming (`KeyValueStoreClient.getRecordStream(...)`), and Server Actor response streaming (`ActorServerClient.requestStream(...)`). The *caller* (the client) is responsible for closing the returned stream; an implementation must not close it itself before completing the future. | +| `sendAsync` | `CompletableFuture> sendAsync(HttpRequest request)` | Sends the single, fully-prepared request (auth, `User-Agent` and any other headers are already set by the client) and completes the future with the response with its body fully buffered as `byte[]`. Used for every non-streaming call that follows redirects. | +| `sendStreamingAsync` | `CompletableFuture> sendStreamingAsync(HttpRequest request)` | Sends the request and completes the future with the response body as a live `InputStream` for incremental consumption, used by log streaming (`LogClient.stream(...)`), dataset export streaming (`DatasetClient.streamItems(...)`), and record streaming (`KeyValueStoreClient.getRecordStream(...)`). The *caller* (the client) is responsible for closing the returned stream; an implementation must not close it itself before completing the future. | Two further methods, `sendAsync(HttpRequest, boolean followRedirects)` and `sendStreamingAsync(HttpRequest, boolean followRedirects)`, have default implementations that send diff --git a/src/main/java/com/apify/client/http/HttpTransport.java b/src/main/java/com/apify/client/http/HttpTransport.java index 98797e0..1cd4fed 100644 --- a/src/main/java/com/apify/client/http/HttpTransport.java +++ b/src/main/java/com/apify/client/http/HttpTransport.java @@ -35,9 +35,9 @@ public interface HttpTransport { /** * Sends a request and completes the returned future with the response body as a live {@link - * InputStream}, for incremental consumption (used by log, dataset export, key-value store record, - * and Server Actor response streaming). The caller closes the stream. Completes exceptionally the - * same way as {@link #sendAsync(HttpRequest)}. + * InputStream}, for incremental consumption (used by log, dataset export, and key-value store + * record streaming). The caller closes the stream. Completes exceptionally the same way as {@link + * #sendAsync(HttpRequest)}. */ CompletableFuture> sendStreamingAsync(HttpRequest request); From 65c76fc339372be3d73dedaec8f3b4d4305299ae Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:58:38 +0000 Subject: [PATCH 07/19] feat!: split the Store search from the Store listing StoreCollectionClient.search returns one page of the best matches. StoreListOptions no longer takes search or sortBy, which matches the reference client. --- CHANGELOG.md | 8 +- docs/README.md | 2 +- docs/misc.md | 49 ++++--- .../client/store/StoreCollectionClient.java | 45 +++--- .../client/store/StoreFilterOptions.java | 88 ++++++++++++ .../apify/client/store/StoreListOptions.java | 132 +++--------------- .../client/store/StoreSearchOptions.java | 53 +++++++ .../apify/client/store/StoreSearchResult.java | 35 +++++ .../client/ClientBehaviourRegressionTest.java | 57 +++++--- .../integration/StoreIntegrationTest.java | 56 +++++--- 10 files changed, 329 insertions(+), 196 deletions(-) create mode 100644 src/main/java/com/apify/client/store/StoreFilterOptions.java create mode 100644 src/main/java/com/apify/client/store/StoreSearchOptions.java create mode 100644 src/main/java/com/apify/client/store/StoreSearchResult.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 326e37e..684c9f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,21 +14,23 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - `KeyValueStoreClient.setRecord` overloads that take an `InputStream`. The stream is sent without being held in memory, and the upload is not retried or compressed. Like a request to an Actor's server, it needs an `HttpTransport` that can disable redirects. - `KeyValueStoreClient.getRecordStream` and `KeyValueStoreRecordStream`, which read a record as an `InputStream`. The request is retried like any other. - `InputStream` as the input of `ActorClient.start`, `ActorClient.call`, `TaskClient.start`, and `TaskClient.call`, and as the body of `ActorServerClient.request` and `requestStream`. A stream is sent once, with no retry, and needs an `HttpTransport` that can disable redirects. +- `StoreCollectionClient.search`, with `StoreSearchOptions` and `StoreSearchResult`, for a Store search. It sends one request and completes with the Actors and the limit the API applied. +- `StoreFilterOptions`, the filters that `StoreListOptions` and `StoreSearchOptions` share. - `APIFY_AI` run origin. ### Changed - **Breaking:** `ActorStoreListItem.getStats()` returns `StoreActorStats` instead of `ActorStats`. The Store no longer returns `totalBuilds`, `totalMetamorphs`, and `lastRunStartedAt`. -- **Breaking:** `StoreCollectionClient.iterate` sends one request when `search` is set, since the Store returns a single page of at most 100 Actors for a search and ignores `offset`. `chunkSize` and `offset` have no effect for a search. +- **Breaking:** `StoreListOptions` no longer has `search`. Use `StoreCollectionClient.search`, since the Store answers a search with one page of at most 100 Actors and ignores `offset`, so iterating it never ended. - `StoreListOptions.category` takes comma-separated category IDs. - `LogClient.stream` and `DatasetClient.streamItems` retry the request like any other, until the response headers arrive. - `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. - Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). - `ActorClient.validateInput` and `RunClient.metamorph` throw `IllegalArgumentException` for an `InputStream` input, instead of serializing it to JSON. -### Deprecated +### Removed -- `StoreListOptions.sortBy`: the API ignores it. +- **Breaking:** `StoreListOptions.sortBy`: the API ignores it. ## [0.14.1] - 2026-11-20 diff --git a/docs/README.md b/docs/README.md index f3e08ed..c92c5f2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -54,7 +54,7 @@ option types, so import each resource you use from its own package: | `com.apify.client.schedule` | `Schedule`, `ScheduleNotifications`, `ScheduleClient`, `ScheduleCollectionClient` | | `com.apify.client.webhook` | `Webhook`, `WebhookStats`, `WebhookLastDispatch`, `WebhookClient`, `WebhookCollectionClient`, `WebhookDispatchCollectionClient`, `NestedWebhookCollectionClient`, `WebhookDispatch`, `WebhookDispatchClient`, `WebhookDispatchCall`, `WebhookDispatchWebhookInfo`, `WebhookDispatchEventData` | | `com.apify.client.user` | `User`, `UserClient`, `UserProfile`, `UserProxy`, `UserPlan`, `ProxyGroup` | -| `com.apify.client.store` | `ActorStoreListItem`, `StoreActorStats`, `StoreCollectionClient`, `StoreListOptions`, `PricingInfo` | +| `com.apify.client.store` | `ActorStoreListItem`, `StoreActorStats`, `StoreCollectionClient`, `StoreFilterOptions`, `StoreListOptions`, `StoreSearchOptions`, `StoreSearchResult`, `PricingInfo` | | `com.apify.client.log` | `LogClient`, `LogOptions`, `StreamedLog`, `StreamedLogOptions` | For example, the [top-level README's dataset snippet](../README.md#quick-start) needs diff --git a/docs/misc.md b/docs/misc.md index 518d54f..76dfbe5 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -2,28 +2,40 @@ ## Apify Store: `client.store()` -Browse public Actors in the Apify Store. `client.store()` returns a `StoreCollectionClient`. +Browse and search public Actors in the Apify Store. `client.store()` returns a +`StoreCollectionClient`. The API serves the Store in two ways, and the client has a method for each: +`list` and `iterate` browse the whole Store in Store order, and `search` returns the Actors that +match a query best. | Method | Description | |---|---| | `list(StoreListOptions)` | A page of Store Actors. Completes with `PaginationList`. | -| `iterate(StoreListOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all matches, fetching pages on demand. The options' `limit` caps the total number of rows read, which are the Actors yielded unless the API drops entries after counting them (`null`/unset or non-positive = all); `chunkSize` is the per-request page size (`null` = server default). With `search` there is a single page instead: see below. | +| `iterate(StoreListOptions, Long chunkSize)` | A lazy `Flow.Publisher` over all matches, fetching pages on demand. The options' `limit` caps the total number of rows read, which are the Actors yielded unless the API drops entries after counting them (`null`/unset or non-positive = all); `chunkSize` is the per-request page size (`null` = server default). | +| `search(StoreSearchOptions)` | The Actors that match a query best, best match first, as a single page. Completes with `StoreSearchResult`. | `StoreListOptions` fields: `offset` (number of Actors to skip), `limit` (maximum number of Actors to -return; the API default and maximum is 1000, or 100 with `search`), `search` (search query), -`sortBy` (deprecated: the API ignores it, and orders the results by relevance with `search` and by -Store position otherwise, so sort them on the client), `category` (filter by one or more category IDs -such as `AI_AND_ML`, comma-separated and case-insensitive; an Actor must match all of them, and an -unknown category fails with a `400` error), `username` (filter Actors by owner username), -`pricingModel` (filter by pricing model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`; the -deprecated rental model `FLAT_PRICE_PER_MONTH` is no longer listed), -`includeUnrunnableActors` (include Actors the current user cannot run), `allowsAgenticUsers` (only -Actors that allow agentic users), `responseFormat` (the response shape: `full` or `agent`). - -A `search` returns the Actors ranked by relevance as a single page of at most 100: the API ignores -`offset` and has no second page. `iterate` therefore sends one request for a search, when you call -`iterate` rather than on first demand, with the options' `limit` as its size. `chunkSize` and -`offset` have no effect. Narrow a search with `category`, `username`, or `pricingModel`. +return; the API default and maximum is 1000), and the filters below. The API has no option to change +the Store order. + +`StoreSearchOptions` takes the query in its constructor, which rejects a `null` or empty query, +since the API answers an empty query with the Store listing. Its fields are `limit` (maximum number +of Actors to return, a positive number; the API default and maximum is 100, and it reduces a larger +value to 100) and the filters below. There is no `offset`: the API ignores it for a search. + +Filters of both options types: `category` (filter by one or more category IDs such as `AI_AND_ML`, +comma-separated and case-insensitive; an Actor must match all of them, and an unknown category fails +with a `400` error), `username` (filter Actors by owner username), `pricingModel` (filter by pricing +model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`; the deprecated rental model +`FLAT_PRICE_PER_MONTH` is no longer listed), `includeUnrunnableActors` (include Actors the current +user cannot run), `allowsAgenticUsers` (only Actors that allow agentic users), `responseFormat` (the +response shape: `full` or `agent`), `includeInputSchema` (add each Actor's compact `inputSchema`; +the API then defaults `limit` to, and caps it at, 10). + +A search returns a single page of at most 100 Actors ranked by relevance. There is no next page, and +the API does not report how many Actors match. `StoreSearchResult` therefore has only `getItems()` +and `getLimit()`, the limit the API applied. When `getItems().size()` equals it, more Actors may +match than were returned, so narrow the search with a more specific query or with `category`, +`username`, or `pricingModel`. To go through the whole Store, use `list` or `iterate`. ```java // Publishers.collect() drains the whole publisher; fine here since `limit` already caps it. @@ -35,8 +47,9 @@ List items = items.forEach(item -> System.out.println(item.getUsername() + "/" + item.getName())); // A search is one page of at most 100 Actors. -List found = - Publishers.collect(client.store().iterate(new StoreListOptions().search("crawler"), null)).join(); +StoreSearchResult found = + client.store().search(new StoreSearchOptions("crawler").limit(10L)).join(); +found.getItems().forEach(item -> System.out.println(item.getUsername() + "/" + item.getName())); ``` `ActorStoreListItem` fields: `getId()`, `getName()`, `getUsername()`, `getTitle()`, diff --git a/src/main/java/com/apify/client/store/StoreCollectionClient.java b/src/main/java/com/apify/client/store/StoreCollectionClient.java index 62eb77f..48e2252 100644 --- a/src/main/java/com/apify/client/store/StoreCollectionClient.java +++ b/src/main/java/com/apify/client/store/StoreCollectionClient.java @@ -1,17 +1,18 @@ package com.apify.client.store; -import com.apify.client.PaginationList; import com.apify.client.internal.AbstractCollectionClient; import com.apify.client.internal.ApiPaths; import com.apify.client.internal.HttpClientCore; -import com.apify.client.internal.ListPublisher; import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Flow; -/** A client for browsing the Apify Store ({@code GET /v2/store}). */ +/** + * A client for browsing and searching the Apify Store ({@code GET /v2/store}). The API serves it in + * two ways, and this client has one method for each: {@code list} and {@code iterate} browse the + * whole Store in Store order, page by page, and {@link #search(StoreSearchOptions)} returns the + * Actors that match a query best, as a single page. + */ public final class StoreCollectionClient extends AbstractCollectionClient { @@ -23,26 +24,22 @@ public StoreCollectionClient(HttpClientCore http, String baseUrl) { } /** - * As {@link AbstractCollectionClient#iterate(com.apify.client.internal.ListOptionsLike, Long)}, - * except that a search returns a single page: the API ignores {@code offset} and has no second - * page, so paging would read the same page forever. The request is then sent once, when {@code - * iterate} is called, with the options' {@code limit} (when positive) as its page size and cap; - * {@code chunkSize} and {@code offset} have no effect. + * Searches the Apify Store and completes with 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 {@link StoreSearchResult#getLimit()} can therefore be cut off: + * narrow it down with a more specific query or with the {@code category}, {@code username}, and + * {@code pricingModel} options. To go through the whole Store, use {@code list} or {@code + * iterate}. + * + * @param options the query, the filters, and the number of results */ - @Override - public Flow.Publisher iterate(StoreListOptions options, Long chunkSize) { - StoreListOptions opts = options != null ? options : defaultOptions(); - if (!opts.hasSearch()) { - return super.iterate(opts, chunkSize); - } - Long limit = opts.limitValue(); + public CompletableFuture search(StoreSearchOptions options) { QueryParams params = new QueryParams(); - opts.applyFilters(params); - if (limit != null && limit > 0) { - params.addLong("limit", limit); - } - CompletableFuture> items = - listWithParams(params).thenApply(PaginationList::getItems); - return new ListPublisher<>(items); + options.apply(params); + return listWithParams(params) + .thenApply(page -> new StoreSearchResult(page.getItems(), page.getLimit())); } } diff --git a/src/main/java/com/apify/client/store/StoreFilterOptions.java b/src/main/java/com/apify/client/store/StoreFilterOptions.java new file mode 100644 index 0000000..9bc363e --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreFilterOptions.java @@ -0,0 +1,88 @@ +package com.apify.client.store; + +import com.apify.client.internal.QueryParams; + +/** + * Filters shared by {@link StoreListOptions} (browsing the Store) and {@link StoreSearchOptions} + * (searching it). + * + * @param the concrete options type, returned by every setter so calls can be chained + */ +public abstract class StoreFilterOptions> { + private String category; + private String username; + private String pricingModel; + private Boolean includeUnrunnableActors; + private Boolean allowsAgenticUsers; + private String responseFormat; + private Boolean includeInputSchema; + + /** The concrete options object, for chaining. */ + abstract T self(); + + /** + * Filter Actors by category. Accepts one or more category IDs (e.g. {@code "AI_AND_ML"}), + * separated by commas and case-insensitive; an Actor must match all of them. Legacy keys such as + * {@code social_media} are still accepted, and an unknown category fails with a {@code 400} + * error. + */ + public T category(String category) { + this.category = category; + return self(); + } + + /** Filter Actors by owner username. */ + public T username(String username) { + this.username = username; + return self(); + } + + /** + * Filter Actors by pricing model ({@code FREE}, {@code PRICE_PER_DATASET_ITEM}, {@code + * PAY_PER_EVENT}). The rental model ({@code FLAT_PRICE_PER_MONTH}) is deprecated and no longer + * supported, so it is no longer documented as a filter value and matches no Actors. + */ + public T pricingModel(String pricingModel) { + this.pricingModel = pricingModel; + return self(); + } + + /** Include Actors the current user cannot run. */ + public T includeUnrunnableActors(Boolean includeUnrunnableActors) { + this.includeUnrunnableActors = includeUnrunnableActors; + return self(); + } + + /** Filter to Actors that allow agentic users. */ + public T allowsAgenticUsers(Boolean allowsAgenticUsers) { + this.allowsAgenticUsers = allowsAgenticUsers; + return self(); + } + + /** The response format ({@code full}, {@code agent}). */ + public T responseFormat(String responseFormat) { + this.responseFormat = responseFormat; + return self(); + } + + /** + * Include a compact {@code inputSchema} (property types and required properties only) of each + * Actor's default build in the results, available through {@code ActorStoreListItem#getExtra()}. + * With this flag the API defaults {@code limit} to, and caps it at, {@code 10}. + */ + public T includeInputSchema(Boolean includeInputSchema) { + this.includeInputSchema = includeInputSchema; + return self(); + } + + /** Applies every filter as a query parameter. */ + public void applyFilters(QueryParams q) { + q.addString("category", category) + .addString("username", username) + .addString("pricingModel", pricingModel) + .addBool("includeUnrunnableActors", includeUnrunnableActors) + .addBool("allowsAgenticUsers", allowsAgenticUsers) + .addString("responseFormat", responseFormat) + .addBool("includeInputSchema", includeInputSchema); + } +} diff --git a/src/main/java/com/apify/client/store/StoreListOptions.java b/src/main/java/com/apify/client/store/StoreListOptions.java index 02707c8..878f37a 100644 --- a/src/main/java/com/apify/client/store/StoreListOptions.java +++ b/src/main/java/com/apify/client/store/StoreListOptions.java @@ -3,121 +3,37 @@ import com.apify.client.internal.ListOptionsLike; import com.apify.client.internal.QueryParams; -/** Options for listing/iterating the Apify Store ({@code GET /v2/store}). */ -public final class StoreListOptions implements ListOptionsLike { +/** + * Options for listing/iterating the Apify Store ({@code GET /v2/store}). The Actors come in Store + * order, which the API has no option to change. To find Actors by a text query, use {@link + * StoreSearchOptions} with {@link StoreCollectionClient#search(StoreSearchOptions)}. + */ +public final class StoreListOptions extends StoreFilterOptions + implements ListOptionsLike { private Long offset; private Long limit; - private String search; - private String sortBy; - private String category; - private String username; - private String pricingModel; - private Boolean includeUnrunnableActors; - private Boolean allowsAgenticUsers; - private String responseFormat; - private Boolean includeInputSchema; - /** Number of Actors to skip. The API ignores it when {@link #search(String)} is used. */ + @Override + StoreListOptions self() { + return this; + } + + /** Number of Actors to skip. */ public StoreListOptions offset(Long offset) { this.offset = offset; return this; } /** - * Maximum number of Actors to return. The API default and maximum is {@code 1000}; when {@link - * #search(String)} is used, both are {@code 100} and a larger value is reduced to {@code 100}. - * Sent verbatim by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} - * a non-positive/zero {@code limit} means "no cap" (all). + * Maximum number of Actors to return. The API default and maximum is {@code 1000}. Sent verbatim + * by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} a + * non-positive/zero {@code limit} means "no cap" (all). */ public StoreListOptions limit(Long limit) { this.limit = limit; return this; } - /** - * Search query. The API ranks the results by relevance and returns them as a single page of at - * most 100 Actors: {@link #offset(Long)} is ignored and there is no second page. Narrow the - * results with {@link #category(String)}, {@link #username(String)}, or {@link - * #pricingModel(String)}. - */ - public StoreListOptions search(String search) { - this.search = search; - return this; - } - - /** - * Accepted for backward compatibility, but the API ignores it. The results are ordered by - * relevance when {@link #search(String)} is used and by Store position otherwise; sort them on - * the client for a different order. - * - * @deprecated the API ignores the value - */ - @Deprecated - public StoreListOptions sortBy(String sortBy) { - this.sortBy = sortBy; - return this; - } - - /** - * Filter Actors by category. Accepts one or more category IDs (e.g. {@code "AI_AND_ML"}), - * separated by commas and case-insensitive; an Actor must match all of them. Legacy keys such as - * {@code social_media} are still accepted, and an unknown category fails with a {@code 400} - * error. - */ - public StoreListOptions category(String category) { - this.category = category; - return this; - } - - /** Filter Actors by owner username. */ - public StoreListOptions username(String username) { - this.username = username; - return this; - } - - /** - * Filter Actors by pricing model ({@code FREE}, {@code PRICE_PER_DATASET_ITEM}, {@code - * PAY_PER_EVENT}). The rental model ({@code FLAT_PRICE_PER_MONTH}) is deprecated and no longer - * supported, so it is no longer documented as a filter value and matches no Actors. - */ - public StoreListOptions pricingModel(String pricingModel) { - this.pricingModel = pricingModel; - return this; - } - - /** Include Actors the current user cannot run. */ - public StoreListOptions includeUnrunnableActors(Boolean includeUnrunnableActors) { - this.includeUnrunnableActors = includeUnrunnableActors; - return this; - } - - /** Filter to Actors that allow agentic users. */ - public StoreListOptions allowsAgenticUsers(Boolean allowsAgenticUsers) { - this.allowsAgenticUsers = allowsAgenticUsers; - return this; - } - - /** The response format ({@code full}, {@code agent}). */ - public StoreListOptions responseFormat(String responseFormat) { - this.responseFormat = responseFormat; - return this; - } - - /** - * Include a compact {@code inputSchema} (property types and required properties only) of each - * Actor's default build in the results, available through {@code ActorStoreListItem#getExtra()}. - * With this flag the API defaults {@code limit} to, and caps it at, {@code 10}. - */ - public StoreListOptions includeInputSchema(Boolean includeInputSchema) { - this.includeInputSchema = includeInputSchema; - return this; - } - - /** Whether a non-empty search query is set, which makes the API return a single page. */ - boolean hasSearch() { - return search != null && !search.isEmpty(); - } - @Override public Long limitValue() { return limit; @@ -133,20 +49,4 @@ public void apply(QueryParams q) { q.addLong("offset", offset).addLong("limit", limit); applyFilters(q); } - - /** - * Applies every filter except {@code offset}/{@code limit}, which the iterator drives per page. - */ - @Override - public void applyFilters(QueryParams q) { - q.addString("search", search) - .addString("sortBy", sortBy) - .addString("category", category) - .addString("username", username) - .addString("pricingModel", pricingModel) - .addBool("includeUnrunnableActors", includeUnrunnableActors) - .addBool("allowsAgenticUsers", allowsAgenticUsers) - .addString("responseFormat", responseFormat) - .addBool("includeInputSchema", includeInputSchema); - } } diff --git a/src/main/java/com/apify/client/store/StoreSearchOptions.java b/src/main/java/com/apify/client/store/StoreSearchOptions.java new file mode 100644 index 0000000..c4781b9 --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreSearchOptions.java @@ -0,0 +1,53 @@ +package com.apify.client.store; + +import com.apify.client.internal.QueryParams; + +/** + * Options for searching the Apify Store ({@code GET /v2/store} with a {@code search} query). The + * API ranks the results by relevance and returns them as a single page of at most 100 Actors, so + * there is no {@code offset}. Narrow a search with {@link #category(String)}, {@link + * #username(String)}, or {@link #pricingModel(String)}. + */ +public final class StoreSearchOptions extends StoreFilterOptions { + private final String search; + private Long limit; + + /** + * Creates the options of a search. + * + * @param search text to search for + * @throws IllegalArgumentException if {@code search} is {@code null} or empty, since the API + * answers an empty query with the Store listing + */ + public StoreSearchOptions(String search) { + if (search == null || search.isEmpty()) { + throw new IllegalArgumentException("search must not be empty"); + } + this.search = search; + } + + @Override + StoreSearchOptions self() { + return this; + } + + /** + * Maximum number of Actors to return. The API returns at most {@code 100} Actors for a search, + * which is also the default, and reduces a larger value to {@code 100}. + * + * @throws IllegalArgumentException if {@code limit} is not positive + */ + public StoreSearchOptions limit(Long limit) { + if (limit != null && limit <= 0) { + throw new IllegalArgumentException("limit must be positive"); + } + this.limit = limit; + return this; + } + + /** Applies the query, the limit, and every filter as query parameters. */ + public void apply(QueryParams q) { + q.addString("search", search).addLong("limit", limit); + applyFilters(q); + } +} diff --git a/src/main/java/com/apify/client/store/StoreSearchResult.java b/src/main/java/com/apify/client/store/StoreSearchResult.java new file mode 100644 index 0000000..9e29d8d --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreSearchResult.java @@ -0,0 +1,35 @@ +package com.apify.client.store; + +import java.util.List; + +/** + * The single page of results that {@link StoreCollectionClient#search(StoreSearchOptions)} + * completes with. + * + *

The API fills the pagination fields of a search response with the number of Actors returned + * and a zero offset, whatever the query matches, so they would read as the number of matches and a + * position to continue from. They are left out. + */ +public final class StoreSearchResult { + private final List items; + private final long limit; + + StoreSearchResult(List items, long limit) { + this.items = List.copyOf(items); + this.limit = limit; + } + + /** The Actors matching the query, best match first. */ + public List getItems() { + return items; + } + + /** + * The maximum number of Actors the API allowed in this result: the requested {@code limit}, or + * the API's maximum when no limit or a larger one was requested. With {@code getItems().size()} + * equal to it, more Actors may match the query than were returned. + */ + public long getLimit() { + return limit; + } +} diff --git a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java index 75de210..1e8af1f 100644 --- a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java +++ b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java @@ -32,6 +32,8 @@ import com.apify.client.schedule.ScheduleInvoked; import com.apify.client.store.ActorStoreListItem; import com.apify.client.store.StoreListOptions; +import com.apify.client.store.StoreSearchOptions; +import com.apify.client.store.StoreSearchResult; import com.apify.client.webhook.NestedWebhookCollectionClient; import com.apify.client.webhook.Webhook; import java.nio.charset.StandardCharsets; @@ -528,35 +530,56 @@ void storeIterateWalksMultiplePages() { } @Test - void storeSearchIterationSendsASingleRequestWithoutAnOffset() { - // The Store ignores `offset` for a search and has no second page, so paging would read the same - // page forever: the iteration must send one request and then complete. + void storeSearchSendsOneRequestWithTheQueryTheLimitAndTheFilters() { MockTransport backend = MockTransport.ofConstant( 200, "{\"data\":{\"items\":[{\"id\":\"a\"},{\"id\":\"b\"}],\"total\":2,\"offset\":0," - + "\"limit\":100,\"count\":2}}"); - StoreListOptions options = new StoreListOptions().search("crawler").offset(5L); - List items = - Publishers.collect(client(backend).store().iterate(options, 1L)).join(); - assertEquals(2, items.size()); + + "\"limit\":10,\"count\":2}}"); + StoreSearchResult result = + client(backend) + .store() + .search(new StoreSearchOptions("crawler").limit(10L).username("apify")) + .join(); + assertEquals(2, result.getItems().size()); + assertEquals(10, result.getLimit()); assertEquals(1, backend.calls, "a search is one page"); assertTrue(backend.lastUrl.contains("search=crawler"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("limit=10"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("username=apify"), backend.lastUrl); assertFalse(backend.lastUrl.contains("offset="), backend.lastUrl); - assertFalse(backend.lastUrl.contains("limit="), backend.lastUrl); } @Test - void storeSearchIterationSendsTheLimitAsThePageSize() { + void storeSearchSendsOnlyTheQueryByDefault() { MockTransport backend = MockTransport.ofConstant( - 200, - "{\"data\":{\"items\":[{\"id\":\"a\"}],\"total\":1,\"offset\":0,\"limit\":10,\"count\":1}}"); - Publishers.collect( - client(backend).store().iterate(new StoreListOptions().search("x").limit(10L), null)) - .join(); - assertEquals(1, backend.calls); - assertTrue(backend.lastUrl.contains("limit=10"), backend.lastUrl); + 200, "{\"data\":{\"items\":[],\"total\":0,\"offset\":0,\"limit\":100,\"count\":0}}"); + StoreSearchResult result = + client(backend).store().search(new StoreSearchOptions("crawler")).join(); + assertTrue(result.getItems().isEmpty()); + assertEquals(100, result.getLimit(), "the limit is the one the API applied"); + assertTrue(backend.lastUrl.endsWith("/v2/store?search=crawler"), backend.lastUrl); + } + + @Test + void storeSearchOptionsRejectAnEmptyQueryAndANonPositiveLimit() { + assertThrows(IllegalArgumentException.class, () -> new StoreSearchOptions(null)); + assertThrows(IllegalArgumentException.class, () -> new StoreSearchOptions("")); + StoreSearchOptions options = new StoreSearchOptions("crawler"); + assertThrows(IllegalArgumentException.class, () -> options.limit(0L)); + assertThrows(IllegalArgumentException.class, () -> options.limit(-1L)); + } + + @Test + void storeListNeverSendsASearchQuery() { + MockTransport backend = + MockTransport.ofConstant( + 200, "{\"data\":{\"items\":[],\"total\":0,\"offset\":0,\"limit\":1000,\"count\":0}}"); + client(backend).store().list(new StoreListOptions().username("apify").offset(5L)).join(); + assertTrue(backend.lastUrl.contains("username=apify"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("offset=5"), backend.lastUrl); + assertFalse(backend.lastUrl.contains("search="), backend.lastUrl); } @Test diff --git a/src/test/java/com/apify/client/integration/StoreIntegrationTest.java b/src/test/java/com/apify/client/integration/StoreIntegrationTest.java index 49d4d48..53650de 100644 --- a/src/test/java/com/apify/client/integration/StoreIntegrationTest.java +++ b/src/test/java/com/apify/client/integration/StoreIntegrationTest.java @@ -1,12 +1,13 @@ package com.apify.client.integration; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.apify.client.ApifyClient; -import com.apify.client.Publishers; import com.apify.client.store.ActorStoreListItem; import com.apify.client.store.StoreListOptions; +import com.apify.client.store.StoreSearchOptions; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Flow; import java.util.concurrent.atomic.AtomicInteger; @@ -21,16 +22,6 @@ void listStore() { assertTrue(page.getItems().size() <= 5); } - @Test - void listStoreAcceptsTheDeprecatedSortBy() { - ApifyClient client = requireClient(); - // The API accepts `sortBy` for compatibility but ignores it, so the order is not asserted. - @SuppressWarnings("deprecation") - StoreListOptions options = new StoreListOptions().limit(5L).sortBy("popularity"); - var page = client.store().list(options).join(); - assertFalse(page.getItems().isEmpty()); - } - @Test void listStoreItemsCarryTheStoreStats() { ApifyClient client = requireClient(); @@ -43,14 +34,45 @@ void listStoreItemsCarryTheStoreStats() { } @Test - void searchReturnsASinglePageAndIterationCompletes() { + void searchReturnsTheBestMatchesAsOnePage() { + ApifyClient client = requireClient(); + var result = client.store().search(new StoreSearchOptions("web scraper").limit(5L)).join(); + // The public Store holds thousands of scrapers, so the page is always full. + assertEquals(5, result.getItems().size()); + assertEquals(5, result.getLimit()); + assertTrue( + result.getItems().stream() + .allMatch(item -> item.getId() != null && item.getUsername() != null)); + } + + @Test + void searchReturnsAtMostOneHundredActors() { + ApifyClient client = requireClient(); + var byDefault = client.store().search(new StoreSearchOptions("scraper")).join(); + var large = client.store().search(new StoreSearchOptions("scraper").limit(1000L)).join(); + assertEquals(100, byDefault.getLimit()); + assertEquals(100, byDefault.getItems().size()); + assertEquals(100, large.getLimit()); + assertEquals(100, large.getItems().size()); + } + + @Test + void searchForAQueryThatMatchesNothingReturnsNoActors() { + ApifyClient client = requireClient(); + var result = client.store().search(new StoreSearchOptions("qzxjvkwpqzxjvkwp")).join(); + assertTrue(result.getItems().isEmpty()); + } + + @Test + void searchFiltersByUsername() { ApifyClient client = requireClient(); - // A search is one page of at most 100 Actors, so iterating it without a limit must complete. - var items = - Publishers.collect(client.store().iterate(new StoreListOptions().search("crawler"), null)) + var result = + client + .store() + .search(new StoreSearchOptions("scraper").limit(10L).username("apify")) .join(); - assertFalse(items.isEmpty()); - assertTrue(items.size() <= 100, "a search returns at most 100 Actors, got " + items.size()); + assertFalse(result.getItems().isEmpty()); + assertTrue(result.getItems().stream().allMatch(item -> "apify".equals(item.getUsername()))); } @Test From 5742fe482cb343504854fea8d8e69f7217cbe50c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 10:17:28 +0000 Subject: [PATCH 08/19] feat!: port the streamed log resume, sync the Store with the 2026-12-02 spec, and fix review findings StreamedLog takes since instead of fromStart, reopens a log stream that broke off, and exposes getLastRedirectedAt. The agentic payment filter and field are removed. The spec version is 2026-12-02. Docs and Javadoc follow the spec for the Store filters, the build OpenAPI definition, and public storage URLs. --- CHANGELOG.md | 21 +- README.md | 2 +- docs/builds.md | 2 +- docs/misc.md | 19 +- docs/runs.md | 27 ++- docs/storages.md | 4 + .../java/com/apify/client/ApifyClient.java | 2 +- src/main/java/com/apify/client/Version.java | 2 +- .../com/apify/client/build/BuildClient.java | 4 + .../apify/client/dataset/DatasetClient.java | 4 + .../client/keyvalue/KeyValueStoreClient.java | 6 +- .../com/apify/client/log/StreamedLog.java | 205 +++++++++++++++--- .../apify/client/log/StreamedLogOptions.java | 21 +- .../java/com/apify/client/run/RunClient.java | 16 +- .../client/store/ActorStoreListItem.java | 8 +- .../client/store/StoreCollectionClient.java | 13 +- .../client/store/StoreFilterOptions.java | 29 +-- .../apify/client/store/StoreListOptions.java | 7 +- .../client/store/StoreSearchOptions.java | 13 +- .../client/ClientBehaviourRegressionTest.java | 4 +- .../com/apify/client/StreamedLogTest.java | 171 ++++++++++++++- 21 files changed, 471 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 684c9f7..67c897d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,32 +5,41 @@ All notable changes to the Apify Java client are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [0.15.0] - 2026-11-27 +## [0.15.0] - 2026-12-03 ### Added +- `StoreCollectionClient.search`, with `StoreSearchOptions` and `StoreSearchResult`, for a Store search. It sends one request and completes with the Actors and the limit the API applied. +- `StoreFilterOptions`, the filters that `StoreListOptions` and `StoreSearchOptions` share. +- `StreamedLogOptions.since` and `StreamedLog.getLastRedirectedAt`, to redirect only the log lines from a given time and to continue a redirection later. - `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating`, and `actorReviewCount`. -- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isWhiteListedForAgenticPayments`, `isVerified`, and `badge`. +- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `isVerified`, and `badge`. - `KeyValueStoreClient.setRecord` overloads that take an `InputStream`. The stream is sent without being held in memory, and the upload is not retried or compressed. Like a request to an Actor's server, it needs an `HttpTransport` that can disable redirects. - `KeyValueStoreClient.getRecordStream` and `KeyValueStoreRecordStream`, which read a record as an `InputStream`. The request is retried like any other. - `InputStream` as the input of `ActorClient.start`, `ActorClient.call`, `TaskClient.start`, and `TaskClient.call`, and as the body of `ActorServerClient.request` and `requestStream`. A stream is sent once, with no retry, and needs an `HttpTransport` that can disable redirects. -- `StoreCollectionClient.search`, with `StoreSearchOptions` and `StoreSearchResult`, for a Store search. It sends one request and completes with the Actors and the limit the API applied. -- `StoreFilterOptions`, the filters that `StoreListOptions` and `StoreSearchOptions` share. - `APIFY_AI` run origin. ### Changed +- Updated to Apify OpenAPI specification `v2-2026-12-02T102104Z`. - **Breaking:** `ActorStoreListItem.getStats()` returns `StoreActorStats` instead of `ActorStats`. The Store no longer returns `totalBuilds`, `totalMetamorphs`, and `lastRunStartedAt`. -- **Breaking:** `StoreListOptions` no longer has `search`. Use `StoreCollectionClient.search`, since the Store answers a search with one page of at most 100 Actors and ignores `offset`, so iterating it never ended. +- **Breaking:** the `StoreListOptions` filter setters (`category`, `username`, `pricingModel`, `includeUnrunnableActors`, `responseFormat`, `includeInputSchema`) now come from `StoreFilterOptions`. Code compiled against 0.14.x must be recompiled. +- **Breaking:** `StreamedLog` takes `since` instead of `fromStart`: `new StreamedLog(logClient, destination, since)`. +- A `StreamedLog` reopens a log stream that is cut off while the run is still going and continues after the last redirected message. - `StoreListOptions.category` takes comma-separated category IDs. - `LogClient.stream` and `DatasetClient.streamItems` retry the request like any other, until the response headers arrive. - `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. - Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). +- Documented that the build OpenAPI definition needs an API token with access to the build, unless the Actor is public or the build's owner allows anyone with the ID to read. +- Documented that a public storage URL grants read access to the whole storage, and that its options do not limit it. - `ActorClient.validateInput` and `RunClient.metamorph` throw `IllegalArgumentException` for an `InputStream` input, instead of serializing it to JSON. ### Removed -- **Breaking:** `StoreListOptions.sortBy`: the API ignores it. +- **Breaking:** `StoreListOptions.search`. Use `StoreCollectionClient.search`: the Store answers a search with one page of at most 100 Actors and ignores `offset`. +- **Breaking:** `StoreListOptions.sortBy`, which the API ignores. +- **Breaking:** `StreamedLogOptions.fromStart`. Use `StreamedLogOptions.since`. +- **Breaking:** `StoreListOptions.allowsAgenticUsers` and `ActorStoreListItem.getIsWhiteListedForAgenticPayments`, which the API no longer has. ## [0.14.1] - 2026-11-20 diff --git a/README.md b/README.md index ecc53e6..b10aa2f 100644 --- a/README.md +++ b/README.md @@ -441,7 +441,7 @@ constants: - `Version.CLIENT_VERSION`: the semantic version of this client (`0.15.0`). - `Version.API_SPEC_VERSION`: the version of the [Apify OpenAPI specification](https://docs.apify.com/api/openapi.json) (its `info.version` field) that this client's endpoints, parameters, and models were last generated - and checked against (`v2-2026-11-18T151559Z`). It is a snapshot, not a live compatibility + and checked against (`v2-2026-12-02T102104Z`). It is a snapshot, not a live compatibility guarantee: the client keeps working against newer, backward-compatible spec revisions, but a feature added to the API after this snapshot has no corresponding method here yet. diff --git a/docs/builds.md b/docs/builds.md index 8da32df..609e219 100644 --- a/docs/builds.md +++ b/docs/builds.md @@ -19,7 +19,7 @@ builds) and a single build with `client.build(id)`. | `abort()` | Abort the build. Completes with `Build`. | | `delete()` | Delete the build. | | `waitForFinish(Long waitSecs)` | Poll until the build finishes (`null` waits indefinitely); see [the run equivalent](runs.md#runclient) for its 404 handling. Completes with `Build`. | -| `getOpenApiDefinition()` | The build's OpenAPI definition. Completes with `Optional`. | +| `getOpenApiDefinition()` | The build's OpenAPI definition. Completes with `Optional`. It needs an API token with access to the build, unless the Actor is public or the build's owner has general resource access set to "Anyone with ID can read"; otherwise the API answers `401` or `403`. | | `log()` | A `LogClient` for the build's log. | `Build` fields: `getId()`, `getActId()`, `getUserId()`, `getStatus()`, `getStartedAt()`, diff --git a/docs/misc.md b/docs/misc.md index 76dfbe5..eca32a2 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -2,7 +2,7 @@ ## Apify Store: `client.store()` -Browse and search public Actors in the Apify Store. `client.store()` returns a +Browse and search public Actors in Apify Store. `client.store()` returns a `StoreCollectionClient`. The API serves the Store in two ways, and the client has a method for each: `list` and `iterate` browse the whole Store in Store order, and `search` returns the Actors that match a query best. @@ -20,16 +20,19 @@ the Store order. `StoreSearchOptions` takes the query in its constructor, which rejects a `null` or empty query, since the API answers an empty query with the Store listing. Its fields are `limit` (maximum number of Actors to return, a positive number; the API default and maximum is 100, and it reduces a larger -value to 100) and the filters below. There is no `offset`: the API ignores it for a search. +value to 100, except with `includeInputSchema`: see below) and the filters below. There is no +`offset`: the API ignores it for a search. Filters of both options types: `category` (filter by one or more category IDs such as `AI_AND_ML`, comma-separated and case-insensitive; an Actor must match all of them, and an unknown category fails with a `400` error), `username` (filter Actors by owner username), `pricingModel` (filter by pricing -model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`; the deprecated rental model -`FLAT_PRICE_PER_MONTH` is no longer listed), `includeUnrunnableActors` (include Actors the current -user cannot run), `allowsAgenticUsers` (only Actors that allow agentic users), `responseFormat` (the -response shape: `full` or `agent`), `includeInputSchema` (add each Actor's compact `inputSchema`; -the API then defaults `limit` to, and caps it at, 10). +model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`), `includeUnrunnableActors` (by default, +the API leaves out Actors that are not safe to run automatically, such as Actors of developers who +have not passed identity verification; `true` includes them), `responseFormat` (the response shape: +`full`, the default, or `agent`, a reduced field set for LLM consumers with `id`, `title`, `name`, +`username`, `description`, `notice`, `badge`, `categories`, and minimal `stats`, so the other +getters of `ActorStoreListItem` return `null`), `includeInputSchema` (add each Actor's compact +`inputSchema`; the API then defaults `limit` to 10 and rejects a larger value with a `400` error). A search returns a single page of at most 100 Actors ranked by relevance. There is no next page, and the API does not report how many Actors match. `StoreSearchResult` therefore has only `getItems()` @@ -57,7 +60,7 @@ found.getItems().forEach(item -> System.out.println(item.getUsername() + "/" + i `getNotice()`, `getStats()` (`StoreActorStats`: `getTotalUsers()`, `getTotalRuns()`, `getTotalUsers7Days()`, `getTotalUsers30Days()`, `getTotalUsers90Days()`, `getActorReviewRating()`, `getActorReviewCount()`), `getCurrentPricingInfo()` (`PricingInfo`: `getPricingModel()`), -`getIsWhiteListedForAgenticPayments()`, `getIsVerified()` (whether the developer has a verified +`getIsVerified()` (whether the developer has a verified identity), `getBadge()`, `getPictureUrl()`, `getUserPictureUrl()`, `getUrl()`, `getReadmeSummary()`. Any field not covered by a typed getter is still available via the inherited `getExtra()` (see diff --git a/docs/runs.md b/docs/runs.md index 1be1d08..dc78750 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -73,8 +73,29 @@ Actor name and run id (looked up automatically). `StreamedLogOptions` customizes - `toLog(Consumer)`: send each complete message to your own consumer instead of the default logger. - `prefix(String)`: override the auto-built prefix used by the default logger. -- `fromStart(boolean)`: when `false`, skip log lines produced before redirection started - (default `true`). +- `since(Instant)`: redirect only the log lines logged at that time or later (default: the whole + log). This can be useful for long-running Actors, such as Server Actors. + +If the log stream is cut off while the run is still going, for example because the run has logged +nothing for several minutes, `StreamedLog` reopens it and continues after the last redirected +message. The API cannot continue a log stream from a given point, so the reopened stream replays +the whole log, and the messages already redirected are skipped. `StreamedLog.getLastRedirectedAt()` +returns the timestamp of the last redirected message (empty before the first one). To continue a +redirection in another process, for example after the Actor that redirects the log reboots, save it +and pass a later time to `since`: + +```java +RunClient runClient = client.run("RUN_ID"); +Instant lastRedirectedAt; +try (StreamedLog streamedLog = runClient.getStreamedLog().join()) { + streamedLog.start().join(); + runClient.waitForFinish(120L).join(); + lastRedirectedAt = streamedLog.getLastRedirectedAt().orElse(Instant.EPOCH); +} +// Later, for example in another process, continue after that message. +StreamedLog resumed = + runClient.getStreamedLog(new StreamedLogOptions().since(lastRedirectedAt.plusMillis(1))).join(); +``` A run that has not logged anything yet (e.g. still queued for resources, see [`waitForResources`](actors.md#actorclient)) serves its log as a stream that ends at once; @@ -97,7 +118,7 @@ waiting, and the reader ends once the consumer returns. `start()` throws until a RunClient runClient = client.run("RUN_ID"); List collected = new ArrayList<>(); try (StreamedLog streamedLog = - runClient.getStreamedLog(new StreamedLogOptions().toLog(collected::add).fromStart(true)).join()) { + runClient.getStreamedLog(new StreamedLogOptions().toLog(collected::add)).join()) { streamedLog.start().join(); runClient.waitForFinish(120L).join(); } diff --git a/docs/storages.md b/docs/storages.md index b56fa1a..5fc8e3d 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -115,6 +115,10 @@ request is sent. The expiry counts from the moment the URL is signed, after the optional `format` sets the serialization the URL serves items in (default `json` when omitted/`null`). +A public URL grants read access to the whole dataset (or, for `createKeysPublicUrl`, the full key +list) until it expires. The signature covers only the storage ID and the expiry: the options only +set the default shape of the response, and anyone holding the URL can change or drop them. + > **Public-URL limitation.** The public-URL builders > (`createItemsPublicUrl`, and the key-value-store `getRecordPublicUrl` / `createKeysPublicUrl`) > build the URL from the client's own resource path plus the signature. When called on a *last-run diff --git a/src/main/java/com/apify/client/ApifyClient.java b/src/main/java/com/apify/client/ApifyClient.java index 5c4eb1c..8efba35 100644 --- a/src/main/java/com/apify/client/ApifyClient.java +++ b/src/main/java/com/apify/client/ApifyClient.java @@ -244,7 +244,7 @@ public WebhookDispatchClient webhookDispatch(String id) { // ----- Misc accessors ------------------------------------------------------ - /** A client for browsing the Apify Store. */ + /** A client for browsing Apify Store. */ public StoreCollectionClient store() { return new StoreCollectionClient(http, baseUrl); } diff --git a/src/main/java/com/apify/client/Version.java b/src/main/java/com/apify/client/Version.java index 3bef73f..0d495b7 100644 --- a/src/main/java/com/apify/client/Version.java +++ b/src/main/java/com/apify/client/Version.java @@ -19,7 +19,7 @@ public final class Version { * The version of the Apify OpenAPI specification this client was generated and verified against. * Corresponds to the {@code info.version} field of the Apify OpenAPI document. */ - public static final String API_SPEC_VERSION = "v2-2026-11-18T151559Z"; + public static final String API_SPEC_VERSION = "v2-2026-12-02T102104Z"; private Version() {} } diff --git a/src/main/java/com/apify/client/build/BuildClient.java b/src/main/java/com/apify/client/build/BuildClient.java index 4004234..ea8ea6f 100644 --- a/src/main/java/com/apify/client/build/BuildClient.java +++ b/src/main/java/com/apify/client/build/BuildClient.java @@ -60,6 +60,10 @@ public CompletableFuture waitForFinish(Long waitSecs) { /** * Returns the OpenAPI definition generated for the build, or empty if it is not available. The * result is the raw OpenAPI document. + * + *

The request needs an API token with access to the build, unless the Actor is public or the + * build's owner has general resource access set to "Anyone with ID can read". Otherwise the API + * answers {@code 401} or {@code 403}, and the future completes exceptionally. */ public CompletableFuture> getOpenApiDefinition() { return ctx.getRaw("openapi.json", new QueryParams(), Timeout.MEDIUM) diff --git a/src/main/java/com/apify/client/dataset/DatasetClient.java b/src/main/java/com/apify/client/dataset/DatasetClient.java index a8b89d0..910a879 100644 --- a/src/main/java/com/apify/client/dataset/DatasetClient.java +++ b/src/main/java/com/apify/client/dataset/DatasetClient.java @@ -323,6 +323,10 @@ public CompletableFuture getStatistics() { * non-expiring); it must be positive and at most 4611686018427387. The URL is built from the * configured public base URL. * + *

The URL grants read access to the whole dataset until it expires. The signature covers only + * the dataset, not {@code options}: they set the default shape of the response, and anyone + * holding the URL can change or drop them. + * * @throws IllegalArgumentException before any request is sent, if {@code expiresInSecs} is not * {@code null} and is not positive or exceeds that maximum */ diff --git a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java index 1475a65..cebbd47 100644 --- a/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java +++ b/src/main/java/com/apify/client/keyvalue/KeyValueStoreClient.java @@ -449,7 +449,7 @@ public CompletableFuture getRecordPublicUrl(String key) { * Builds a public URL for listing this store's keys. As with {@link #getRecordPublicUrl}, a * signature is appended for private stores. {@code expiresInSecs} optionally bounds the validity * of a signed URL ({@code null} for non-expiring); it must be positive and at most - * 4611686018427387. + * 4611686018427387. The URL grants read access to the full key list until it expires. * * @throws IllegalArgumentException before any request is sent, if {@code expiresInSecs} is not * {@code null} and is not positive or exceeds that maximum @@ -465,6 +465,10 @@ public CompletableFuture createKeysPublicUrl(Long expiresInSecs) { * already supplied one. {@code expiresInSecs} optionally bounds the validity of a signed URL * ({@code null} for non-expiring); it must be positive and at most 4611686018427387. * + *

The URL grants read access to the full key list until it expires. The signature covers only + * the store, not {@code options}: they set the default shape of the response, and anyone holding + * the URL can change or drop them. + * * @throws IllegalArgumentException before any request is sent, if {@code expiresInSecs} is not * {@code null} and is not positive or exceeds that maximum */ diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 38d6882..d53d445 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -14,6 +14,7 @@ import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; @@ -33,6 +34,13 @@ *

Call {@link #start()} to begin and {@link #stop()} to end. {@link #close()} stops redirection * if it is still running, so the class works in try-with-resources. * + *

When the log stream is cut off while the run is still going, for example because 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 log stream from a given point, so a reopened + * stream replays the whole log and the messages already redirected are skipped. {@link + * #getLastRedirectedAt()} reports the timestamp of the last redirected message, so a redirection + * can also be continued in another process. + * *

Typical use: * *

{@code
@@ -70,6 +78,13 @@ public final class StreamedLog implements AutoCloseable {
   /** Upper bound on the pause between reopens of an empty log stream. */
   private static final long EMPTY_STREAM_MAX_RETRY_MILLIS = 5_000;
 
+  /**
+   * Pause 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, and fails with a read error.
+   * The stream of a finished log ends without one.
+   */
+  private static final long BROKEN_STREAM_REOPEN_MILLIS = 1_000;
+
   /** How long {@link #stop()} and {@link #close()} wait for a message in flight before closing. */
   private static final long STOP_GRACE_MILLIS = 1_000;
 
@@ -77,7 +92,23 @@ public final class StreamedLog implements AutoCloseable {
   private final Consumer destination;
 
   /** Messages older than this are dropped; {@code null} drops nothing. */
-  private final Instant relevancyTimeLimit;
+  private final Instant since;
+
+  /** Timestamp of the last redirected message; {@code null} until one is redirected. */
+  private volatile Instant lastRedirectedAt;
+
+  /**
+   * How many redirected messages carry {@link #lastRedirectedAt}: several can share a millisecond.
+   */
+  private int redirectedAtLastTimestamp;
+
+  /**
+   * A reopened stream replays the messages before this timestamp, and the first {@link
+   * #replaySkipCount} messages at it; {@code null} when there is nothing to skip.
+   */
+  private Instant replayedUntil;
+
+  private int replaySkipCount;
 
   private volatile boolean stopLogging;
 
@@ -100,10 +131,25 @@ public final class StreamedLog implements AutoCloseable {
    */
   private boolean closeRequested;
 
-  public StreamedLog(LogClient logClient, Consumer destination, boolean fromStart) {
+  /**
+   * Creates a log redirection that is not started yet.
+   *
+   * @param since redirect only the messages logged at this time or later; {@code null} redirects
+   *     the whole log
+   */
+  public StreamedLog(LogClient logClient, Consumer destination, Instant since) {
     this.logClient = logClient;
     this.destination = destination;
-    this.relevancyTimeLimit = fromStart ? null : Instant.now();
+    this.since = since;
+  }
+
+  /**
+   * The timestamp of the last redirected log message, or empty if nothing has been redirected yet.
+   * To continue the redirection in another process, pass this timestamp plus one millisecond as
+   * {@link com.apify.client.log.StreamedLogOptions#since(Instant)}.
+   */
+  public Optional getLastRedirectedAt() {
+    return Optional.ofNullable(lastRedirectedAt);
   }
 
   /**
@@ -277,15 +323,11 @@ private void awaitStopped(StopHandle handle) {
     }
   }
 
-  /** Reads the live raw log stream and forwards complete messages to the destination. */
+  /**
+   * Reads the live raw log stream and forwards complete messages to the destination. A stream that
+   * breaks off after it delivered data is reopened.
+   */
   private void streamLog() {
-    // Bytes after the last newline, kept for the next read so that a message split across chunks,
-    // even in the middle of a UTF-8 sequence, is not corrupted. Declared outside the try so the
-    // final flush can emit it.
-    byte[] lineRemainder = new byte[0];
-    // Decoded text not yet split into complete messages. Local, so overlapping readers never share
-    // it.
-    StringBuilder pending = new StringBuilder();
     InputStream stream;
     try {
       // The API serves the log of a run that has not logged yet as a stream that ends at once.
@@ -302,13 +344,35 @@ private void streamLog() {
       try {
         String logContent = logClient.get(new LogOptions().raw(true)).join().orElse("");
         if (!forwardingFailed) {
-          emitMessages(pending, logContent, true);
+          emitMessages(new StringBuilder(), logContent, true);
         }
       } catch (RuntimeException e) {
         LOG.warn("Log redirection stopped due to error", e);
       }
       return;
     }
+    while (redirectLogStream(stream)) {
+      stream = reopenBrokenStream();
+      if (stream == null) {
+        return;
+      }
+    }
+  }
+
+  /**
+   * Forwards the messages of one log stream until it ends or redirection is stopped. Returns
+   * whether the stream broke off and has to be opened again. A stream that ends without an error
+   * after it delivered data carried the whole log of a finished run.
+   */
+  private boolean redirectLogStream(InputStream stream) {
+    // Bytes after the last newline, kept for the next read so that a message split across chunks,
+    // even in the middle of a UTF-8 sequence, is not corrupted. Declared outside the try so the
+    // final flush can emit it.
+    byte[] lineRemainder = new byte[0];
+    // Decoded text not yet split into complete messages. Local, so overlapping readers never share
+    // it.
+    StringBuilder pending = new StringBuilder();
+    boolean brokeOff = false;
     // The reader owns the stream and closes it on exit; stop() may close it first to end a read.
     try (InputStream liveStream = stream) {
       byte[] readBuffer = new byte[READ_BUFFER_BYTES];
@@ -334,17 +398,92 @@ private void streamLog() {
         }
       }
     } catch (IOException e) {
-      // A read error after an explicit stop is expected. Report only unsolicited failures.
+      // A read error after an explicit stop is expected. Any other one cut the stream off.
       if (!stopLogging) {
-        LOG.warn("Log redirection stopped due to error", e);
+        if (replayCaughtUp()) {
+          LOG.debug("Log stream broke off, reopening it", e);
+          prepareReopen();
+          brokeOff = true;
+        } else {
+          LOG.warn(
+              "Log redirection stopped: the reopened log stream broke off again before it reached"
+                  + " the last redirected message",
+              e);
+        }
       }
     } finally {
       // Flush on stream end and on a stop mid-read: emitMessages holds back the last message and a
-      // stop skips the loop body. Skipped once a consumer has thrown.
-      if (!forwardingFailed) {
+      // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke
+      // off, since its held-back message comes again when the log is replayed.
+      if (!brokeOff && !forwardingFailed) {
         emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true);
       }
     }
+    return brokeOff;
+  }
+
+  /**
+   * Waits {@link #BROKEN_STREAM_REOPEN_MILLIS}, then opens the log stream again. Returns {@code
+   * null} if redirection was stopped meanwhile or the stream could not be opened.
+   */
+  private InputStream reopenBrokenStream() {
+    sleepAsWakeableBackoff(BROKEN_STREAM_REOPEN_MILLIS);
+    if (stopLogging) {
+      return null;
+    }
+    InputStream reopened;
+    try {
+      reopened = logClient.stream(new LogOptions().raw(true)).join();
+    } catch (RuntimeException e) {
+      if (!stopLogging) {
+        LOG.warn("Log redirection stopped due to error", e);
+      }
+      return null;
+    }
+    // A plain volatile write, so the reader never waits for the monitor here.
+    activeStream = reopened;
+    // A stop during the reopen closed the previous stream, not this one, so close it here.
+    if (stopLogging) {
+      closeQuietly(reopened);
+      return null;
+    }
+    return reopened;
+  }
+
+  /** Makes the reopened stream redirect only the messages after the last redirected one. */
+  private void prepareReopen() {
+    replayedUntil = lastRedirectedAt;
+    replaySkipCount = redirectedAtLastTimestamp;
+  }
+
+  /** Whether the current stream got at least as far as the stream before it. */
+  private boolean replayCaughtUp() {
+    return replayedUntil == null || replaySkipCount == 0;
+  }
+
+  /** Whether a message of a reopened stream was already redirected before it was reopened. */
+  private boolean isReplayed(Instant logTime) {
+    if (replayedUntil == null) {
+      return false;
+    }
+    if (logTime.isBefore(replayedUntil)) {
+      return true;
+    }
+    if (logTime.equals(replayedUntil) && replaySkipCount > 0) {
+      replaySkipCount--;
+      return true;
+    }
+    replayedUntil = null;
+    return false;
+  }
+
+  private void rememberRedirected(Instant logTime) {
+    if (logTime.equals(lastRedirectedAt)) {
+      redirectedAtLastTimestamp++;
+    } else {
+      lastRedirectedAt = logTime;
+      redirectedAtLastTimestamp = 1;
+    }
   }
 
   /**
@@ -464,21 +603,16 @@ private void emitMessages(StringBuilder pending, String text, boolean flush) {
   }
 
   /**
-   * Forwards a trimmed message to the destination, dropping it if it is empty or (when a relevancy
-   * limit is set) older than that limit.
+   * Forwards a trimmed message to the destination, dropping it if it is empty, was already
+   * redirected before the stream was reopened, or is older than {@link #since}.
    */
   private void emitIfRelevant(String message, String timestamp) {
     if (message.isEmpty()) {
       return;
     }
-    if (relevancyTimeLimit != null && timestamp != null) {
-      try {
-        if (Instant.parse(timestamp).isBefore(relevancyTimeLimit)) {
-          return;
-        }
-      } catch (DateTimeParseException ignored) {
-        // Unparseable timestamp: keep the message rather than silently dropping log output.
-      }
+    Instant logTime = parseTimestamp(timestamp);
+    if (logTime != null && (isReplayed(logTime) || (since != null && logTime.isBefore(since)))) {
+      return;
     }
     try {
       destination.accept(message);
@@ -488,6 +622,25 @@ private void emitIfRelevant(String message, String timestamp) {
       forwardingFailed = true;
       stopLogging = true;
       LOG.warn("Log redirection stopped due to error", e);
+      return;
+    }
+    if (logTime != null) {
+      rememberRedirected(logTime);
+    }
+  }
+
+  /**
+   * Parses a message timestamp. Returns {@code null} for a message without one, or with one that is
+   * not a valid instant: it is then kept, rather than silently dropping log output.
+   */
+  private static Instant parseTimestamp(String timestamp) {
+    if (timestamp == null) {
+      return null;
+    }
+    try {
+      return Instant.parse(timestamp);
+    } catch (DateTimeParseException e) {
+      return null;
     }
   }
 
diff --git a/src/main/java/com/apify/client/log/StreamedLogOptions.java b/src/main/java/com/apify/client/log/StreamedLogOptions.java
index 8de3d4e..1f0de88 100644
--- a/src/main/java/com/apify/client/log/StreamedLogOptions.java
+++ b/src/main/java/com/apify/client/log/StreamedLogOptions.java
@@ -1,19 +1,20 @@
 package com.apify.client.log;
 
 import com.apify.client.run.RunClient;
+import java.time.Instant;
 import java.util.function.Consumer;
 
 /**
  * Configures {@link RunClient#getStreamedLog(StreamedLogOptions)} log redirection.
  *
- * 

Sets the destination ({@code toLog}) and whether to include messages produced before - * redirection started ({@code fromStart}). + *

Sets the destination ({@code toLog}) and the time from which messages are redirected ({@code + * since}). */ public final class StreamedLogOptions { private Consumer toLog; private String prefix; - private boolean fromStart = true; + private Instant since; /** * Destination for redirected log messages. Each complete log message is passed to the consumer. @@ -36,12 +37,12 @@ public StreamedLogOptions prefix(String prefix) { } /** - * Whether to redirect all of the run's logs, including those produced before redirection started - * ({@code true}, the default). When {@code false}, only messages timestamped at or after the - * moment redirection is created are redirected. + * Redirect only the log messages logged 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. */ - public StreamedLogOptions fromStart(boolean fromStart) { - this.fromStart = fromStart; + public StreamedLogOptions since(Instant since) { + this.since = since; return this; } @@ -53,7 +54,7 @@ public String prefixValue() { return prefix; } - public boolean fromStartValue() { - return fromStart; + public Instant sinceValue() { + return since; } } diff --git a/src/main/java/com/apify/client/run/RunClient.java b/src/main/java/com/apify/client/run/RunClient.java index b3e48ff..d1ecec4 100644 --- a/src/main/java/com/apify/client/run/RunClient.java +++ b/src/main/java/com/apify/client/run/RunClient.java @@ -328,24 +328,26 @@ public CompletableFuture getStreamedLog() { *

If {@link StreamedLogOptions#toLog(Consumer)} is set, each complete log message is passed to * that consumer; otherwise a default {@link Logger} destination is used with a per-run prefix (an * explicit {@link StreamedLogOptions#prefix(String)} overrides the auto-built one, in which case - * this completes without needing to fetch the run). {@link StreamedLogOptions#fromStart(boolean)} - * controls whether log lines produced before redirection started are included. + * this completes without needing to fetch the run). {@link + * StreamedLogOptions#since(java.time.Instant)} limits the redirection to the log lines logged at + * that time or later. + * + *

When the log stream is cut off while the run is still going, it is reopened and the + * redirection resumes after the last redirected message. */ public CompletableFuture getStreamedLog(StreamedLogOptions options) { Consumer destination = options.destination(); if (destination != null) { - return CancellableFuture.completed( - new StreamedLog(log(), destination, options.fromStartValue())); + return CancellableFuture.completed(new StreamedLog(log(), destination, options.sinceValue())); } if (options.prefixValue() != null) { return CancellableFuture.completed( new StreamedLog( - log(), defaultLogDestination(options.prefixValue()), options.fromStartValue())); + log(), defaultLogDestination(options.prefixValue()), options.sinceValue())); } return buildDefaultLogPrefix() .thenApply( - prefix -> - new StreamedLog(log(), defaultLogDestination(prefix), options.fromStartValue())); + prefix -> new StreamedLog(log(), defaultLogDestination(prefix), options.sinceValue())); } /** diff --git a/src/main/java/com/apify/client/store/ActorStoreListItem.java b/src/main/java/com/apify/client/store/ActorStoreListItem.java index 4b3ad50..e3ca439 100644 --- a/src/main/java/com/apify/client/store/ActorStoreListItem.java +++ b/src/main/java/com/apify/client/store/ActorStoreListItem.java @@ -6,7 +6,7 @@ import java.util.List; import tools.jackson.databind.annotation.JsonDeserialize; -/** An Actor as listed in the Apify Store. */ +/** An Actor as listed in Apify Store. */ public final class ActorStoreListItem extends ApifyResource { private String id; private String name; @@ -18,7 +18,6 @@ public final class ActorStoreListItem extends ApifyResource { private String notice; private StoreActorStats stats; private PricingInfo currentPricingInfo; - private Boolean isWhiteListedForAgenticPayments; private Boolean isVerified; private String badge; private String pictureUrl; @@ -88,11 +87,6 @@ public PricingInfo getCurrentPricingInfo() { return currentPricingInfo; } - /** Whether the Actor is whitelisted for agentic payment processing. */ - public Boolean getIsWhiteListedForAgenticPayments() { - return isWhiteListedForAgenticPayments; - } - /** Whether the Actor's developer has a verified identity. */ public Boolean getIsVerified() { return isVerified; diff --git a/src/main/java/com/apify/client/store/StoreCollectionClient.java b/src/main/java/com/apify/client/store/StoreCollectionClient.java index 48e2252..b412283 100644 --- a/src/main/java/com/apify/client/store/StoreCollectionClient.java +++ b/src/main/java/com/apify/client/store/StoreCollectionClient.java @@ -5,13 +5,14 @@ import com.apify.client.internal.HttpClientCore; import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; +import java.util.Objects; import java.util.concurrent.CompletableFuture; /** - * A client for browsing and searching the Apify Store ({@code GET /v2/store}). The API serves it in - * two ways, and this client has one method for each: {@code list} and {@code iterate} browse the - * whole Store in Store order, page by page, and {@link #search(StoreSearchOptions)} returns the - * Actors that match a query best, as a single page. + * A client for browsing and searching Apify Store ({@code GET /v2/store}). The API serves it in two + * ways, and this client has one method for each: {@code list} and {@code iterate} browse the whole + * Store in Store order, page by page, and {@link #search(StoreSearchOptions)} returns the Actors + * that match a query best, as a single page. */ public final class StoreCollectionClient extends AbstractCollectionClient { @@ -24,7 +25,7 @@ public StoreCollectionClient(HttpClientCore http, String baseUrl) { } /** - * Searches the Apify Store and completes with the Actors that match the query best, ordered by + * Searches Apify Store and completes with 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 @@ -35,8 +36,10 @@ public StoreCollectionClient(HttpClientCore http, String baseUrl) { * iterate}. * * @param options the query, the filters, and the number of results + * @throws NullPointerException if {@code options} is {@code null} */ public CompletableFuture search(StoreSearchOptions options) { + Objects.requireNonNull(options, "options"); QueryParams params = new QueryParams(); options.apply(params); return listWithParams(params) diff --git a/src/main/java/com/apify/client/store/StoreFilterOptions.java b/src/main/java/com/apify/client/store/StoreFilterOptions.java index 9bc363e..95d21f7 100644 --- a/src/main/java/com/apify/client/store/StoreFilterOptions.java +++ b/src/main/java/com/apify/client/store/StoreFilterOptions.java @@ -13,7 +13,6 @@ public abstract class StoreFilterOptions> { private String username; private String pricingModel; private Boolean includeUnrunnableActors; - private Boolean allowsAgenticUsers; private String responseFormat; private Boolean includeInputSchema; @@ -38,28 +37,30 @@ public T username(String username) { } /** - * Filter Actors by pricing model ({@code FREE}, {@code PRICE_PER_DATASET_ITEM}, {@code - * PAY_PER_EVENT}). The rental model ({@code FLAT_PRICE_PER_MONTH}) is deprecated and no longer - * supported, so it is no longer documented as a filter value and matches no Actors. + * Filter Actors by pricing model: {@code FREE}, {@code PRICE_PER_DATASET_ITEM}, or {@code + * PAY_PER_EVENT}. */ public T pricingModel(String pricingModel) { this.pricingModel = pricingModel; return self(); } - /** Include Actors the current user cannot run. */ + /** + * By default, the API leaves out Actors that are not safe to run automatically, such as Actors of + * developers who have not passed identity verification, or full-permission Actors without a large + * user base. If {@code true}, it skips that safety filter and includes them. + */ public T includeUnrunnableActors(Boolean includeUnrunnableActors) { this.includeUnrunnableActors = includeUnrunnableActors; return self(); } - /** Filter to Actors that allow agentic users. */ - public T allowsAgenticUsers(Boolean allowsAgenticUsers) { - this.allowsAgenticUsers = allowsAgenticUsers; - return self(); - } - - /** The response format ({@code full}, {@code agent}). */ + /** + * The shape of the response: {@code full} (the default) returns every field, and {@code agent} + * returns a reduced field set for LLM consumers ({@code id}, {@code title}, {@code name}, {@code + * username}, {@code description}, {@code notice}, {@code badge}, {@code categories}, and minimal + * {@code stats}), so the other getters of {@link ActorStoreListItem} return {@code null}. + */ public T responseFormat(String responseFormat) { this.responseFormat = responseFormat; return self(); @@ -68,7 +69,8 @@ public T responseFormat(String responseFormat) { /** * Include a compact {@code inputSchema} (property types and required properties only) of each * Actor's default build in the results, available through {@code ActorStoreListItem#getExtra()}. - * With this flag the API defaults {@code limit} to, and caps it at, {@code 10}. + * With this flag the API defaults {@code limit} to {@code 10} and rejects a larger value with a + * {@code 400} error. */ public T includeInputSchema(Boolean includeInputSchema) { this.includeInputSchema = includeInputSchema; @@ -81,7 +83,6 @@ public void applyFilters(QueryParams q) { .addString("username", username) .addString("pricingModel", pricingModel) .addBool("includeUnrunnableActors", includeUnrunnableActors) - .addBool("allowsAgenticUsers", allowsAgenticUsers) .addString("responseFormat", responseFormat) .addBool("includeInputSchema", includeInputSchema); } diff --git a/src/main/java/com/apify/client/store/StoreListOptions.java b/src/main/java/com/apify/client/store/StoreListOptions.java index 878f37a..6efb155 100644 --- a/src/main/java/com/apify/client/store/StoreListOptions.java +++ b/src/main/java/com/apify/client/store/StoreListOptions.java @@ -4,7 +4,7 @@ import com.apify.client.internal.QueryParams; /** - * Options for listing/iterating the Apify Store ({@code GET /v2/store}). The Actors come in Store + * Options for listing/iterating Apify Store ({@code GET /v2/store}). The Actors come in Store * order, which the API has no option to change. To find Actors by a text query, use {@link * StoreSearchOptions} with {@link StoreCollectionClient#search(StoreSearchOptions)}. */ @@ -25,8 +25,9 @@ public StoreListOptions offset(Long offset) { } /** - * Maximum number of Actors to return. The API default and maximum is {@code 1000}. Sent verbatim - * by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} a + * Maximum number of Actors to return. The API default and maximum is {@code 1000}; with {@link + * #includeInputSchema(Boolean)} the default is {@code 10} and a larger value is rejected. Sent + * verbatim by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} a * non-positive/zero {@code limit} means "no cap" (all). */ public StoreListOptions limit(Long limit) { diff --git a/src/main/java/com/apify/client/store/StoreSearchOptions.java b/src/main/java/com/apify/client/store/StoreSearchOptions.java index c4781b9..f80cd44 100644 --- a/src/main/java/com/apify/client/store/StoreSearchOptions.java +++ b/src/main/java/com/apify/client/store/StoreSearchOptions.java @@ -3,10 +3,10 @@ import com.apify.client.internal.QueryParams; /** - * Options for searching the Apify Store ({@code GET /v2/store} with a {@code search} query). The - * API ranks the results by relevance and returns them as a single page of at most 100 Actors, so - * there is no {@code offset}. Narrow a search with {@link #category(String)}, {@link - * #username(String)}, or {@link #pricingModel(String)}. + * Options for searching Apify Store ({@code GET /v2/store} with a {@code search} query). The API + * ranks the results by relevance and returns them as a single page of at most 100 Actors, so there + * is no {@code offset}. Narrow a search with {@link #category(String)}, {@link #username(String)}, + * or {@link #pricingModel(String)}. */ public final class StoreSearchOptions extends StoreFilterOptions { private final String search; @@ -33,7 +33,8 @@ StoreSearchOptions self() { /** * Maximum number of Actors to return. The API returns at most {@code 100} Actors for a search, - * which is also the default, and reduces a larger value to {@code 100}. + * which is also the default, and reduces a larger value to {@code 100}. With {@link + * #includeInputSchema(Boolean)}, the default is {@code 10} and a larger value is rejected. * * @throws IllegalArgumentException if {@code limit} is not positive */ @@ -46,7 +47,7 @@ public StoreSearchOptions limit(Long limit) { } /** Applies the query, the limit, and every filter as query parameters. */ - public void apply(QueryParams q) { + void apply(QueryParams q) { q.addString("search", search).addLong("limit", limit); applyFilters(q); } diff --git a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java index 1e8af1f..9cbcb38 100644 --- a/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java +++ b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java @@ -591,8 +591,7 @@ void storeItemParsesTheStoreShape() { + "\"categories\":[\"AI_AND_ML\",\"GENERATE_LEADS\"],\"notice\":\"UNDER_MAINTENANCE\"," + "\"stats\":{\"totalUsers\":6,\"totalRuns\":16,\"totalUsers7Days\":2," + "\"totalUsers30Days\":6,\"totalUsers90Days\":6,\"actorReviewRating\":4.7," - + "\"actorReviewCount\":69},\"isWhiteListedForAgenticPayments\":true," - + "\"isVerified\":true,\"badge\":null}," + + "\"actorReviewCount\":69},\"isVerified\":true,\"badge\":null}," + "{\"id\":\"b\",\"categories\":null,\"stats\":{\"totalUsers\":1}}]," + "\"total\":2,\"offset\":0,\"limit\":2,\"count\":2}}"); List items = @@ -608,7 +607,6 @@ void storeItemParsesTheStoreShape() { assertEquals(6L, first.getStats().getTotalUsers90Days()); assertEquals(4.7, first.getStats().getActorReviewRating()); assertEquals(69L, first.getStats().getActorReviewCount()); - assertEquals(Boolean.TRUE, first.getIsWhiteListedForAgenticPayments()); assertEquals(Boolean.TRUE, first.getIsVerified()); assertNull(first.getBadge()); assertTrue(items.get(1).getCategories().isEmpty(), "null categories read as an empty list"); diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index b6d7ba8..f18261f 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -15,6 +15,7 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -27,8 +28,8 @@ /** * Offline tests for the {@link StreamedLog} log-redirection helper: it must forward complete - * timestamped messages to the destination, drop messages older than the relevancy limit when {@code - * fromStart} is false, flush a final unterminated line, and enforce its start/stop lifecycle. + * timestamped messages to the destination, drop messages older than {@code since}, flush a final + * unterminated line, and enforce its start/stop lifecycle. */ @Timeout(30) class StreamedLogTest { @@ -92,13 +93,12 @@ void flushesFinalUnterminatedMessage() throws InterruptedException { } @Test - void fromStartFalseDropsOldMessages() throws InterruptedException { - // relevancyTimeLimit is set to "now" at construction, so the year-2000 line is dropped and the - // year-2999 line is kept. + void sinceDropsOldMessages() throws InterruptedException { + // The year-2000 line is older than `since` and dropped; the year-2999 line is kept. List messages = redirect( "2000-01-01T00:00:00.000Z old\n2999-01-01T00:00:00.000Z new\n", - new StreamedLogOptions().fromStart(false)); + new StreamedLogOptions().since(Instant.parse("2020-01-01T00:00:00Z"))); assertEquals(List.of("2999-01-01T00:00:00.000Z new"), messages); } @@ -628,6 +628,134 @@ void stopDuringAnInFlightReopenStillCompletesPromptly() { "stop() should return well within the full empty-stream backoff/retry schedule"); } + /** Redirects the scripted streams of a run and returns what reached the destination. */ + private static List redirectUntil( + MockTransport backend, StreamedLogOptions options, int expectedMessages) { + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend).run("run123").getStreamedLog(options.toLog(collected::add)).join(); + streamedLog.start().join(); + pollUntil( + REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= expectedMessages); + streamedLog.stop(); + return collected; + } + + @Test + void reopensAStreamThatBrokeOffAndSkipsTheMessagesItAlreadyRedirected() { + // A stream cut off while the run goes on is reopened. The reopened stream replays the whole + // log, + // so the messages redirected before the break must not come again, and the held-back last + // message of the broken stream is redirected once, from the reopened one. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n")); + backend.scriptStream( + 200, + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n" + + "2999-01-01T00:00:03.000Z D\n"); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C", + "2999-01-01T00:00:03.000Z D"), + collected); + assertEquals(2, backend.calls, "one open, one reopen"); + } + + @Test + void aReopenSkipsOnlyAsManyMessagesAsItRedirectedAtTheSharedTimestamp() { + // Several messages can share a millisecond: the replay skips exactly the ones already + // redirected there, and redirects the rest. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z a\n2999-01-01T00:00:00.000Z b\n2999-01-01T00:00:00.000Z c\n")); + backend.scriptStream( + 200, + "2999-01-01T00:00:00.000Z a\n2999-01-01T00:00:00.000Z b\n2999-01-01T00:00:00.000Z c\n" + + "2999-01-01T00:00:01.000Z d\n"); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z a", + "2999-01-01T00:00:00.000Z b", + "2999-01-01T00:00:00.000Z c", + "2999-01-01T00:00:01.000Z d"), + collected); + } + + @Test + void aReopenedStreamThatBreaksOffBeforeTheLastRedirectedMessageEndsTheRedirection() + throws InterruptedException { + // The first stream redirected A and B. The reopened one breaks off after A, before it replayed + // B, so continuing would skip log lines: redirection stops instead of reopening again. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n")); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); + assertEquals(2, backend.calls, "no third open"); + } + + @Test + void aStreamThatEndsWithoutAnErrorIsNotReopened() throws InterruptedException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); + assertEquals(1, backend.calls); + } + + @Test + void aStreamThatBreaksOffBeforeItsFirstByteEndsTheRedirection() throws InterruptedException { + // Nothing was delivered yet, so there is nothing to resume: the error ends the redirection. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, new BrokenStream("")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + assertEquals(List.of(), redirect(backend, new StreamedLogOptions())); + assertEquals(1, backend.calls); + } + + @Test + void lastRedirectedAtIsTheTimestampOfTheLastRedirectedMessage() throws InterruptedException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.500Z B\n"); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(m -> {})) + .join(); + assertTrue(streamedLog.getLastRedirectedAt().isEmpty(), "nothing redirected yet"); + streamedLog.start().join(); + streamedLog.stop(); + assertEquals( + Instant.parse("2999-01-01T00:00:01.500Z"), streamedLog.getLastRedirectedAt().orElseThrow()); + } + + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ + private static List redirect(MockTransport backend, StreamedLogOptions options) + throws InterruptedException { + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend).run("run123").getStreamedLog(options.toLog(collected::add)).join(); + streamedLog.start().join(); + // Reopening pauses for a second, so give a reader that does not end quickly time to finish. + Thread.sleep(2_500); + streamedLog.stop(); + return collected; + } + @Test void defaultPrefixLookupFailureStillCreatesHelper() { // The no-arg getStreamedLog() builds a cosmetic per-run prefix by GETting the run (and its @@ -640,6 +768,37 @@ void defaultPrefixLookupFailureStillCreatesHelper() { assertNotNull(streamedLog); } + /** + * An {@link InputStream} that serves a fixed payload and then fails with an {@link IOException} + * on its own, as a log stream does when the connection is cut off. + */ + private static final class BrokenStream extends InputStream { + private final byte[] data; + private int pos; + + BrokenStream(String data) { + this.data = data.getBytes(StandardCharsets.UTF_8); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (pos >= data.length) { + throw new IOException("Connection reset"); + } + int n = Math.min(len, data.length - pos); + System.arraycopy(data, pos, b, off, n); + pos += n; + return n; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int n = read(one, 0, 1); + return n == -1 ? -1 : one[0] & 0xff; + } + } + /** * An {@link InputStream} that serves a fixed payload once and then blocks on {@code read()} until * it is closed, throwing an {@link IOException} when unblocked by the close. This models a live From 2d75729a5efc6b34a33785251cbe4791cf4cc201 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 10:34:18 +0000 Subject: [PATCH 09/19] fix: redirect the last log message when a broken stream is not reopened A stream that broke off held back its last message for the replay of the reopened stream. A stop during the reopen, a failed reopen, or a stop during the replay lost that message. Now the whole log is read once through the replay filter. start() clears the replay state, and the resume example and the since migration are documented. --- CHANGELOG.md | 2 +- docs/runs.md | 25 ++-- .../com/apify/client/log/StreamedLog.java | 69 ++++++++--- .../com/apify/client/StreamedLogTest.java | 108 +++++++++++++++++- 4 files changed, 178 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c897d..997227a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,7 +38,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - **Breaking:** `StoreListOptions.search`. Use `StoreCollectionClient.search`: the Store answers a search with one page of at most 100 Actors and ignores `offset`. - **Breaking:** `StoreListOptions.sortBy`, which the API ignores. -- **Breaking:** `StreamedLogOptions.fromStart`. Use `StreamedLogOptions.since`. +- **Breaking:** `StreamedLogOptions.fromStart`. Use `StreamedLogOptions.since`: `fromStart(false)` becomes `since(Instant.now())`, and `fromStart(true)` is the default. - **Breaking:** `StoreListOptions.allowsAgenticUsers` and `ActorStoreListItem.getIsWhiteListedForAgenticPayments`, which the API no longer has. ## [0.14.1] - 2026-11-20 diff --git a/docs/runs.md b/docs/runs.md index dc78750..3e6c7da 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -80,21 +80,28 @@ If the log stream is cut off while the run is still going, for example because t nothing for several minutes, `StreamedLog` reopens it and continues after the last redirected message. The API cannot continue a log stream from a given point, so the reopened stream replays the whole log, and the messages already redirected are skipped. `StreamedLog.getLastRedirectedAt()` -returns the timestamp of the last redirected message (empty before the first one). To continue a -redirection in another process, for example after the Actor that redirects the log reboots, save it -and pass a later time to `since`: +returns the timestamp of the last redirected message (empty before the first one); read it after +`stop()` or `close()`, which deliver the last message. To continue a redirection in another +process, for example after the Actor that redirects the log reboots, save it and pass it to +`since`. The API cannot continue a log from an exact point: with the saved timestamp itself, +messages logged in the same millisecond come again, and with one millisecond added, those not +redirected yet are dropped. ```java RunClient runClient = client.run("RUN_ID"); -Instant lastRedirectedAt; -try (StreamedLog streamedLog = runClient.getStreamedLog().join()) { +StreamedLog streamedLog = runClient.getStreamedLog().join(); +try (streamedLog) { streamedLog.start().join(); runClient.waitForFinish(120L).join(); - lastRedirectedAt = streamedLog.getLastRedirectedAt().orElse(Instant.EPOCH); } -// Later, for example in another process, continue after that message. -StreamedLog resumed = - runClient.getStreamedLog(new StreamedLogOptions().since(lastRedirectedAt.plusMillis(1))).join(); +Instant lastRedirectedAt = streamedLog.getLastRedirectedAt().orElse(Instant.EPOCH); + +// Later, for example in another process, continue from that message. +StreamedLogOptions resumedOptions = new StreamedLogOptions().since(lastRedirectedAt); +try (StreamedLog resumed = runClient.getStreamedLog(resumedOptions).join()) { + resumed.start().join(); + runClient.waitForFinish(120L).join(); +} ``` A run that has not logged anything yet (e.g. still queued for resources, see diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index d53d445..6d8e15c 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -110,6 +110,12 @@ public final class StreamedLog implements AutoCloseable { private int replaySkipCount; + /** + * The complete lines of the last message that a broken stream had received but held back, as it + * may still have been growing. Used when the log cannot be read again. + */ + private String heldBack = ""; + private volatile boolean stopLogging; /** Set when the destination consumer throws; nothing is forwarded after that. */ @@ -145,8 +151,11 @@ public StreamedLog(LogClient logClient, Consumer destination, Instant si /** * The timestamp of the last redirected log message, or empty if nothing has been redirected yet. - * To continue the redirection in another process, pass this timestamp plus one millisecond as - * {@link com.apify.client.log.StreamedLogOptions#since(Instant)}. + * To continue the redirection in another process, pass this timestamp as {@link + * com.apify.client.log.StreamedLogOptions#since(Instant)}: with the timestamp itself, messages + * logged in the same millisecond come again, and with one millisecond added, those not redirected + * yet are dropped, as the API cannot continue a log from an exact point. Read it after {@link + * #stop()} or {@link #close()}, which deliver the last message. */ public Optional getLastRedirectedAt() { return Optional.ofNullable(lastRedirectedAt); @@ -179,6 +188,10 @@ public synchronized CompletableFuture start() { starting = true; stopLogging = false; forwardingFailed = false; + // A new redirection reads the log from its start, so nothing is skipped as replayed. + replayedUntil = null; + replaySkipCount = 0; + heldBack = ""; CancellableFuture started = new CancellableFuture<>(); CompletableFuture opening = logClient.stream(new LogOptions().raw(true)); // Cancelling the returned future cancels the stream-open request. The callback below hangs off @@ -354,9 +367,32 @@ private void streamLog() { while (redirectLogStream(stream)) { stream = reopenBrokenStream(); if (stream == null) { + redirectRemainingLog(); return; } } + if (stopLogging && replayedUntil != null) { + // Stopped while a reopened stream was still replaying messages that were already redirected. + redirectRemainingLog(); + } + } + + /** + * Redirects what a broken stream did not deliver, when no reopened stream will: reads the whole + * log once and passes it through the replay filter, which skips the messages already redirected. + * If the log cannot be read, the held-back lines of the broken stream are redirected instead. + */ + private void redirectRemainingLog() { + if (forwardingFailed) { + return; + } + try { + String logContent = logClient.get(new LogOptions().raw(true)).join().orElse(""); + emitMessages(new StringBuilder(), logContent, true); + } catch (RuntimeException e) { + LOG.warn("Log redirection stopped due to error", e); + emitMessages(new StringBuilder(), heldBack, true); + } } /** @@ -373,6 +409,7 @@ private boolean redirectLogStream(InputStream stream) { // it. StringBuilder pending = new StringBuilder(); boolean brokeOff = false; + heldBack = ""; // The reader owns the stream and closes it on exit; stop() may close it first to end a read. try (InputStream liveStream = stream) { byte[] readBuffer = new byte[READ_BUFFER_BYTES]; @@ -403,6 +440,7 @@ private boolean redirectLogStream(InputStream stream) { if (replayCaughtUp()) { LOG.debug("Log stream broke off, reopening it", e); prepareReopen(); + heldBack = pending.toString(); brokeOff = true; } else { LOG.warn( @@ -431,23 +469,30 @@ private InputStream reopenBrokenStream() { if (stopLogging) { return null; } - InputStream reopened; try { - reopened = logClient.stream(new LogOptions().raw(true)).join(); + return openStreamUnlessStopped(); } catch (RuntimeException e) { if (!stopLogging) { LOG.warn("Log redirection stopped due to error", e); } return null; } + } + + /** + * Opens the raw log stream and makes it the one {@link #stop()} closes. Returns {@code null}, + * with the new stream closed, if redirection was stopped meanwhile. + */ + private InputStream openStreamUnlessStopped() { + InputStream opened = logClient.stream(new LogOptions().raw(true)).join(); // A plain volatile write, so the reader never waits for the monitor here. - activeStream = reopened; - // A stop during the reopen closed the previous stream, not this one, so close it here. + activeStream = opened; + // A stop during the open closed the previous stream, not this one, so close it here. if (stopLogging) { - closeQuietly(reopened); + closeQuietly(opened); return null; } - return reopened; + return opened; } /** Makes the reopened stream redirect only the messages after the last redirected one. */ @@ -522,7 +567,7 @@ private InputStream awaitNonEmptyStream() throws IOException { return null; } try { - stream = logClient.stream(new LogOptions().raw(true)).join(); + stream = openStreamUnlessStopped(); } catch (RuntimeException e) { if (stopLogging) { return null; @@ -533,11 +578,7 @@ private InputStream awaitNonEmptyStream() throws IOException { } throw new IOException("failed to reopen log stream", cause); } - // A plain volatile write, so the reader never waits for the monitor here. - activeStream = stream; - // A stop during the reopen closed the previous stream, not this one, so close it here. - if (stopLogging) { - closeQuietly(stream); + if (stream == null) { return null; } } diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index f18261f..b4d8692 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -44,6 +44,12 @@ class StreamedLogTest { */ private static final int REDIRECT_POLL_ATTEMPTS = (int) (5_000 / REDIRECT_POLL_MILLIS); + /** Covers the one-second pause before a broken stream is reopened, plus a margin. */ + private static final long REOPEN_WAIT_MILLIS = 2_500; + + /** Long enough for the reader to handle a broken stream and sleep before reopening it. */ + private static final long BREAK_HANDLED_MILLIS = 300; + private static ApifyClient client(MockTransport backend) { return ApifyClient.builder().token("test-token").httpTransport(backend).maxRetries(0).build(); } @@ -743,6 +749,105 @@ void lastRedirectedAtIsTheTimestampOfTheLastRedirectedMessage() throws Interrupt Instant.parse("2999-01-01T00:00:01.500Z"), streamedLog.getLastRedirectedAt().orElseThrow()); } + private static final String LOG_ABC = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n"; + + @Test + void stopDuringThePauseBeforeAReopenStillRedirectsTheHeldBackMessage() + throws InterruptedException { + // The broken stream held C back, expecting the reopened stream to replay it. A stop that comes + // before the reopen reads the whole log once instead, and the replay filter skips A and B. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= 2); + Thread.sleep(BREAK_HANDLED_MILLIS); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + assertEquals( + Instant.parse("2999-01-01T00:00:02.000Z"), streamedLog.getLastRedirectedAt().orElseThrow()); + } + + @Test + void aFailedReopenStillRedirectsTheHeldBackMessage() { + // The reopen and the one-off read of the log both fail, so the lines the broken stream held + // back are all that is left to redirect. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void stopWhileAReopenedStreamIsStillReplayingRedirectsTheRest() { + // The reopened stream serves A and then stalls, before it reaches B and C. Stopping then reads + // the whole log once, which delivers C and skips what was already redirected. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream("2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRestartRedirectsTheWholeLogEvenAfterAStopDuringAReopen() throws InterruptedException { + // The first redirection stops during the pause before a reopen. The one-off read of the log is + // empty, so the replay filter stays armed for A. A new start() reads the log from its start and + // must not skip anything. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, new BrokenStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + Thread.sleep(BREAK_HANDLED_MILLIS); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + collected.clear(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= 2); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { @@ -750,8 +855,7 @@ private static List redirect(MockTransport backend, StreamedLogOptions o StreamedLog streamedLog = client(backend).run("run123").getStreamedLog(options.toLog(collected::add)).join(); streamedLog.start().join(); - // Reopening pauses for a second, so give a reader that does not end quickly time to finish. - Thread.sleep(2_500); + Thread.sleep(REOPEN_WAIT_MILLIS); streamedLog.stop(); return collected; } From 8d4bf1ad3c1033738b06205580ee02678ffd6f56 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 10:53:03 +0000 Subject: [PATCH 10/19] fix: do not redirect a log message twice after a stop during the replay The full-log read at a stop now rebuilds the replay filter, so a message the reopened stream already replayed is skipped. A broken replay also reads the log once. The held-back message bypasses the filter, and a restart clears the last redirected message. --- docs/runs.md | 8 +- .../com/apify/client/log/StreamedLog.java | 74 ++++++--- .../com/apify/client/StreamedLogTest.java | 155 ++++++++++++++++-- 3 files changed, 197 insertions(+), 40 deletions(-) diff --git a/docs/runs.md b/docs/runs.md index 3e6c7da..0672975 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -80,12 +80,12 @@ If the log stream is cut off while the run is still going, for example because t nothing for several minutes, `StreamedLog` reopens it and continues after the last redirected message. The API cannot continue a log stream from a given point, so the reopened stream replays the whole log, and the messages already redirected are skipped. `StreamedLog.getLastRedirectedAt()` -returns the timestamp of the last redirected message (empty before the first one); read it after +returns the timestamp of the last message redirected since the latest `start()` (empty before the +first one); read it after `stop()` or `close()`, which deliver the last message. To continue a redirection in another process, for example after the Actor that redirects the log reboots, save it and pass it to -`since`. The API cannot continue a log from an exact point: with the saved timestamp itself, -messages logged in the same millisecond come again, and with one millisecond added, those not -redirected yet are dropped. +`since`. So with the saved timestamp itself, messages logged in the same millisecond come again, and +with one millisecond added, those not redirected yet are dropped. ```java RunClient runClient = client.run("RUN_ID"); diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 6d8e15c..4ef2643 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -111,8 +111,9 @@ public final class StreamedLog implements AutoCloseable { private int replaySkipCount; /** - * The complete lines of the last message that a broken stream had received but held back, as it - * may still have been growing. Used when the log cannot be read again. + * The last message that a broken stream had received but held back, as it may still have been + * growing, and that no stream has redirected since. Empty when there is none. Used when the log + * cannot be read again. */ private String heldBack = ""; @@ -150,12 +151,12 @@ public StreamedLog(LogClient logClient, Consumer destination, Instant si } /** - * The timestamp of the last redirected log message, or empty if nothing has been redirected yet. - * To continue the redirection in another process, pass this timestamp as {@link - * com.apify.client.log.StreamedLogOptions#since(Instant)}: with the timestamp itself, messages - * logged in the same millisecond come again, and with one millisecond added, those not redirected - * yet are dropped, as the API cannot continue a log from an exact point. Read it after {@link - * #stop()} or {@link #close()}, which deliver the last message. + * The timestamp of the last message redirected since the latest {@link #start()}, or empty if + * nothing has been redirected yet. To continue the redirection in another process, pass this + * timestamp as {@link com.apify.client.log.StreamedLogOptions#since(Instant)}. The API cannot + * continue a log from an exact point, so with the timestamp itself, messages logged in the same + * millisecond come again, and with one millisecond added, those not redirected yet are dropped. + * Read it after {@link #stop()} or {@link #close()}, which deliver the last message. */ public Optional getLastRedirectedAt() { return Optional.ofNullable(lastRedirectedAt); @@ -189,6 +190,8 @@ public synchronized CompletableFuture start() { stopLogging = false; forwardingFailed = false; // A new redirection reads the log from its start, so nothing is skipped as replayed. + lastRedirectedAt = null; + redirectedAtLastTimestamp = 0; replayedUntil = null; replaySkipCount = 0; heldBack = ""; @@ -364,43 +367,63 @@ private void streamLog() { } return; } - while (redirectLogStream(stream)) { + StreamEnd end = redirectLogStream(stream); + while (end == StreamEnd.BROKE_OFF) { stream = reopenBrokenStream(); if (stream == null) { redirectRemainingLog(); return; } + end = redirectLogStream(stream); } - if (stopLogging && replayedUntil != null) { - // Stopped while a reopened stream was still replaying messages that were already redirected. + if (replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging)) { + // A reopened stream was stopped or broke off again while it was still replaying messages that + // were already redirected, so the messages after them have not been delivered. redirectRemainingLog(); } } + /** How a log stream ended. */ + private enum StreamEnd { + /** The stream ended, or redirection was stopped. */ + ENDED, + /** + * The stream broke off, and a reopened one has to continue after the last redirected message. + */ + BROKE_OFF, + /** A reopened stream broke off again before it replayed up to the last redirected message. */ + REPLAY_INCOMPLETE + } + /** * Redirects what a broken stream did not deliver, when no reopened stream will: reads the whole * log once and passes it through the replay filter, which skips the messages already redirected. - * If the log cannot be read, the held-back lines of the broken stream are redirected instead. + * If the log cannot be read, the held-back message of the broken stream is redirected instead. */ private void redirectRemainingLog() { if (forwardingFailed) { return; } + // A stream that replayed part of the log may have used up some of the filter. Nothing new was + // redirected meanwhile, or the filter would be off, so it is built again from the last message. + prepareReopen(); try { String logContent = logClient.get(new LogOptions().raw(true)).join().orElse(""); emitMessages(new StringBuilder(), logContent, true); } catch (RuntimeException e) { - LOG.warn("Log redirection stopped due to error", e); + LOG.warn("Log redirection could not read the rest of the log", e); + // The held-back message was never redirected, so it must not go through the replay filter. + replayedUntil = null; emitMessages(new StringBuilder(), heldBack, true); } } /** - * Forwards the messages of one log stream until it ends or redirection is stopped. Returns - * whether the stream broke off and has to be opened again. A stream that ends without an error - * after it delivered data carried the whole log of a finished run. + * Forwards the messages of one log stream until it ends or redirection is stopped, and returns + * how it ended. A stream that ends without an error after it delivered data carried the whole log + * of a finished run. */ - private boolean redirectLogStream(InputStream stream) { + private StreamEnd redirectLogStream(InputStream stream) { // Bytes after the last newline, kept for the next read so that a message split across chunks, // even in the middle of a UTF-8 sequence, is not corrupted. Declared outside the try so the // final flush can emit it. @@ -408,8 +431,7 @@ private boolean redirectLogStream(InputStream stream) { // Decoded text not yet split into complete messages. Local, so overlapping readers never share // it. StringBuilder pending = new StringBuilder(); - boolean brokeOff = false; - heldBack = ""; + StreamEnd end = StreamEnd.ENDED; // The reader owns the stream and closes it on exit; stop() may close it first to end a read. try (InputStream liveStream = stream) { byte[] readBuffer = new byte[READ_BUFFER_BYTES]; @@ -439,10 +461,14 @@ private boolean redirectLogStream(InputStream stream) { if (!stopLogging) { if (replayCaughtUp()) { LOG.debug("Log stream broke off, reopening it", e); - prepareReopen(); + // A stream that has caught up with the replay holds back a message after the last + // redirected + // one, so it is not one that was redirected before. heldBack = pending.toString(); - brokeOff = true; + prepareReopen(); + end = StreamEnd.BROKE_OFF; } else { + end = StreamEnd.REPLAY_INCOMPLETE; LOG.warn( "Log redirection stopped: the reopened log stream broke off again before it reached" + " the last redirected message", @@ -453,11 +479,11 @@ private boolean redirectLogStream(InputStream stream) { // Flush on stream end and on a stop mid-read: emitMessages holds back the last message and a // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke // off, since its held-back message comes again when the log is replayed. - if (!brokeOff && !forwardingFailed) { + if (end != StreamEnd.BROKE_OFF && !forwardingFailed) { emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true); } } - return brokeOff; + return end; } /** @@ -518,7 +544,9 @@ private boolean isReplayed(Instant logTime) { replaySkipCount--; return true; } + // A message after the last redirected one: the stream delivers what the broken one held back. replayedUntil = null; + heldBack = ""; return false; } diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index b4d8692..7b2d5cf 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -649,10 +649,9 @@ private static List redirectUntil( @Test void reopensAStreamThatBrokeOffAndSkipsTheMessagesItAlreadyRedirected() { - // A stream cut off while the run goes on is reopened. The reopened stream replays the whole - // log, - // so the messages redirected before the break must not come again, and the held-back last - // message of the broken stream is redirected once, from the reopened one. + // A stream cut off while the run goes on is reopened. The reopened stream replays the log from + // its start, so the messages redirected before the break must not come again, and the + // held-back last message of the broken stream is redirected once, from the reopened one. MockTransport backend = MockTransport.ofConstant(200, ""); backend.scriptStream( 200, @@ -699,18 +698,21 @@ void aReopenSkipsOnlyAsManyMessagesAsItRedirectedAtTheSharedTimestamp() { @Test void aReopenedStreamThatBreaksOffBeforeTheLastRedirectedMessageEndsTheRedirection() throws InterruptedException { - // The first stream redirected A and B. The reopened one breaks off after A, before it replayed - // B, so continuing would skip log lines: redirection stops instead of reopening again. - MockTransport backend = MockTransport.ofConstant(200, ""); - backend.scriptStream( - 200, - new BrokenStream( - "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n")); + // The first stream redirected A and B and held C back. The reopened one breaks off after A, + // before it replayed B, so reopening again could skip log lines: the redirection reads the log + // once, which delivers C, and ends without a third stream. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); List collected = redirect(backend, new StreamedLogOptions()); - assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); - assertEquals(2, backend.calls, "no third open"); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + assertEquals(3, backend.calls, "two streams and one read of the log"); } @Test @@ -848,6 +850,133 @@ void aRestartRedirectsTheWholeLogEvenAfterAStopDuringAReopen() throws Interrupte assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); } + @Test + void stopAfterTheReplayCaughtUpDoesNotRedirectTheLastMessageTwice() { + // The reopened stream replayed A and B, up to the last redirected message, and then stalls. + // Stopping reads the whole log once: B must not come a second time, and C must. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = + new BlockingStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void stopAfterTheReplayUsedPartOfTheSkipCountDoesNotRepeatMessagesOfTheSameMillisecond() { + // B1 and B2 share a millisecond. The reopened stream replayed only B1 before it stalled, so the + // read of the whole log at the stop must still skip both. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B1\n" + + "2999-01-01T00:00:01.000Z B2\n2999-01-01T00:00:02.000Z C\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B1\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B1", + "2999-01-01T00:00:01.000Z B2", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aHeldBackMessageThatSharesAMillisecondWithTheLastRedirectedOneIsStillRedirected() { + // C was held back and shares B's millisecond. With the reopen and the read of the log both + // failing, the held-back C must not be taken for a replay of B. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:01.000Z C\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:01.000Z C"), + collected); + } + + @Test + void stopWhileAReopenedStreamIsReplayingRedirectsTheHeldBackMessageWhenTheLogCannotBeRead() { + // The reopened stream stalls after A, before the held-back C, and reading the log fails: the + // held-back message of the first stream is still redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream("2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRestartDoesNotSkipMessagesBecauseOfWhatThePreviousRedirectionSent() + throws InterruptedException { + // The first redirection sent A. After a restart, the stream holds A back and breaks off. The + // replay filter must not be built from the first redirection's A, which would drop it. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n"); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + streamedLog.stop(); + collected.clear(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 08c9f5207fcd89ed2a98dee7c37c9227793af917 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 11:13:51 +0000 Subject: [PATCH 11/19] fix: keep the held-back log message and skip a truncated copy of it A replay that is cut short no longer redirects the start of the next message, since the log is read in full afterwards. A stream that breaks before any message keeps the earlier held-back one. Comments and the resume docs are reworded. --- docs/runs.md | 15 +++-- .../com/apify/client/log/StreamedLog.java | 22 +++--- .../com/apify/client/StreamedLogTest.java | 67 ++++++++++++++++++- 3 files changed, 87 insertions(+), 17 deletions(-) diff --git a/docs/runs.md b/docs/runs.md index 0672975..203baa0 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -79,13 +79,14 @@ Actor name and run id (looked up automatically). `StreamedLogOptions` customizes If the log stream is cut off while the run is still going, for example because the run has logged nothing for several minutes, `StreamedLog` reopens it and continues after the last redirected message. The API cannot continue a log stream from a given point, so the reopened stream replays -the whole log, and the messages already redirected are skipped. `StreamedLog.getLastRedirectedAt()` -returns the timestamp of the last message redirected since the latest `start()` (empty before the -first one); read it after -`stop()` or `close()`, which deliver the last message. To continue a redirection in another -process, for example after the Actor that redirects the log reboots, save it and pass it to -`since`. So with the saved timestamp itself, messages logged in the same millisecond come again, and -with one millisecond added, those not redirected yet are dropped. +the whole log, and the messages already redirected are skipped. + +`StreamedLog.getLastRedirectedAt()` returns the timestamp of the last message redirected since the +latest `start()` (empty before the first one); read it after `stop()` or `close()`, which deliver +the last message. To continue a redirection in another process, for example after the Actor that +redirects the log reboots, save it and pass it to `since`. With the saved timestamp itself, +messages logged in the same millisecond come again, and with one millisecond added, those not +redirected yet are dropped. ```java RunClient runClient = client.run("RUN_ID"); diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 4ef2643..c8e492b 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -111,9 +111,9 @@ public final class StreamedLog implements AutoCloseable { private int replaySkipCount; /** - * The last message that a broken stream had received but held back, as it may still have been - * growing, and that no stream has redirected since. Empty when there is none. Used when the log - * cannot be read again. + * The complete lines of the last message a broken stream held back, as it may still have been + * growing. Cleared once a stream redirects a later message. Used when the log cannot be read + * again. */ private String heldBack = ""; @@ -461,10 +461,11 @@ private StreamEnd redirectLogStream(InputStream stream) { if (!stopLogging) { if (replayCaughtUp()) { LOG.debug("Log stream broke off, reopening it", e); - // A stream that has caught up with the replay holds back a message after the last - // redirected - // one, so it is not one that was redirected before. - heldBack = pending.toString(); + // Caught up, so a held-back message has not been redirected yet. A stream that broke off + // before it held one back leaves the earlier one in place. + if (pending.length() > 0) { + heldBack = pending.toString(); + } prepareReopen(); end = StreamEnd.BROKE_OFF; } else { @@ -480,7 +481,12 @@ private StreamEnd redirectLogStream(InputStream stream) { // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke // off, since its held-back message comes again when the log is replayed. if (end != StreamEnd.BROKE_OFF && !forwardingFailed) { - emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true); + // A replay that is cut short has only the start of the next message in lineRemainder. The + // log is read in full afterwards, so redirecting that start would send a truncated copy. + boolean replayCutShort = + replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging); + String rest = replayCutShort ? "" : new String(lineRemainder, StandardCharsets.UTF_8); + emitMessages(pending, rest, true); } } return end; diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index 7b2d5cf..a5879ce 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -699,8 +699,9 @@ void aReopenSkipsOnlyAsManyMessagesAsItRedirectedAtTheSharedTimestamp() { void aReopenedStreamThatBreaksOffBeforeTheLastRedirectedMessageEndsTheRedirection() throws InterruptedException { // The first stream redirected A and B and held C back. The reopened one breaks off after A, - // before it replayed B, so reopening again could skip log lines: the redirection reads the log - // once, which delivers C, and ends without a third stream. + // before it replayed B. A stream that keeps breaking off before it catches up would reopen + // without end, as the reference client avoids too, so the redirection reads the log once, + // which delivers C, and ends without a third stream. MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); backend.scriptStream(200, new BrokenStream(LOG_ABC)); backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); @@ -977,6 +978,68 @@ void aRestartDoesNotSkipMessagesBecauseOfWhatThePreviousRedirectionSent() assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); } + @Test + void aReplayCutOffInsideTheHeldBackMessageDoesNotRedirectATruncatedCopy() + throws InterruptedException { + // The first stream redirected A and B and held C back. The reopened stream breaks off in the + // middle of C, so only the start of it arrived. The read of the log delivers the whole C. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cf")); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z Cfull"), + collected); + } + + @Test + void aStopInsideTheHeldBackMessageOfAReplayDoesNotRedirectATruncatedCopy() { + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cf"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z Cfull"), + collected); + } + + @Test + void aReopenedStreamThatBreaksBeforeAnyMessageKeepsTheHeldBackMessage() { + // A was held back by the first stream. The second one breaks off before it delivers anything, + // and then the reopen and the read of the log fail, so the held-back A is all that is left. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, new BrokenStream("")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 1); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 885f3d1e008b7a3f2a3cb656dd91c863482c1662 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 11:33:13 +0000 Subject: [PATCH 12/19] fix: read the log instead of flushing a replay that was cut short The final flush of a replay that broke off or was stopped before it caught up is skipped, so the message after the last redirected one is neither lost nor sent truncated, including a multi-line one. The read of the whole log delivers it. --- .../com/apify/client/log/StreamedLog.java | 9 +-- .../com/apify/client/StreamedLogTest.java | 63 ++++++++++++++++++- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index c8e492b..64f0c77 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -481,12 +481,13 @@ private StreamEnd redirectLogStream(InputStream stream) { // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke // off, since its held-back message comes again when the log is replayed. if (end != StreamEnd.BROKE_OFF && !forwardingFailed) { - // A replay that is cut short has only the start of the next message in lineRemainder. The - // log is read in full afterwards, so redirecting that start would send a truncated copy. + // A replay that is cut short is not flushed: the log is read in full afterwards, and what + // arrived so far ends in the middle of a message, which would be sent truncated. boolean replayCutShort = replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging); - String rest = replayCutShort ? "" : new String(lineRemainder, StandardCharsets.UTF_8); - emitMessages(pending, rest, true); + if (!replayCutShort) { + emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true); + } } } return end; diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index a5879ce..02b4415 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -700,8 +700,8 @@ void aReopenedStreamThatBreaksOffBeforeTheLastRedirectedMessageEndsTheRedirectio throws InterruptedException { // The first stream redirected A and B and held C back. The reopened one breaks off after A, // before it replayed B. A stream that keeps breaking off before it catches up would reopen - // without end, as the reference client avoids too, so the redirection reads the log once, - // which delivers C, and ends without a third stream. + // without end. The redirection reads the log once instead, which delivers C, and ends without + // a third stream. MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); backend.scriptStream(200, new BrokenStream(LOG_ABC)); backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); @@ -1040,6 +1040,65 @@ void aReopenedStreamThatBreaksBeforeAnyMessageKeepsTheHeldBackMessage() { assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); } + @Test + void aStopAfterTheReplayPassedTheHeldBackMessageDoesNotLoseTheNextOne() { + // The reopened stream replayed A, B and C and has only the start of D when it is stopped. D is + // not redirected truncated, and not lost: the read of the log delivers it whole. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n" + + "2999-01-01T00:00:03.000Z Dfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream(LOG_ABC + "2999-01-01T00:00:03.000Z Df"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C", + "2999-01-01T00:00:03.000Z Dfull"), + collected); + } + + @Test + void aStopInsideAMultiLineHeldBackMessageRedirectsItWhole() { + // C spans two lines. The reopened stream is stopped after its first line, so the read of the + // log delivers both. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n" + + "line2\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 22552ff3773cc36706b61b98341da7a963093a39 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 11:48:46 +0000 Subject: [PATCH 13/19] fix: keep the fuller held-back message when a cut-short replay cannot read the log redirectLogStream now reports a cut-short replay once, as REPLAY_INCOMPLETE, and streamLog reads the log on that result alone. The held-back message is taken from the replay when it passed the last redirected message. --- .../com/apify/client/log/StreamedLog.java | 24 ++++++++----- .../com/apify/client/StreamedLogTest.java | 34 ++++++++++++++++++- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 64f0c77..ebc17da 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -376,9 +376,7 @@ private void streamLog() { } end = redirectLogStream(stream); } - if (replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging)) { - // A reopened stream was stopped or broke off again while it was still replaying messages that - // were already redirected, so the messages after them have not been delivered. + if (end == StreamEnd.REPLAY_INCOMPLETE) { redirectRemainingLog(); } } @@ -391,7 +389,10 @@ private enum StreamEnd { * The stream broke off, and a reopened one has to continue after the last redirected message. */ BROKE_OFF, - /** A reopened stream broke off again before it replayed up to the last redirected message. */ + /** + * A reopened stream was stopped or broke off again before it delivered a message after the last + * redirected one, so the messages after it have to be read from the whole log. + */ REPLAY_INCOMPLETE } @@ -481,11 +482,16 @@ private StreamEnd redirectLogStream(InputStream stream) { // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke // off, since its held-back message comes again when the log is replayed. if (end != StreamEnd.BROKE_OFF && !forwardingFailed) { - // A replay that is cut short is not flushed: the log is read in full afterwards, and what - // arrived so far ends in the middle of a message, which would be sent truncated. - boolean replayCutShort = - replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging); - if (!replayCutShort) { + if (replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging)) { + // A replay cut short is not flushed: that would end the replay filter at the next + // message, and the caller would not read the log, losing what follows. If the replay got + // past the last redirected message, the held-back one is fuller here than in the broken + // stream. + end = StreamEnd.REPLAY_INCOMPLETE; + if (replayCaughtUp() && pending.length() > 0) { + heldBack = pending.toString(); + } + } else { emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true); } } diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index 02b4415..909d65f 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -1043,7 +1043,7 @@ void aReopenedStreamThatBreaksBeforeAnyMessageKeepsTheHeldBackMessage() { @Test void aStopAfterTheReplayPassedTheHeldBackMessageDoesNotLoseTheNextOne() { // The reopened stream replayed A, B and C and has only the start of D when it is stopped. D is - // not redirected truncated, and not lost: the read of the log delivers it whole. + // neither redirected truncated nor lost: the read of the log delivers it whole. String log = "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n" + "2999-01-01T00:00:03.000Z Dfull\n"; @@ -1099,6 +1099,38 @@ void aStopInsideAMultiLineHeldBackMessageRedirectsItWhole() { collected); } + @Test + void aCutShortReplayThatPassedTheHeldBackMessageKeepsItsFullerCopyWhenTheLogCannotBeRead() { + // The first stream held back the first line of C. The reopened stream got the second line too + // before it was stopped, and reading the log fails, so the fuller copy is what is redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n")); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n" + + "line2\n2999-01-01T00:00:03.000Z Df"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 53d68cbe086843f7b6750896c11abf59ef34e7d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:05:51 +0000 Subject: [PATCH 14/19] fix: keep the longest copy of the held-back log message A reopened stream that is cut short earlier than the broken one no longer replaces its copy of the held-back message with a shorter one. --- .../com/apify/client/log/StreamedLog.java | 33 ++++++----- .../com/apify/client/StreamedLogTest.java | 55 +++++++++++++++++++ 2 files changed, 74 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index ebc17da..013934f 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -111,9 +111,9 @@ public final class StreamedLog implements AutoCloseable { private int replaySkipCount; /** - * The complete lines of the last message a broken stream held back, as it may still have been - * growing. Cleared once a stream redirects a later message. Used when the log cannot be read - * again. + * The complete lines of the last message that streams held back, the longest copy of it, as the + * message may still have been growing. Cleared once a stream redirects a later message. Used when + * the log cannot be read again. */ private String heldBack = ""; @@ -399,7 +399,7 @@ private enum StreamEnd { /** * Redirects what a broken stream did not deliver, when no reopened stream will: reads the whole * log once and passes it through the replay filter, which skips the messages already redirected. - * If the log cannot be read, the held-back message of the broken stream is redirected instead. + * If the log cannot be read, the held-back message is redirected instead. */ private void redirectRemainingLog() { if (forwardingFailed) { @@ -462,11 +462,8 @@ private StreamEnd redirectLogStream(InputStream stream) { if (!stopLogging) { if (replayCaughtUp()) { LOG.debug("Log stream broke off, reopening it", e); - // Caught up, so a held-back message has not been redirected yet. A stream that broke off - // before it held one back leaves the earlier one in place. - if (pending.length() > 0) { - heldBack = pending.toString(); - } + // Caught up, so a held-back message has not been redirected yet. + rememberHeldBack(pending); prepareReopen(); end = StreamEnd.BROKE_OFF; } else { @@ -484,12 +481,10 @@ private StreamEnd redirectLogStream(InputStream stream) { if (end != StreamEnd.BROKE_OFF && !forwardingFailed) { if (replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging)) { // A replay cut short is not flushed: that would end the replay filter at the next - // message, and the caller would not read the log, losing what follows. If the replay got - // past the last redirected message, the held-back one is fuller here than in the broken - // stream. + // message, and the caller would not read the log, losing what follows. end = StreamEnd.REPLAY_INCOMPLETE; - if (replayCaughtUp() && pending.length() > 0) { - heldBack = pending.toString(); + if (replayCaughtUp()) { + rememberHeldBack(pending); } } else { emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true); @@ -534,6 +529,16 @@ private InputStream openStreamUnlessStopped() { return opened; } + /** + * Keeps the held-back message of a stream if it is longer than the one kept. A stream can be cut + * short earlier than the one before it, so a later copy is not always the fuller one. + */ + private void rememberHeldBack(StringBuilder pending) { + if (pending.length() > heldBack.length()) { + heldBack = pending.toString(); + } + } + /** Makes the reopened stream redirect only the messages after the last redirected one. */ private void prepareReopen() { replayedUntil = lastRedirectedAt; diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index 909d65f..4f8c441 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -1131,6 +1131,61 @@ void aCutShortReplayThatPassedTheHeldBackMessageKeepsItsFullerCopyWhenTheLogCann collected); } + @Test + void aCutShortReplayKeepsTheLongerHeldBackMessageWhenTheLogCannotBeRead() { + // The first stream held back both lines of C. The reopened stream is stopped after the first + // line of C and part of the second, so the first stream's copy stays. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nline2\n")); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nli"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + + @Test + void aReopenedStreamThatBreaksOffShorterKeepsTheLongerHeldBackMessage() { + // The second stream breaks off after the first line of C, while the first one had both lines. + // The reopen and the read of the log then fail, so the longer copy is redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nline2\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 0f4a5c74a7472b67c023dba3ade5e8a689fc2d2c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:22:50 +0000 Subject: [PATCH 15/19] fix: forget the held-back log message once a later one is redirected A held-back message that a later stream redirected, or a later message that followed it, is no longer sent again when the log cannot be read. The held-back copy is cleared after every redirected message. --- .../java/com/apify/client/log/StreamedLog.java | 10 ++++++---- .../java/com/apify/client/StreamedLogTest.java | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 013934f..5021808 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -530,8 +530,9 @@ private InputStream openStreamUnlessStopped() { } /** - * Keeps the held-back message of a stream if it is longer than the one kept. A stream can be cut - * short earlier than the one before it, so a later copy is not always the fuller one. + * Remembers the held-back message of a stream, unless the one remembered is longer. Both are + * copies of the same message, since a redirected message clears the remembered one, and a stream + * can be cut off earlier than the stream before it, so a later copy is not always the fuller one. */ private void rememberHeldBack(StringBuilder pending) { if (pending.length() > heldBack.length()) { @@ -562,9 +563,7 @@ private boolean isReplayed(Instant logTime) { replaySkipCount--; return true; } - // A message after the last redirected one: the stream delivers what the broken one held back. replayedUntil = null; - heldBack = ""; return false; } @@ -711,6 +710,9 @@ private void emitIfRelevant(String message, String timestamp) { LOG.warn("Log redirection stopped due to error", e); return; } + // Messages are redirected in order, so a held-back message is either this one or an older one + // that no longer matters. + heldBack = ""; if (logTime != null) { rememberRedirected(logTime); } diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index 4f8c441..1abb1c9 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -1186,6 +1186,24 @@ void aReopenedStreamThatBreaksOffShorterKeepsTheLongerHeldBackMessage() { collected); } + @Test + void aHeldBackMessageThatWasRedirectedLaterIsNotRedirectedAgain() { + // A was held back by the first stream. The second stream redirects A and B and holds C back, + // and then the reopen and the read of the log fail: C is redirected, and A is not sent again. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 4b73f8c1bd0242ba37984f59187321ec4ee67639 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:45:39 +0000 Subject: [PATCH 16/19] ci: do not create GitHub deployments for the tests environment --- .github/workflows/java-integration-tests.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-integration-tests.yml b/.github/workflows/java-integration-tests.yml index 0e381cd..6b74a4d 100644 --- a/.github/workflows/java-integration-tests.yml +++ b/.github/workflows/java-integration-tests.yml @@ -28,8 +28,11 @@ permissions: jobs: test: runs-on: ubuntu-latest - # APIFY_TOKEN is an environment secret of the `tests` environment. - environment: tests + # APIFY_TOKEN is an environment secret of the `tests` environment, which does not create + # deployments. + environment: + name: tests + deployment: false steps: - name: Checkout uses: actions/checkout@v4.4.0 From 2fa5a09fe51e671e9dfbf72b6c2a150375617c2c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:45:39 +0000 Subject: [PATCH 17/19] fix: replace a held-back log message that is not a copy of the new one The held-back message is replaced unless the new copy is a prefix of it, and only a message with a parsed timestamp clears it, since one without may be sent again by a reopened stream. --- .../com/apify/client/log/StreamedLog.java | 21 ++++---- .../com/apify/client/StreamedLogTest.java | 54 +++++++++++++++++++ 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 5021808..51cc970 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -112,8 +112,8 @@ public final class StreamedLog implements AutoCloseable { /** * The complete lines of the last message that streams held back, the longest copy of it, as the - * message may still have been growing. Cleared once a stream redirects a later message. Used when - * the log cannot be read again. + * message may still have been growing. Cleared when a message with a timestamp is redirected. + * Used when the log cannot be read again. */ private String heldBack = ""; @@ -530,13 +530,14 @@ private InputStream openStreamUnlessStopped() { } /** - * Remembers the held-back message of a stream, unless the one remembered is longer. Both are - * copies of the same message, since a redirected message clears the remembered one, and a stream - * can be cut off earlier than the stream before it, so a later copy is not always the fuller one. + * Remembers the held-back message of a stream, unless the one remembered is a longer copy of it. + * A stream can be cut off earlier than the stream before it, so the later copy can be the shorter + * one: it is a prefix of the remembered one. Any other text is another message and replaces it. */ private void rememberHeldBack(StringBuilder pending) { - if (pending.length() > heldBack.length()) { - heldBack = pending.toString(); + String copy = pending.toString(); + if (!heldBack.startsWith(copy)) { + heldBack = copy; } } @@ -710,10 +711,10 @@ private void emitIfRelevant(String message, String timestamp) { LOG.warn("Log redirection stopped due to error", e); return; } - // Messages are redirected in order, so a held-back message is either this one or an older one - // that no longer matters. - heldBack = ""; if (logTime != null) { + // Messages are redirected in order, so a held-back message is either this one or an older one + // that no longer matters. A message without a timestamp may be a repeat, so it keeps it. + heldBack = ""; rememberRedirected(logTime); } } diff --git a/src/test/java/com/apify/client/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index 1abb1c9..216191a 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -1204,6 +1204,60 @@ void aHeldBackMessageThatWasRedirectedLaterIsNotRedirectedAgain() { collected); } + @Test + void aTwoLineHeldBackMessageThatWasRedirectedLaterIsNotRedirectedAgain() { + // As the single-line case: the first stream held back both lines of A, the second one redirects + // A with B and holds C back, and then the reopen and the read of the log fail. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A line1\nline2\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A line1\nline2\n2999-01-01T00:00:01.000Z B\n" + + "2999-01-01T00:00:02.000Z C\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A line1\nline2", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRepeatedMessageWithAnUnparsableTimestampKeepsTheLongerHeldBackMessage() { + // The timestamp of X has the right shape but is not a date, so the replay filter cannot tell + // that X was redirected before, and the reopened stream sends it again. That must not discard + // the fuller copy of the held-back C. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + String head = "2999-01-01T00:00:00.000Z A\n2999-99-01T00:00:00.000Z X\n"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(head + "2999-01-01T00:00:02.000Z C line1\nline2\n")); + backend.scriptStream(200, new BrokenStream(head + "2999-01-01T00:00:02.000Z C line1\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals("2999-01-01T00:00:02.000Z C line1\nline2", collected.get(collected.size() - 1)); + } + + @Test + void aHeldBackMessageWithoutAParsableTimestampIsReplacedByALaterOne() { + // X was held back, and its timestamp is not a date, so redirecting it does not clear the copy. + // The second stream redirects X again and holds back Z: Z must be the one that is left. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-99-01T00:00:00.000Z XXXXXXXXXXXX\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-99-01T00:00:00.000Z XXXXXXXXXXXX\n2999-99-01T00:00:01.000Z Y\n" + + "2999-99-01T00:00:02.000Z Z\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals("2999-99-01T00:00:02.000Z Z", collected.get(collected.size() - 1)); + } + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ private static List redirect(MockTransport backend, StreamedLogOptions options) throws InterruptedException { From 072080d6854fa689d2d1340398974f2a809447ea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:04:28 +0000 Subject: [PATCH 18/19] docs: state when the held-back log message is cleared --- src/main/java/com/apify/client/log/StreamedLog.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 51cc970..3f856d1 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -112,8 +112,8 @@ public final class StreamedLog implements AutoCloseable { /** * The complete lines of the last message that streams held back, the longest copy of it, as the - * message may still have been growing. Cleared when a message with a timestamp is redirected. - * Used when the log cannot be read again. + * message may still have been growing. Cleared when a message with a valid timestamp is + * redirected. Used when the log cannot be read again. */ private String heldBack = ""; @@ -713,7 +713,8 @@ private void emitIfRelevant(String message, String timestamp) { } if (logTime != null) { // Messages are redirected in order, so a held-back message is either this one or an older one - // that no longer matters. A message without a timestamp may be a repeat, so it keeps it. + // that no longer matters. A message without a valid timestamp does not clear it: the replay + // filter cannot recognise such a message, so a reopened stream sends it again. heldBack = ""; rememberRedirected(logTime); } From 29de7ec29d8aa5e32e5afddfe35ace5aa055b292 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:15:22 +0000 Subject: [PATCH 19/19] docs: use US spelling in a StreamedLog comment --- src/main/java/com/apify/client/log/StreamedLog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/apify/client/log/StreamedLog.java b/src/main/java/com/apify/client/log/StreamedLog.java index 3f856d1..5b78c6c 100644 --- a/src/main/java/com/apify/client/log/StreamedLog.java +++ b/src/main/java/com/apify/client/log/StreamedLog.java @@ -714,7 +714,7 @@ private void emitIfRelevant(String message, String timestamp) { if (logTime != null) { // Messages are redirected in order, so a held-back message is either this one or an older one // that no longer matters. A message without a valid timestamp does not clear it: the replay - // filter cannot recognise such a message, so a reopened stream sends it again. + // filter cannot recognize such a message, so a reopened stream sends it again. heldBack = ""; rememberRedirected(logTime); }