From 54976b213d01dc86883cc6de948207a6a2669d47 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:45:05 +0000 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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);