diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e0c02..326e37e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ 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`. +- `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 + +- **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. + +### Deprecated + +- `StoreListOptions.sortBy`: the API ignores it. + ## [0.14.1] - 2026-11-20 ### Changed diff --git a/README.md b/README.md index 5b0f45f..ecc53e6 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' } ``` @@ -308,15 +308,16 @@ 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. | +| `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 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). @@ -437,7 +438,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..f3e08ed 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,13 +48,13 @@ 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` | | `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..938e4e0 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. @@ -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, 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)` @@ -232,14 +233,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..518d54f 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -7,30 +7,46 @@ 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), `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, 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()`, -`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)). @@ -94,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 552dbeb..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`. | @@ -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. 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. | | `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..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`. | +| `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/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/ActorClient.java b/src/main/java/com/apify/client/actor/ActorClient.java index 65c8572..749b04b 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 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/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/ActorServerClient.java b/src/main/java/com/apify/client/actor/ActorServerClient.java index bbf9590..8fe2899 100644 --- a/src/main/java/com/apify/client/actor/ActorServerClient.java +++ b/src/main/java/com/apify/client/actor/ActorServerClient.java @@ -11,6 +11,7 @@ import com.apify.client.internal.QueryParams; import com.apify.client.internal.RequestPolicy; import com.apify.client.internal.ResourceContext; +import java.io.InputStream; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; @@ -209,19 +210,31 @@ public CompletableFuture> getOpenApiSpec(Timeout timeout) { */ public CompletableFuture request(String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); - byte[] body = Json.toRequestBody(opts.bodyValue()); + RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); + 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, - RequestPolicy.server(opts.compressionValue()))); + 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}. */ @@ -246,24 +259,47 @@ public CompletableFuture request() { public CompletableFuture requestStream( String path, ActorServerRequestOptions options) { ActorServerRequestOptions opts = options != null ? options : new ActorServerRequestOptions(); - byte[] body = Json.toRequestBody(opts.bodyValue()); + RequestPolicy policy = RequestPolicy.server(opts.compressionValue()); + InputStream stream = opts.bodyValue() instanceof InputStream in ? in : null; + byte[] body = stream == null ? Json.toRequestBody(opts.bodyValue()) : null; return getUrl() .thenCompose( serverUrl -> - http.streamRequest( - opts.methodValue(), - requestUrl(serverUrl, path, opts), - body, - contentTypeOf(opts), - opts.headersValue(), - opts.timeoutValue(), - RequestPolicy.server(opts.compressionValue()))) + 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 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) { + HttpClientCore.closeQuietly(stream); + } + } + /** Fetches the Actor and checks that it is a Server Actor. */ private CompletableFuture fetchServerActor(Timeout timeout) { return ctx.getResourceRequired("", new QueryParams(), Actor.class, timeout) @@ -394,7 +430,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..d96cdcc 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 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/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/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/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..1cd4fed 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, and key-value store + * record streaming). The caller closes the stream. Completes exceptionally the same way as {@link + * #sendAsync(HttpRequest)}. */ CompletableFuture> sendStreamingAsync(HttpRequest request); @@ -44,12 +45,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 +81,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 0e5c685..0a1b2e2 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,56 @@ 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, compressed, + * 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, + 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) + .whenComplete((response, error) -> closeQuietly(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(); + 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) {} @@ -397,7 +448,7 @@ private PreparedBody prepareBody( private CompletableFuture attemptWithRetry( String method, String url, - byte[] body, + HttpRequest.BodyPublisher body, String contentType, Map headers, Duration baseTimeout, @@ -458,7 +509,7 @@ private record AttemptOutcome( private CompletableFuture attempt( String method, String url, - byte[] body, + HttpRequest.BodyPublisher body, String contentType, Map extraHeaders, Duration timeout, @@ -527,10 +578,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 +639,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())); } @@ -831,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, 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, 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 once the retries run out. */ public CompletableFuture> streamRequest( String method, @@ -877,6 +933,35 @@ 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, 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, + 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()) + .whenComplete((response, error) -> closeQuietly(body)); + } + /** * 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. @@ -901,14 +986,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)) @@ -924,7 +1021,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( @@ -951,17 +1068,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, - * dataset export streaming) so the drain-and-throw logic lives in one place. + * 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 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<>(); - 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); @@ -970,12 +1088,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()); } @@ -983,7 +1095,8 @@ public CompletableFuture streamOrThrow(String url) { 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/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..6bb591d 100644 --- a/src/main/java/com/apify/client/internal/RequestPolicy.java +++ b/src/main/java/com/apify/client/internal/RequestPolicy.java @@ -71,4 +71,20 @@ public static RequestPolicy server(HttpCompressor compressor) { /* compress= */ compressor != null, /* compressor= */ compressor); } + + /** + * 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( + authorizationHeader, + throwOnErrorStatus, + retryableStatus, + retryTransportErrors, + /* 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 a3dc385..6ff7c3e 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,44 @@ 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. Retries like any other request, throws on an + * 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) { + String u = mergedParams(params).applyToUrl(subUrl(subPath)); + return http.streamRequest("GET", u, (byte[]) null, null, null, Timeout.LONG, RequestPolicy.API) + .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 +555,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..4101428 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; @@ -54,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. * @@ -87,7 +89,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 +96,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..1475a65 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. 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 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)); + } + + /** 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 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()); + } + + /** + * 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/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/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..4b3ad50 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..02707c8 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/main/java/com/apify/client/task/TaskClient.java b/src/main/java/com/apify/client/task/TaskClient.java index 5206e66..db5b81d 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/ClientBehaviourRegressionTest.java b/src/test/java/com/apify/client/ClientBehaviourRegressionTest.java index 7c5c38f..75de210 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 @@ -1136,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/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..d0bfe64 --- /dev/null +++ b/src/test/java/com/apify/client/StreamBodyTest.java @@ -0,0 +1,576 @@ +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.DefaultHttpTransport; +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; +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.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; +import java.util.concurrent.atomic.AtomicInteger; +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; + + /** + * 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. + */ + 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/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/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\"}}"); + } + 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 setRecordDoesNotFollowARedirectWithAStream() { + CompletionException error = + assertThrows( + CompletionException.class, + () -> + client() + .keyValueStore("s1") + .setRecord("redirected", streamOf(new byte[] {1, 2, 3}), "text/plain") + .join()); + assertEquals(307, assertInstanceOf(ApifyApiException.class, rootOf(error)).getStatusCode()); + 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. */ + 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 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(); + 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 + 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 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(); + 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 -------------------------------------------------------------------- + + @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 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(); + 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/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/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(); 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();