diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e0c02..997227a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,42 @@ 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-12-03 + +### Added + +- `StoreCollectionClient.search`, with `StoreSearchOptions` and `StoreSearchResult`, for a Store search. It sends one request and completes with the Actors and the limit the API applied. +- `StoreFilterOptions`, the filters that `StoreListOptions` and `StoreSearchOptions` share. +- `StreamedLogOptions.since` and `StreamedLog.getLastRedirectedAt`, to redirect only the log lines from a given time and to continue a redirection later. +- `StoreActorStats`, the statistics of a Store Actor: `totalUsers`, `totalRuns`, `totalUsers7Days`, `totalUsers30Days`, `totalUsers90Days`, `actorReviewRating`, and `actorReviewCount`. +- `ActorStoreListItem` getters for `userFullName`, `categories`, `notice`, `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 + +- Updated to Apify OpenAPI specification `v2-2026-12-02T102104Z`. +- **Breaking:** `ActorStoreListItem.getStats()` returns `StoreActorStats` instead of `ActorStats`. The Store no longer returns `totalBuilds`, `totalMetamorphs`, and `lastRunStartedAt`. +- **Breaking:** the `StoreListOptions` filter setters (`category`, `username`, `pricingModel`, `includeUnrunnableActors`, `responseFormat`, `includeInputSchema`) now come from `StoreFilterOptions`. Code compiled against 0.14.x must be recompiled. +- **Breaking:** `StreamedLog` takes `since` instead of `fromStart`: `new StreamedLog(logClient, destination, since)`. +- A `StreamedLog` reopens a log stream that is cut off while the run is still going and continues after the last redirected message. +- `StoreListOptions.category` takes comma-separated category IDs. +- `LogClient.stream` and `DatasetClient.streamItems` retry the request like any other, until the response headers arrive. +- `ActorVersionCollectionClient.create` and `ActorVersionClient.update` use the long timeout tier, since a version can carry its source files. +- Documented that creating an Actor with a name you already use fails with a `ConflictError` (`actor-name-not-unique`). +- Documented that the build OpenAPI definition needs an API token with access to the build, unless the Actor is public or the build's owner allows anyone with the ID to read. +- Documented that a public storage URL grants read access to the whole storage, and that its options do not limit it. +- `ActorClient.validateInput` and `RunClient.metamorph` throw `IllegalArgumentException` for an `InputStream` input, instead of serializing it to JSON. + +### Removed + +- **Breaking:** `StoreListOptions.search`. Use `StoreCollectionClient.search`: the Store answers a search with one page of at most 100 Actors and ignores `offset`. +- **Breaking:** `StoreListOptions.sortBy`, which the API ignores. +- **Breaking:** `StreamedLogOptions.fromStart`. Use `StreamedLogOptions.since`: `fromStart(false)` becomes `since(Instant.now())`, and `fromStart(true)` is the default. +- **Breaking:** `StoreListOptions.allowsAgenticUsers` and `ActorStoreListItem.getIsWhiteListedForAgenticPayments`, which the API no longer has. + ## [0.14.1] - 2026-11-20 ### Changed diff --git a/README.md b/README.md index 5b0f45f..b10aa2f 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,10 +438,10 @@ 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 + and checked against (`v2-2026-12-02T102104Z`). It is a snapshot, not a live compatibility guarantee: the client keeps working against newer, backward-compatible spec revisions, but a feature added to the API after this snapshot has no corresponding method here yet. diff --git a/docs/README.md b/docs/README.md index 703a7fb..c92c5f2 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`, `StoreFilterOptions`, `StoreListOptions`, `StoreSearchOptions`, `StoreSearchResult`, `PricingInfo` | | `com.apify.client.log` | `LogClient`, `LogOptions`, `StreamedLog`, `StreamedLogOptions` | For example, the [top-level README's dataset snippet](../README.md#quick-start) needs diff --git a/docs/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/builds.md b/docs/builds.md index 8da32df..609e219 100644 --- a/docs/builds.md +++ b/docs/builds.md @@ -19,7 +19,7 @@ builds) and a single build with `client.build(id)`. | `abort()` | Abort the build. Completes with `Build`. | | `delete()` | Delete the build. | | `waitForFinish(Long waitSecs)` | Poll until the build finishes (`null` waits indefinitely); see [the run equivalent](runs.md#runclient) for its 404 handling. Completes with `Build`. | -| `getOpenApiDefinition()` | The build's OpenAPI definition. Completes with `Optional`. | +| `getOpenApiDefinition()` | The build's OpenAPI definition. Completes with `Optional`. It needs an API token with access to the build, unless the Actor is public or the build's owner has general resource access set to "Anyone with ID can read"; otherwise the API answers `401` or `403`. | | `log()` | A `LogClient` for the build's log. | `Build` fields: `getId()`, `getActId()`, `getUserId()`, `getStatus()`, `getStartedAt()`, diff --git a/docs/misc.md b/docs/misc.md index 65450de..eca32a2 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -2,35 +2,67 @@ ## Apify Store: `client.store()` -Browse public Actors in the Apify Store. `client.store()` returns a `StoreCollectionClient`. +Browse and search public Actors in Apify Store. `client.store()` returns a +`StoreCollectionClient`. The API serves the Store in two ways, and the client has a method for each: +`list` and `iterate` browse the whole Store in Store order, and `search` returns the Actors that +match a query best. | 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). | +| `search(StoreSearchOptions)` | The Actors that match a query best, best match first, as a single page. Completes with `StoreSearchResult`. | `StoreListOptions` fields: `offset` (number of Actors to skip), `limit` (maximum number of Actors to -return), `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), -`includeUnrunnableActors` (include Actors the current user cannot run), `allowsAgenticUsers` (only -Actors that allow agentic users), `responseFormat` (the response shape: `full` or `agent`). +return; the API default and maximum is 1000), and the filters below. The API has no option to change +the Store order. + +`StoreSearchOptions` takes the query in its constructor, which rejects a `null` or empty query, +since the API answers an empty query with the Store listing. Its fields are `limit` (maximum number +of Actors to return, a positive number; the API default and maximum is 100, and it reduces a larger +value to 100, except with `includeInputSchema`: see below) and the filters below. There is no +`offset`: the API ignores it for a search. + +Filters of both options types: `category` (filter by one or more category IDs such as `AI_AND_ML`, +comma-separated and case-insensitive; an Actor must match all of them, and an unknown category fails +with a `400` error), `username` (filter Actors by owner username), `pricingModel` (filter by pricing +model: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`), `includeUnrunnableActors` (by default, +the API leaves out Actors that are not safe to run automatically, such as Actors of developers who +have not passed identity verification; `true` includes them), `responseFormat` (the response shape: +`full`, the default, or `agent`, a reduced field set for LLM consumers with `id`, `title`, `name`, +`username`, `description`, `notice`, `badge`, `categories`, and minimal `stats`, so the other +getters of `ActorStoreListItem` return `null`), `includeInputSchema` (add each Actor's compact +`inputSchema`; the API then defaults `limit` to 10 and rejects a larger value with a `400` error). + +A search returns a single page of at most 100 Actors ranked by relevance. There is no next page, and +the API does not report how many Actors match. `StoreSearchResult` therefore has only `getItems()` +and `getLimit()`, the limit the API applied. When `getItems().size()` equals it, more Actors may +match than were returned, so narrow the search with a more specific query or with `category`, +`username`, or `pricingModel`. To go through the whole Store, use `list` or `iterate`. ```java // Publishers.collect() drains the whole publisher; fine here since `limit` already caps it. // 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. +StoreSearchResult found = + client.store().search(new StoreSearchOptions("crawler").limit(10L)).join(); +found.getItems().forEach(item -> System.out.println(item.getUsername() + "/" + item.getName())); ``` `ActorStoreListItem` fields: `getId()`, `getName()`, `getUsername()`, `getTitle()`, -`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()`), +`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 +126,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/runs.md b/docs/runs.md index 1be1d08..203baa0 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -73,8 +73,37 @@ Actor name and run id (looked up automatically). `StreamedLogOptions` customizes - `toLog(Consumer)`: send each complete message to your own consumer instead of the default logger. - `prefix(String)`: override the auto-built prefix used by the default logger. -- `fromStart(boolean)`: when `false`, skip log lines produced before redirection started - (default `true`). +- `since(Instant)`: redirect only the log lines logged at that time or later (default: the whole + log). This can be useful for long-running Actors, such as Server Actors. + +If the log stream is cut off while the run is still going, for example because the run has logged +nothing for several minutes, `StreamedLog` reopens it and continues after the last redirected +message. The API cannot continue a log stream from a given point, so the reopened stream replays +the whole log, and the messages already redirected are skipped. + +`StreamedLog.getLastRedirectedAt()` returns the timestamp of the last message redirected since the +latest `start()` (empty before the first one); read it after `stop()` or `close()`, which deliver +the last message. To continue a redirection in another process, for example after the Actor that +redirects the log reboots, save it and pass it to `since`. With the saved timestamp itself, +messages logged in the same millisecond come again, and with one millisecond added, those not +redirected yet are dropped. + +```java +RunClient runClient = client.run("RUN_ID"); +StreamedLog streamedLog = runClient.getStreamedLog().join(); +try (streamedLog) { + streamedLog.start().join(); + runClient.waitForFinish(120L).join(); +} +Instant lastRedirectedAt = streamedLog.getLastRedirectedAt().orElse(Instant.EPOCH); + +// Later, for example in another process, continue from that message. +StreamedLogOptions resumedOptions = new StreamedLogOptions().since(lastRedirectedAt); +try (StreamedLog resumed = runClient.getStreamedLog(resumedOptions).join()) { + resumed.start().join(); + runClient.waitForFinish(120L).join(); +} +``` A run that has not logged anything yet (e.g. still queued for resources, see [`waitForResources`](actors.md#actorclient)) serves its log as a stream that ends at once; @@ -97,7 +126,7 @@ waiting, and the reader ends once the consumer returns. `start()` throws until a RunClient runClient = client.run("RUN_ID"); List collected = new ArrayList<>(); try (StreamedLog streamedLog = - runClient.getStreamedLog(new StreamedLogOptions().toLog(collected::add).fromStart(true)).join()) { + runClient.getStreamedLog(new StreamedLogOptions().toLog(collected::add)).join()) { streamedLog.start().join(); runClient.waitForFinish(120L).join(); } diff --git a/docs/storages.md b/docs/storages.md index 552dbeb..5fc8e3d 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`. | @@ -115,6 +115,10 @@ request is sent. The expiry counts from the moment the URL is signed, after the optional `format` sets the serialization the URL serves items in (default `json` when omitted/`null`). +A public URL grants read access to the whole dataset (or, for `createKeysPublicUrl`, the full key +list) until it expires. The signature covers only the storage ID and the expiry: the options only +set the default shape of the response, and anyone holding the URL can change or drop them. + > **Public-URL limitation.** The public-URL builders > (`createItemsPublicUrl`, and the key-value-store `getRecordPublicUrl` / `createKeysPublicUrl`) > build the URL from the client's own resource path plus the signature. When called on a *last-run @@ -142,6 +146,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 +190,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/ApifyClient.java b/src/main/java/com/apify/client/ApifyClient.java index 5c4eb1c..8efba35 100644 --- a/src/main/java/com/apify/client/ApifyClient.java +++ b/src/main/java/com/apify/client/ApifyClient.java @@ -244,7 +244,7 @@ public WebhookDispatchClient webhookDispatch(String id) { // ----- Misc accessors ------------------------------------------------------ - /** A client for browsing the Apify Store. */ + /** A client for browsing Apify Store. */ public StoreCollectionClient store() { return new StoreCollectionClient(http, baseUrl); } diff --git a/src/main/java/com/apify/client/Version.java b/src/main/java/com/apify/client/Version.java index 0654df4..0d495b7 100644 --- a/src/main/java/com/apify/client/Version.java +++ b/src/main/java/com/apify/client/Version.java @@ -13,13 +13,13 @@ 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. * Corresponds to the {@code info.version} field of the Apify OpenAPI document. */ - public static final String API_SPEC_VERSION = "v2-2026-11-18T151559Z"; + public static final String API_SPEC_VERSION = "v2-2026-12-02T102104Z"; private Version() {} } diff --git a/src/main/java/com/apify/client/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/build/BuildClient.java b/src/main/java/com/apify/client/build/BuildClient.java index 4004234..ea8ea6f 100644 --- a/src/main/java/com/apify/client/build/BuildClient.java +++ b/src/main/java/com/apify/client/build/BuildClient.java @@ -60,6 +60,10 @@ public CompletableFuture waitForFinish(Long waitSecs) { /** * Returns the OpenAPI definition generated for the build, or empty if it is not available. The * result is the raw OpenAPI document. + * + *

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

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

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

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

When the log stream is cut off while the run is still going, for example because the run has + * logged nothing for several minutes, the stream is reopened and the redirection resumes after the + * last redirected message. The API cannot continue a log stream from a given point, so a reopened + * stream replays the whole log and the messages already redirected are skipped. {@link + * #getLastRedirectedAt()} reports the timestamp of the last redirected message, so a redirection + * can also be continued in another process. + * *

Typical use: * *

{@code
@@ -70,6 +78,13 @@ public final class StreamedLog implements AutoCloseable {
   /** Upper bound on the pause between reopens of an empty log stream. */
   private static final long EMPTY_STREAM_MAX_RETRY_MILLIS = 5_000;
 
+  /**
+   * Pause before reopening a log stream that broke off before its end. A stream that has carried no
+   * data for several minutes is cut off even though the run goes on, and fails with a read error.
+   * The stream of a finished log ends without one.
+   */
+  private static final long BROKEN_STREAM_REOPEN_MILLIS = 1_000;
+
   /** How long {@link #stop()} and {@link #close()} wait for a message in flight before closing. */
   private static final long STOP_GRACE_MILLIS = 1_000;
 
@@ -77,7 +92,30 @@ public final class StreamedLog implements AutoCloseable {
   private final Consumer destination;
 
   /** Messages older than this are dropped; {@code null} drops nothing. */
-  private final Instant relevancyTimeLimit;
+  private final Instant since;
+
+  /** Timestamp of the last redirected message; {@code null} until one is redirected. */
+  private volatile Instant lastRedirectedAt;
+
+  /**
+   * How many redirected messages carry {@link #lastRedirectedAt}: several can share a millisecond.
+   */
+  private int redirectedAtLastTimestamp;
+
+  /**
+   * A reopened stream replays the messages before this timestamp, and the first {@link
+   * #replaySkipCount} messages at it; {@code null} when there is nothing to skip.
+   */
+  private Instant replayedUntil;
+
+  private int replaySkipCount;
+
+  /**
+   * The complete lines of the last message that streams held back, the longest copy of it, as the
+   * message may still have been growing. Cleared when a message with a valid timestamp is
+   * redirected. Used when the log cannot be read again.
+   */
+  private String heldBack = "";
 
   private volatile boolean stopLogging;
 
@@ -100,10 +138,28 @@ public final class StreamedLog implements AutoCloseable {
    */
   private boolean closeRequested;
 
-  public StreamedLog(LogClient logClient, Consumer destination, boolean fromStart) {
+  /**
+   * Creates a log redirection that is not started yet.
+   *
+   * @param since redirect only the messages logged at this time or later; {@code null} redirects
+   *     the whole log
+   */
+  public StreamedLog(LogClient logClient, Consumer destination, Instant since) {
     this.logClient = logClient;
     this.destination = destination;
-    this.relevancyTimeLimit = fromStart ? null : Instant.now();
+    this.since = since;
+  }
+
+  /**
+   * The timestamp of the last message redirected since the latest {@link #start()}, or empty if
+   * nothing has been redirected yet. To continue the redirection in another process, pass this
+   * timestamp as {@link com.apify.client.log.StreamedLogOptions#since(Instant)}. The API cannot
+   * continue a log from an exact point, so with the timestamp itself, messages logged in the same
+   * millisecond come again, and with one millisecond added, those not redirected yet are dropped.
+   * Read it after {@link #stop()} or {@link #close()}, which deliver the last message.
+   */
+  public Optional getLastRedirectedAt() {
+    return Optional.ofNullable(lastRedirectedAt);
   }
 
   /**
@@ -133,6 +189,12 @@ public synchronized CompletableFuture start() {
     starting = true;
     stopLogging = false;
     forwardingFailed = false;
+    // A new redirection reads the log from its start, so nothing is skipped as replayed.
+    lastRedirectedAt = null;
+    redirectedAtLastTimestamp = 0;
+    replayedUntil = null;
+    replaySkipCount = 0;
+    heldBack = "";
     CancellableFuture started = new CancellableFuture<>();
     CompletableFuture opening = logClient.stream(new LogOptions().raw(true));
     // Cancelling the returned future cancels the stream-open request. The callback below hangs off
@@ -277,15 +339,11 @@ private void awaitStopped(StopHandle handle) {
     }
   }
 
-  /** Reads the live raw log stream and forwards complete messages to the destination. */
+  /**
+   * Reads the live raw log stream and forwards complete messages to the destination. A stream that
+   * breaks off after it delivered data is reopened.
+   */
   private void streamLog() {
-    // Bytes after the last newline, kept for the next read so that a message split across chunks,
-    // even in the middle of a UTF-8 sequence, is not corrupted. Declared outside the try so the
-    // final flush can emit it.
-    byte[] lineRemainder = new byte[0];
-    // Decoded text not yet split into complete messages. Local, so overlapping readers never share
-    // it.
-    StringBuilder pending = new StringBuilder();
     InputStream stream;
     try {
       // The API serves the log of a run that has not logged yet as a stream that ends at once.
@@ -302,13 +360,79 @@ private void streamLog() {
       try {
         String logContent = logClient.get(new LogOptions().raw(true)).join().orElse("");
         if (!forwardingFailed) {
-          emitMessages(pending, logContent, true);
+          emitMessages(new StringBuilder(), logContent, true);
         }
       } catch (RuntimeException e) {
         LOG.warn("Log redirection stopped due to error", e);
       }
       return;
     }
+    StreamEnd end = redirectLogStream(stream);
+    while (end == StreamEnd.BROKE_OFF) {
+      stream = reopenBrokenStream();
+      if (stream == null) {
+        redirectRemainingLog();
+        return;
+      }
+      end = redirectLogStream(stream);
+    }
+    if (end == StreamEnd.REPLAY_INCOMPLETE) {
+      redirectRemainingLog();
+    }
+  }
+
+  /** How a log stream ended. */
+  private enum StreamEnd {
+    /** The stream ended, or redirection was stopped. */
+    ENDED,
+    /**
+     * The stream broke off, and a reopened one has to continue after the last redirected message.
+     */
+    BROKE_OFF,
+    /**
+     * A reopened stream was stopped or broke off again before it delivered a message after the last
+     * redirected one, so the messages after it have to be read from the whole log.
+     */
+    REPLAY_INCOMPLETE
+  }
+
+  /**
+   * Redirects what a broken stream did not deliver, when no reopened stream will: reads the whole
+   * log once and passes it through the replay filter, which skips the messages already redirected.
+   * If the log cannot be read, the held-back message is redirected instead.
+   */
+  private void redirectRemainingLog() {
+    if (forwardingFailed) {
+      return;
+    }
+    // A stream that replayed part of the log may have used up some of the filter. Nothing new was
+    // redirected meanwhile, or the filter would be off, so it is built again from the last message.
+    prepareReopen();
+    try {
+      String logContent = logClient.get(new LogOptions().raw(true)).join().orElse("");
+      emitMessages(new StringBuilder(), logContent, true);
+    } catch (RuntimeException e) {
+      LOG.warn("Log redirection could not read the rest of the log", e);
+      // The held-back message was never redirected, so it must not go through the replay filter.
+      replayedUntil = null;
+      emitMessages(new StringBuilder(), heldBack, true);
+    }
+  }
+
+  /**
+   * Forwards the messages of one log stream until it ends or redirection is stopped, and returns
+   * how it ended. A stream that ends without an error after it delivered data carried the whole log
+   * of a finished run.
+   */
+  private StreamEnd redirectLogStream(InputStream stream) {
+    // Bytes after the last newline, kept for the next read so that a message split across chunks,
+    // even in the middle of a UTF-8 sequence, is not corrupted. Declared outside the try so the
+    // final flush can emit it.
+    byte[] lineRemainder = new byte[0];
+    // Decoded text not yet split into complete messages. Local, so overlapping readers never share
+    // it.
+    StringBuilder pending = new StringBuilder();
+    StreamEnd end = StreamEnd.ENDED;
     // The reader owns the stream and closes it on exit; stop() may close it first to end a read.
     try (InputStream liveStream = stream) {
       byte[] readBuffer = new byte[READ_BUFFER_BYTES];
@@ -334,16 +458,122 @@ private void streamLog() {
         }
       }
     } catch (IOException e) {
-      // A read error after an explicit stop is expected. Report only unsolicited failures.
+      // A read error after an explicit stop is expected. Any other one cut the stream off.
       if (!stopLogging) {
-        LOG.warn("Log redirection stopped due to error", e);
+        if (replayCaughtUp()) {
+          LOG.debug("Log stream broke off, reopening it", e);
+          // Caught up, so a held-back message has not been redirected yet.
+          rememberHeldBack(pending);
+          prepareReopen();
+          end = StreamEnd.BROKE_OFF;
+        } else {
+          end = StreamEnd.REPLAY_INCOMPLETE;
+          LOG.warn(
+              "Log redirection stopped: the reopened log stream broke off again before it reached"
+                  + " the last redirected message",
+              e);
+        }
       }
     } finally {
       // Flush on stream end and on a stop mid-read: emitMessages holds back the last message and a
-      // stop skips the loop body. Skipped once a consumer has thrown.
-      if (!forwardingFailed) {
-        emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true);
+      // stop skips the loop body. Skipped once a consumer has thrown, and for a stream that broke
+      // off, since its held-back message comes again when the log is replayed.
+      if (end != StreamEnd.BROKE_OFF && !forwardingFailed) {
+        if (replayedUntil != null && (end == StreamEnd.REPLAY_INCOMPLETE || stopLogging)) {
+          // A replay cut short is not flushed: that would end the replay filter at the next
+          // message, and the caller would not read the log, losing what follows.
+          end = StreamEnd.REPLAY_INCOMPLETE;
+          if (replayCaughtUp()) {
+            rememberHeldBack(pending);
+          }
+        } else {
+          emitMessages(pending, new String(lineRemainder, StandardCharsets.UTF_8), true);
+        }
+      }
+    }
+    return end;
+  }
+
+  /**
+   * Waits {@link #BROKEN_STREAM_REOPEN_MILLIS}, then opens the log stream again. Returns {@code
+   * null} if redirection was stopped meanwhile or the stream could not be opened.
+   */
+  private InputStream reopenBrokenStream() {
+    sleepAsWakeableBackoff(BROKEN_STREAM_REOPEN_MILLIS);
+    if (stopLogging) {
+      return null;
+    }
+    try {
+      return openStreamUnlessStopped();
+    } catch (RuntimeException e) {
+      if (!stopLogging) {
+        LOG.warn("Log redirection stopped due to error", e);
       }
+      return null;
+    }
+  }
+
+  /**
+   * Opens the raw log stream and makes it the one {@link #stop()} closes. Returns {@code null},
+   * with the new stream closed, if redirection was stopped meanwhile.
+   */
+  private InputStream openStreamUnlessStopped() {
+    InputStream opened = logClient.stream(new LogOptions().raw(true)).join();
+    // A plain volatile write, so the reader never waits for the monitor here.
+    activeStream = opened;
+    // A stop during the open closed the previous stream, not this one, so close it here.
+    if (stopLogging) {
+      closeQuietly(opened);
+      return null;
+    }
+    return opened;
+  }
+
+  /**
+   * Remembers the held-back message of a stream, unless the one remembered is a longer copy of it.
+   * A stream can be cut off earlier than the stream before it, so the later copy can be the shorter
+   * one: it is a prefix of the remembered one. Any other text is another message and replaces it.
+   */
+  private void rememberHeldBack(StringBuilder pending) {
+    String copy = pending.toString();
+    if (!heldBack.startsWith(copy)) {
+      heldBack = copy;
+    }
+  }
+
+  /** Makes the reopened stream redirect only the messages after the last redirected one. */
+  private void prepareReopen() {
+    replayedUntil = lastRedirectedAt;
+    replaySkipCount = redirectedAtLastTimestamp;
+  }
+
+  /** Whether the current stream got at least as far as the stream before it. */
+  private boolean replayCaughtUp() {
+    return replayedUntil == null || replaySkipCount == 0;
+  }
+
+  /** Whether a message of a reopened stream was already redirected before it was reopened. */
+  private boolean isReplayed(Instant logTime) {
+    if (replayedUntil == null) {
+      return false;
+    }
+    if (logTime.isBefore(replayedUntil)) {
+      return true;
+    }
+    if (logTime.equals(replayedUntil) && replaySkipCount > 0) {
+      replaySkipCount--;
+      return true;
+    }
+    replayedUntil = null;
+    return false;
+  }
+
+  private void rememberRedirected(Instant logTime) {
+    if (logTime.equals(lastRedirectedAt)) {
+      redirectedAtLastTimestamp++;
+    } else {
+      lastRedirectedAt = logTime;
+      redirectedAtLastTimestamp = 1;
     }
   }
 
@@ -383,7 +613,7 @@ private InputStream awaitNonEmptyStream() throws IOException {
         return null;
       }
       try {
-        stream = logClient.stream(new LogOptions().raw(true)).join();
+        stream = openStreamUnlessStopped();
       } catch (RuntimeException e) {
         if (stopLogging) {
           return null;
@@ -394,11 +624,7 @@ private InputStream awaitNonEmptyStream() throws IOException {
         }
         throw new IOException("failed to reopen log stream", cause);
       }
-      // A plain volatile write, so the reader never waits for the monitor here.
-      activeStream = stream;
-      // A stop during the reopen closed the previous stream, not this one, so close it here.
-      if (stopLogging) {
-        closeQuietly(stream);
+      if (stream == null) {
         return null;
       }
     }
@@ -464,21 +690,16 @@ private void emitMessages(StringBuilder pending, String text, boolean flush) {
   }
 
   /**
-   * Forwards a trimmed message to the destination, dropping it if it is empty or (when a relevancy
-   * limit is set) older than that limit.
+   * Forwards a trimmed message to the destination, dropping it if it is empty, was already
+   * redirected before the stream was reopened, or is older than {@link #since}.
    */
   private void emitIfRelevant(String message, String timestamp) {
     if (message.isEmpty()) {
       return;
     }
-    if (relevancyTimeLimit != null && timestamp != null) {
-      try {
-        if (Instant.parse(timestamp).isBefore(relevancyTimeLimit)) {
-          return;
-        }
-      } catch (DateTimeParseException ignored) {
-        // Unparseable timestamp: keep the message rather than silently dropping log output.
-      }
+    Instant logTime = parseTimestamp(timestamp);
+    if (logTime != null && (isReplayed(logTime) || (since != null && logTime.isBefore(since)))) {
+      return;
     }
     try {
       destination.accept(message);
@@ -488,6 +709,29 @@ private void emitIfRelevant(String message, String timestamp) {
       forwardingFailed = true;
       stopLogging = true;
       LOG.warn("Log redirection stopped due to error", e);
+      return;
+    }
+    if (logTime != null) {
+      // Messages are redirected in order, so a held-back message is either this one or an older one
+      // that no longer matters. A message without a valid timestamp does not clear it: the replay
+      // filter cannot recognize such a message, so a reopened stream sends it again.
+      heldBack = "";
+      rememberRedirected(logTime);
+    }
+  }
+
+  /**
+   * Parses a message timestamp. Returns {@code null} for a message without one, or with one that is
+   * not a valid instant: it is then kept, rather than silently dropping log output.
+   */
+  private static Instant parseTimestamp(String timestamp) {
+    if (timestamp == null) {
+      return null;
+    }
+    try {
+      return Instant.parse(timestamp);
+    } catch (DateTimeParseException e) {
+      return null;
     }
   }
 
diff --git a/src/main/java/com/apify/client/log/StreamedLogOptions.java b/src/main/java/com/apify/client/log/StreamedLogOptions.java
index 8de3d4e..1f0de88 100644
--- a/src/main/java/com/apify/client/log/StreamedLogOptions.java
+++ b/src/main/java/com/apify/client/log/StreamedLogOptions.java
@@ -1,19 +1,20 @@
 package com.apify.client.log;
 
 import com.apify.client.run.RunClient;
+import java.time.Instant;
 import java.util.function.Consumer;
 
 /**
  * Configures {@link RunClient#getStreamedLog(StreamedLogOptions)} log redirection.
  *
- * 

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

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

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

When the log stream is cut off while the run is still going, it is reopened and the + * redirection resumes after the last redirected message. */ public CompletableFuture getStreamedLog(StreamedLogOptions options) { Consumer destination = options.destination(); if (destination != null) { - return CancellableFuture.completed( - new StreamedLog(log(), destination, options.fromStartValue())); + return CancellableFuture.completed(new StreamedLog(log(), destination, options.sinceValue())); } if (options.prefixValue() != null) { return CancellableFuture.completed( new StreamedLog( - log(), defaultLogDestination(options.prefixValue()), options.fromStartValue())); + log(), defaultLogDestination(options.prefixValue()), options.sinceValue())); } return buildDefaultLogPrefix() .thenApply( - prefix -> - new StreamedLog(log(), defaultLogDestination(prefix), options.fromStartValue())); + prefix -> new StreamedLog(log(), defaultLogDestination(prefix), options.sinceValue())); } /** diff --git a/src/main/java/com/apify/client/store/ActorStoreListItem.java b/src/main/java/com/apify/client/store/ActorStoreListItem.java index ed25137..e3ca439 100644 --- a/src/main/java/com/apify/client/store/ActorStoreListItem.java +++ b/src/main/java/com/apify/client/store/ActorStoreListItem.java @@ -1,19 +1,25 @@ 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. */ +/** An Actor as listed in Apify Store. */ public final class ActorStoreListItem extends ApifyResource { private String id; 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 isVerified; + private String badge; private String pictureUrl; @JsonDeserialize(using = NormalizedUrlDeserializer.class) @@ -44,13 +50,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 +87,16 @@ public PricingInfo getCurrentPricingInfo() { return currentPricingInfo; } + /** 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..b412283 100644 --- a/src/main/java/com/apify/client/store/StoreCollectionClient.java +++ b/src/main/java/com/apify/client/store/StoreCollectionClient.java @@ -3,9 +3,17 @@ import com.apify.client.internal.AbstractCollectionClient; import com.apify.client.internal.ApiPaths; import com.apify.client.internal.HttpClientCore; +import com.apify.client.internal.QueryParams; import com.apify.client.internal.ResourceContext; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; -/** A client for browsing the Apify Store ({@code GET /v2/store}). */ +/** + * A client for browsing and searching Apify Store ({@code GET /v2/store}). The API serves it in two + * ways, and this client has one method for each: {@code list} and {@code iterate} browse the whole + * Store in Store order, page by page, and {@link #search(StoreSearchOptions)} returns the Actors + * that match a query best, as a single page. + */ public final class StoreCollectionClient extends AbstractCollectionClient { @@ -15,4 +23,26 @@ public StoreCollectionClient(HttpClientCore http, String baseUrl) { ActorStoreListItem.class, StoreListOptions::new); } + + /** + * Searches Apify Store and completes with the Actors that match the query best, ordered by + * relevance. + * + *

The API answers a search with a single page of at most 100 Actors. There is no next page and + * no way to skip results, and the API does not report how many Actors match the query in total. A + * result holding as many Actors as {@link StoreSearchResult#getLimit()} can therefore be cut off: + * narrow it down with a more specific query or with the {@code category}, {@code username}, and + * {@code pricingModel} options. To go through the whole Store, use {@code list} or {@code + * iterate}. + * + * @param options the query, the filters, and the number of results + * @throws NullPointerException if {@code options} is {@code null} + */ + public CompletableFuture search(StoreSearchOptions options) { + Objects.requireNonNull(options, "options"); + QueryParams params = new QueryParams(); + options.apply(params); + return listWithParams(params) + .thenApply(page -> new StoreSearchResult(page.getItems(), page.getLimit())); + } } diff --git a/src/main/java/com/apify/client/store/StoreFilterOptions.java b/src/main/java/com/apify/client/store/StoreFilterOptions.java new file mode 100644 index 0000000..95d21f7 --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreFilterOptions.java @@ -0,0 +1,89 @@ +package com.apify.client.store; + +import com.apify.client.internal.QueryParams; + +/** + * Filters shared by {@link StoreListOptions} (browsing the Store) and {@link StoreSearchOptions} + * (searching it). + * + * @param the concrete options type, returned by every setter so calls can be chained + */ +public abstract class StoreFilterOptions> { + private String category; + private String username; + private String pricingModel; + private Boolean includeUnrunnableActors; + private String responseFormat; + private Boolean includeInputSchema; + + /** The concrete options object, for chaining. */ + abstract T self(); + + /** + * Filter Actors by category. Accepts one or more category IDs (e.g. {@code "AI_AND_ML"}), + * separated by commas and case-insensitive; an Actor must match all of them. Legacy keys such as + * {@code social_media} are still accepted, and an unknown category fails with a {@code 400} + * error. + */ + public T category(String category) { + this.category = category; + return self(); + } + + /** Filter Actors by owner username. */ + public T username(String username) { + this.username = username; + return self(); + } + + /** + * Filter Actors by pricing model: {@code FREE}, {@code PRICE_PER_DATASET_ITEM}, or {@code + * PAY_PER_EVENT}. + */ + public T pricingModel(String pricingModel) { + this.pricingModel = pricingModel; + return self(); + } + + /** + * By default, the API leaves out Actors that are not safe to run automatically, such as Actors of + * developers who have not passed identity verification, or full-permission Actors without a large + * user base. If {@code true}, it skips that safety filter and includes them. + */ + public T includeUnrunnableActors(Boolean includeUnrunnableActors) { + this.includeUnrunnableActors = includeUnrunnableActors; + return self(); + } + + /** + * The shape of the response: {@code full} (the default) returns every field, and {@code agent} + * returns a reduced field set for LLM consumers ({@code id}, {@code title}, {@code name}, {@code + * username}, {@code description}, {@code notice}, {@code badge}, {@code categories}, and minimal + * {@code stats}), so the other getters of {@link ActorStoreListItem} return {@code null}. + */ + public T responseFormat(String responseFormat) { + this.responseFormat = responseFormat; + return self(); + } + + /** + * Include a compact {@code inputSchema} (property types and required properties only) of each + * Actor's default build in the results, available through {@code ActorStoreListItem#getExtra()}. + * With this flag the API defaults {@code limit} to {@code 10} and rejects a larger value with a + * {@code 400} error. + */ + public T includeInputSchema(Boolean includeInputSchema) { + this.includeInputSchema = includeInputSchema; + return self(); + } + + /** Applies every filter as a query parameter. */ + public void applyFilters(QueryParams q) { + q.addString("category", category) + .addString("username", username) + .addString("pricingModel", pricingModel) + .addBool("includeUnrunnableActors", includeUnrunnableActors) + .addString("responseFormat", responseFormat) + .addBool("includeInputSchema", includeInputSchema); + } +} diff --git a/src/main/java/com/apify/client/store/StoreListOptions.java b/src/main/java/com/apify/client/store/StoreListOptions.java index 69ce18e..6efb155 100644 --- a/src/main/java/com/apify/client/store/StoreListOptions.java +++ b/src/main/java/com/apify/client/store/StoreListOptions.java @@ -3,19 +3,20 @@ import com.apify.client.internal.ListOptionsLike; import com.apify.client.internal.QueryParams; -/** Options for listing/iterating the Apify Store ({@code GET /v2/store}). */ -public final class StoreListOptions implements ListOptionsLike { +/** + * Options for listing/iterating Apify Store ({@code GET /v2/store}). The Actors come in Store + * order, which the API has no option to change. To find Actors by a text query, use {@link + * StoreSearchOptions} with {@link StoreCollectionClient#search(StoreSearchOptions)}. + */ +public final class StoreListOptions extends StoreFilterOptions + implements ListOptionsLike { private Long offset; private Long limit; - private String search; - private String sortBy; - private String category; - private String username; - private String pricingModel; - private Boolean includeUnrunnableActors; - private Boolean allowsAgenticUsers; - private String responseFormat; - private Boolean includeInputSchema; + + @Override + StoreListOptions self() { + return this; + } /** Number of Actors to skip. */ public StoreListOptions offset(Long offset) { @@ -24,76 +25,16 @@ public StoreListOptions offset(Long offset) { } /** - * 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}; with {@link + * #includeInputSchema(Boolean)} the default is {@code 10} and a larger value is rejected. Sent + * verbatim by {@code list(...)} (so {@code 0} returns zero Actors); in {@code iterate(...)} a + * non-positive/zero {@code limit} means "no cap" (all). */ public StoreListOptions limit(Long limit) { this.limit = limit; return this; } - /** Full-text search query. */ - public StoreListOptions search(String search) { - this.search = search; - return this; - } - - /** The sort field (e.g. {@code "popularity"}, {@code "newest"}). */ - public StoreListOptions sortBy(String sortBy) { - this.sortBy = sortBy; - return this; - } - - /** Filter Actors by category. */ - public StoreListOptions category(String category) { - this.category = category; - return this; - } - - /** Filter Actors by owner username. */ - public StoreListOptions username(String username) { - this.username = username; - return this; - } - - /** - * Filter Actors by pricing model ({@code FREE}, {@code PRICE_PER_DATASET_ITEM}, {@code - * PAY_PER_EVENT}). The rental model ({@code FLAT_PRICE_PER_MONTH}) is deprecated and no longer - * supported, so it is no longer documented as a filter value and matches no Actors. - */ - public StoreListOptions pricingModel(String pricingModel) { - this.pricingModel = pricingModel; - return this; - } - - /** Include Actors the current user cannot run. */ - public StoreListOptions includeUnrunnableActors(Boolean includeUnrunnableActors) { - this.includeUnrunnableActors = includeUnrunnableActors; - return this; - } - - /** Filter to Actors that allow agentic users. */ - public StoreListOptions allowsAgenticUsers(Boolean allowsAgenticUsers) { - this.allowsAgenticUsers = allowsAgenticUsers; - return this; - } - - /** The response format ({@code full}, {@code agent}). */ - public StoreListOptions responseFormat(String responseFormat) { - this.responseFormat = responseFormat; - return this; - } - - /** - * Include a compact {@code inputSchema} (property types and required properties only) of each - * Actor's default build in the results, available through {@code ActorStoreListItem#getExtra()}. - * With this flag the API defaults {@code limit} to, and caps it at, {@code 10}. - */ - public StoreListOptions includeInputSchema(Boolean includeInputSchema) { - this.includeInputSchema = includeInputSchema; - return this; - } - @Override public Long limitValue() { return limit; @@ -109,20 +50,4 @@ public void apply(QueryParams q) { q.addLong("offset", offset).addLong("limit", limit); applyFilters(q); } - - /** - * Applies every filter except {@code offset}/{@code limit}, which the iterator drives per page. - */ - @Override - public void applyFilters(QueryParams q) { - q.addString("search", search) - .addString("sortBy", sortBy) - .addString("category", category) - .addString("username", username) - .addString("pricingModel", pricingModel) - .addBool("includeUnrunnableActors", includeUnrunnableActors) - .addBool("allowsAgenticUsers", allowsAgenticUsers) - .addString("responseFormat", responseFormat) - .addBool("includeInputSchema", includeInputSchema); - } } diff --git a/src/main/java/com/apify/client/store/StoreSearchOptions.java b/src/main/java/com/apify/client/store/StoreSearchOptions.java new file mode 100644 index 0000000..f80cd44 --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreSearchOptions.java @@ -0,0 +1,54 @@ +package com.apify.client.store; + +import com.apify.client.internal.QueryParams; + +/** + * Options for searching Apify Store ({@code GET /v2/store} with a {@code search} query). The API + * ranks the results by relevance and returns them as a single page of at most 100 Actors, so there + * is no {@code offset}. Narrow a search with {@link #category(String)}, {@link #username(String)}, + * or {@link #pricingModel(String)}. + */ +public final class StoreSearchOptions extends StoreFilterOptions { + private final String search; + private Long limit; + + /** + * Creates the options of a search. + * + * @param search text to search for + * @throws IllegalArgumentException if {@code search} is {@code null} or empty, since the API + * answers an empty query with the Store listing + */ + public StoreSearchOptions(String search) { + if (search == null || search.isEmpty()) { + throw new IllegalArgumentException("search must not be empty"); + } + this.search = search; + } + + @Override + StoreSearchOptions self() { + return this; + } + + /** + * Maximum number of Actors to return. The API returns at most {@code 100} Actors for a search, + * which is also the default, and reduces a larger value to {@code 100}. With {@link + * #includeInputSchema(Boolean)}, the default is {@code 10} and a larger value is rejected. + * + * @throws IllegalArgumentException if {@code limit} is not positive + */ + public StoreSearchOptions limit(Long limit) { + if (limit != null && limit <= 0) { + throw new IllegalArgumentException("limit must be positive"); + } + this.limit = limit; + return this; + } + + /** Applies the query, the limit, and every filter as query parameters. */ + void apply(QueryParams q) { + q.addString("search", search).addLong("limit", limit); + applyFilters(q); + } +} diff --git a/src/main/java/com/apify/client/store/StoreSearchResult.java b/src/main/java/com/apify/client/store/StoreSearchResult.java new file mode 100644 index 0000000..9e29d8d --- /dev/null +++ b/src/main/java/com/apify/client/store/StoreSearchResult.java @@ -0,0 +1,35 @@ +package com.apify.client.store; + +import java.util.List; + +/** + * The single page of results that {@link StoreCollectionClient#search(StoreSearchOptions)} + * completes with. + * + *

The API fills the pagination fields of a search response with the number of Actors returned + * and a zero offset, whatever the query matches, so they would read as the number of matches and a + * position to continue from. They are left out. + */ +public final class StoreSearchResult { + private final List items; + private final long limit; + + StoreSearchResult(List items, long limit) { + this.items = List.copyOf(items); + this.limit = limit; + } + + /** The Actors matching the query, best match first. */ + public List getItems() { + return items; + } + + /** + * The maximum number of Actors the API allowed in this result: the requested {@code limit}, or + * the API's maximum when no limit or a larger one was requested. With {@code getItems().size()} + * equal to it, more Actors may match the query than were returned. + */ + public long getLimit() { + return limit; + } +} diff --git a/src/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..9cbcb38 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; @@ -31,6 +32,8 @@ import com.apify.client.schedule.ScheduleInvoked; import com.apify.client.store.ActorStoreListItem; import com.apify.client.store.StoreListOptions; +import com.apify.client.store.StoreSearchOptions; +import com.apify.client.store.StoreSearchResult; import com.apify.client.webhook.NestedWebhookCollectionClient; import com.apify.client.webhook.Webhook; import java.nio.charset.StandardCharsets; @@ -526,6 +529,89 @@ void storeIterateWalksMultiplePages() { assertEquals(3, backend.calls, "two data pages plus the terminating empty page"); } + @Test + void storeSearchSendsOneRequestWithTheQueryTheLimitAndTheFilters() { + MockTransport backend = + MockTransport.ofConstant( + 200, + "{\"data\":{\"items\":[{\"id\":\"a\"},{\"id\":\"b\"}],\"total\":2,\"offset\":0," + + "\"limit\":10,\"count\":2}}"); + StoreSearchResult result = + client(backend) + .store() + .search(new StoreSearchOptions("crawler").limit(10L).username("apify")) + .join(); + assertEquals(2, result.getItems().size()); + assertEquals(10, result.getLimit()); + assertEquals(1, backend.calls, "a search is one page"); + assertTrue(backend.lastUrl.contains("search=crawler"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("limit=10"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("username=apify"), backend.lastUrl); + assertFalse(backend.lastUrl.contains("offset="), backend.lastUrl); + } + + @Test + void storeSearchSendsOnlyTheQueryByDefault() { + MockTransport backend = + MockTransport.ofConstant( + 200, "{\"data\":{\"items\":[],\"total\":0,\"offset\":0,\"limit\":100,\"count\":0}}"); + StoreSearchResult result = + client(backend).store().search(new StoreSearchOptions("crawler")).join(); + assertTrue(result.getItems().isEmpty()); + assertEquals(100, result.getLimit(), "the limit is the one the API applied"); + assertTrue(backend.lastUrl.endsWith("/v2/store?search=crawler"), backend.lastUrl); + } + + @Test + void storeSearchOptionsRejectAnEmptyQueryAndANonPositiveLimit() { + assertThrows(IllegalArgumentException.class, () -> new StoreSearchOptions(null)); + assertThrows(IllegalArgumentException.class, () -> new StoreSearchOptions("")); + StoreSearchOptions options = new StoreSearchOptions("crawler"); + assertThrows(IllegalArgumentException.class, () -> options.limit(0L)); + assertThrows(IllegalArgumentException.class, () -> options.limit(-1L)); + } + + @Test + void storeListNeverSendsASearchQuery() { + MockTransport backend = + MockTransport.ofConstant( + 200, "{\"data\":{\"items\":[],\"total\":0,\"offset\":0,\"limit\":1000,\"count\":0}}"); + client(backend).store().list(new StoreListOptions().username("apify").offset(5L)).join(); + assertTrue(backend.lastUrl.contains("username=apify"), backend.lastUrl); + assertTrue(backend.lastUrl.contains("offset=5"), backend.lastUrl); + assertFalse(backend.lastUrl.contains("search="), backend.lastUrl); + } + + @Test + 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},\"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.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 +1222,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/StreamedLogTest.java b/src/test/java/com/apify/client/StreamedLogTest.java index b6d7ba8..216191a 100644 --- a/src/test/java/com/apify/client/StreamedLogTest.java +++ b/src/test/java/com/apify/client/StreamedLogTest.java @@ -15,6 +15,7 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -27,8 +28,8 @@ /** * Offline tests for the {@link StreamedLog} log-redirection helper: it must forward complete - * timestamped messages to the destination, drop messages older than the relevancy limit when {@code - * fromStart} is false, flush a final unterminated line, and enforce its start/stop lifecycle. + * timestamped messages to the destination, drop messages older than {@code since}, flush a final + * unterminated line, and enforce its start/stop lifecycle. */ @Timeout(30) class StreamedLogTest { @@ -43,6 +44,12 @@ class StreamedLogTest { */ private static final int REDIRECT_POLL_ATTEMPTS = (int) (5_000 / REDIRECT_POLL_MILLIS); + /** Covers the one-second pause before a broken stream is reopened, plus a margin. */ + private static final long REOPEN_WAIT_MILLIS = 2_500; + + /** Long enough for the reader to handle a broken stream and sleep before reopening it. */ + private static final long BREAK_HANDLED_MILLIS = 300; + private static ApifyClient client(MockTransport backend) { return ApifyClient.builder().token("test-token").httpTransport(backend).maxRetries(0).build(); } @@ -92,13 +99,12 @@ void flushesFinalUnterminatedMessage() throws InterruptedException { } @Test - void fromStartFalseDropsOldMessages() throws InterruptedException { - // relevancyTimeLimit is set to "now" at construction, so the year-2000 line is dropped and the - // year-2999 line is kept. + void sinceDropsOldMessages() throws InterruptedException { + // The year-2000 line is older than `since` and dropped; the year-2999 line is kept. List messages = redirect( "2000-01-01T00:00:00.000Z old\n2999-01-01T00:00:00.000Z new\n", - new StreamedLogOptions().fromStart(false)); + new StreamedLogOptions().since(Instant.parse("2020-01-01T00:00:00Z"))); assertEquals(List.of("2999-01-01T00:00:00.000Z new"), messages); } @@ -628,6 +634,642 @@ void stopDuringAnInFlightReopenStillCompletesPromptly() { "stop() should return well within the full empty-stream backoff/retry schedule"); } + /** Redirects the scripted streams of a run and returns what reached the destination. */ + private static List redirectUntil( + MockTransport backend, StreamedLogOptions options, int expectedMessages) { + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend).run("run123").getStreamedLog(options.toLog(collected::add)).join(); + streamedLog.start().join(); + pollUntil( + REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= expectedMessages); + streamedLog.stop(); + return collected; + } + + @Test + void reopensAStreamThatBrokeOffAndSkipsTheMessagesItAlreadyRedirected() { + // A stream cut off while the run goes on is reopened. The reopened stream replays the log from + // its start, so the messages redirected before the break must not come again, and the + // held-back last message of the broken stream is redirected once, from the reopened one. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n")); + backend.scriptStream( + 200, + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n" + + "2999-01-01T00:00:03.000Z D\n"); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C", + "2999-01-01T00:00:03.000Z D"), + collected); + assertEquals(2, backend.calls, "one open, one reopen"); + } + + @Test + void aReopenSkipsOnlyAsManyMessagesAsItRedirectedAtTheSharedTimestamp() { + // Several messages can share a millisecond: the replay skips exactly the ones already + // redirected there, and redirects the rest. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z a\n2999-01-01T00:00:00.000Z b\n2999-01-01T00:00:00.000Z c\n")); + backend.scriptStream( + 200, + "2999-01-01T00:00:00.000Z a\n2999-01-01T00:00:00.000Z b\n2999-01-01T00:00:00.000Z c\n" + + "2999-01-01T00:00:01.000Z d\n"); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z a", + "2999-01-01T00:00:00.000Z b", + "2999-01-01T00:00:00.000Z c", + "2999-01-01T00:00:01.000Z d"), + collected); + } + + @Test + void aReopenedStreamThatBreaksOffBeforeTheLastRedirectedMessageEndsTheRedirection() + throws InterruptedException { + // The first stream redirected A and B and held C back. The reopened one breaks off after A, + // before it replayed B. A stream that keeps breaking off before it catches up would reopen + // without end. The redirection reads the log once instead, which delivers C, and ends without + // a third stream. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + assertEquals(3, backend.calls, "two streams and one read of the log"); + } + + @Test + void aStreamThatEndsWithoutAnErrorIsNotReopened() throws InterruptedException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); + assertEquals(1, backend.calls); + } + + @Test + void aStreamThatBreaksOffBeforeItsFirstByteEndsTheRedirection() throws InterruptedException { + // Nothing was delivered yet, so there is nothing to resume: the error ends the redirection. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, new BrokenStream("")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z never read\n"); + assertEquals(List.of(), redirect(backend, new StreamedLogOptions())); + assertEquals(1, backend.calls); + } + + @Test + void lastRedirectedAtIsTheTimestampOfTheLastRedirectedMessage() throws InterruptedException { + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.500Z B\n"); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(m -> {})) + .join(); + assertTrue(streamedLog.getLastRedirectedAt().isEmpty(), "nothing redirected yet"); + streamedLog.start().join(); + streamedLog.stop(); + assertEquals( + Instant.parse("2999-01-01T00:00:01.500Z"), streamedLog.getLastRedirectedAt().orElseThrow()); + } + + private static final String LOG_ABC = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n"; + + @Test + void stopDuringThePauseBeforeAReopenStillRedirectsTheHeldBackMessage() + throws InterruptedException { + // The broken stream held C back, expecting the reopened stream to replay it. A stop that comes + // before the reopen reads the whole log once instead, and the replay filter skips A and B. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= 2); + Thread.sleep(BREAK_HANDLED_MILLIS); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + assertEquals( + Instant.parse("2999-01-01T00:00:02.000Z"), streamedLog.getLastRedirectedAt().orElseThrow()); + } + + @Test + void aFailedReopenStillRedirectsTheHeldBackMessage() { + // The reopen and the one-off read of the log both fail, so the lines the broken stream held + // back are all that is left to redirect. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void stopWhileAReopenedStreamIsStillReplayingRedirectsTheRest() { + // The reopened stream serves A and then stalls, before it reaches B and C. Stopping then reads + // the whole log once, which delivers C and skips what was already redirected. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream("2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRestartRedirectsTheWholeLogEvenAfterAStopDuringAReopen() throws InterruptedException { + // The first redirection stops during the pause before a reopen. The one-off read of the log is + // empty, so the replay filter stays armed for A. A new start() reads the log from its start and + // must not skip anything. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream( + 200, new BrokenStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + Thread.sleep(BREAK_HANDLED_MILLIS); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + collected.clear(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> collected.size() >= 2); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A", "2999-01-01T00:00:01.000Z B"), collected); + } + + @Test + void stopAfterTheReplayCaughtUpDoesNotRedirectTheLastMessageTwice() { + // The reopened stream replayed A and B, up to the last redirected message, and then stalls. + // Stopping reads the whole log once: B must not come a second time, and C must. + MockTransport backend = MockTransport.ofConstant(200, LOG_ABC); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = + new BlockingStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void stopAfterTheReplayUsedPartOfTheSkipCountDoesNotRepeatMessagesOfTheSameMillisecond() { + // B1 and B2 share a millisecond. The reopened stream replayed only B1 before it stalled, so the + // read of the whole log at the stop must still skip both. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B1\n" + + "2999-01-01T00:00:01.000Z B2\n2999-01-01T00:00:02.000Z C\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream("2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B1\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B1", + "2999-01-01T00:00:01.000Z B2", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aHeldBackMessageThatSharesAMillisecondWithTheLastRedirectedOneIsStillRedirected() { + // C was held back and shares B's millisecond. With the reopen and the read of the log both + // failing, the held-back C must not be taken for a replay of B. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:01.000Z C\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:01.000Z C"), + collected); + } + + @Test + void stopWhileAReopenedStreamIsReplayingRedirectsTheHeldBackMessageWhenTheLogCannotBeRead() { + // The reopened stream stalls after A, before the held-back C, and reading the log fails: the + // held-back message of the first stream is still redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream("2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRestartDoesNotSkipMessagesBecauseOfWhatThePreviousRedirectionSent() + throws InterruptedException { + // The first redirection sent A. After a restart, the stream holds A back and breaks off. The + // replay filter must not be built from the first redirection's A, which would drop it. + MockTransport backend = MockTransport.ofConstant(200, ""); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n"); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, "2999-01-01T00:00:00.000Z A\n"); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + streamedLog.stop(); + collected.clear(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, () -> !collected.isEmpty()); + streamedLog.stop(); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + } + + @Test + void aReplayCutOffInsideTheHeldBackMessageDoesNotRedirectATruncatedCopy() + throws InterruptedException { + // The first stream redirected A and B and held C back. The reopened stream breaks off in the + // middle of C, so only the start of it arrived. The read of the log delivers the whole C. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cf")); + List collected = redirect(backend, new StreamedLogOptions()); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z Cfull"), + collected); + } + + @Test + void aStopInsideTheHeldBackMessageOfAReplayDoesNotRedirectATruncatedCopy() { + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z Cf"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z Cfull"), + collected); + } + + @Test + void aReopenedStreamThatBreaksBeforeAnyMessageKeepsTheHeldBackMessage() { + // A was held back by the first stream. The second one breaks off before it delivers anything, + // and then the reopen and the read of the log fail, so the held-back A is all that is left. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, new BrokenStream("")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 1); + assertEquals(List.of("2999-01-01T00:00:00.000Z A"), collected); + } + + @Test + void aStopAfterTheReplayPassedTheHeldBackMessageDoesNotLoseTheNextOne() { + // The reopened stream replayed A, B and C and has only the start of D when it is stopped. D is + // neither redirected truncated nor lost: the read of the log delivers it whole. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C\n" + + "2999-01-01T00:00:03.000Z Dfull\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + BlockingStream stalled = new BlockingStream(LOG_ABC + "2999-01-01T00:00:03.000Z Df"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C", + "2999-01-01T00:00:03.000Z Dfull"), + collected); + } + + @Test + void aStopInsideAMultiLineHeldBackMessageRedirectsItWhole() { + // C spans two lines. The reopened stream is stopped after its first line, so the read of the + // log delivers both. + String log = + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n" + + "line2\n"; + MockTransport backend = MockTransport.ofConstant(200, log); + backend.scriptStream(200, new BrokenStream(log)); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + + @Test + void aCutShortReplayThatPassedTheHeldBackMessageKeepsItsFullerCopyWhenTheLogCannotBeRead() { + // The first stream held back the first line of C. The reopened stream got the second line too + // before it was stopped, and reading the log fails, so the fuller copy is what is redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n")); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n" + + "line2\n2999-01-01T00:00:03.000Z Df"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + + @Test + void aCutShortReplayKeepsTheLongerHeldBackMessageWhenTheLogCannotBeRead() { + // The first stream held back both lines of C. The reopened stream is stopped after the first + // line of C and part of the second, so the first stream's copy stays. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nline2\n")); + BlockingStream stalled = + new BlockingStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nli"); + backend.scriptStream(200, stalled); + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend) + .run("run123") + .getStreamedLog(new StreamedLogOptions().toLog(collected::add)) + .join(); + streamedLog.start().join(); + pollUntil(REDIRECT_POLL_ATTEMPTS, REDIRECT_POLL_MILLIS, stalled::isBlocked); + streamedLog.stop(); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + + @Test + void aReopenedStreamThatBreaksOffShorterKeepsTheLongerHeldBackMessage() { + // The second stream breaks off after the first line of C, while the first one had both lines. + // The reopen and the read of the log then fail, so the longer copy is redirected. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\nline2\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A\n2999-01-01T00:00:01.000Z B\n2999-01-01T00:00:02.000Z C line1\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C line1\nline2"), + collected); + } + + @Test + void aHeldBackMessageThatWasRedirectedLaterIsNotRedirectedAgain() { + // A was held back by the first stream. The second stream redirects A and B and holds C back, + // and then the reopen and the read of the log fail: C is redirected, and A is not sent again. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A\n")); + backend.scriptStream(200, new BrokenStream(LOG_ABC)); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aTwoLineHeldBackMessageThatWasRedirectedLaterIsNotRedirectedAgain() { + // As the single-line case: the first stream held back both lines of A, the second one redirects + // A with B and holds C back, and then the reopen and the read of the log fail. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-01-01T00:00:00.000Z A line1\nline2\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-01-01T00:00:00.000Z A line1\nline2\n2999-01-01T00:00:01.000Z B\n" + + "2999-01-01T00:00:02.000Z C\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals( + List.of( + "2999-01-01T00:00:00.000Z A line1\nline2", + "2999-01-01T00:00:01.000Z B", + "2999-01-01T00:00:02.000Z C"), + collected); + } + + @Test + void aRepeatedMessageWithAnUnparsableTimestampKeepsTheLongerHeldBackMessage() { + // The timestamp of X has the right shape but is not a date, so the replay filter cannot tell + // that X was redirected before, and the reopened stream sends it again. That must not discard + // the fuller copy of the held-back C. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + String head = "2999-01-01T00:00:00.000Z A\n2999-99-01T00:00:00.000Z X\n"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream(head + "2999-01-01T00:00:02.000Z C line1\nline2\n")); + backend.scriptStream(200, new BrokenStream(head + "2999-01-01T00:00:02.000Z C line1\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 4); + assertEquals("2999-01-01T00:00:02.000Z C line1\nline2", collected.get(collected.size() - 1)); + } + + @Test + void aHeldBackMessageWithoutAParsableTimestampIsReplacedByALaterOne() { + // X was held back, and its timestamp is not a date, so redirecting it does not clear the copy. + // The second stream redirects X again and holds back Z: Z must be the one that is left. + String error = "{\"error\":{\"type\":\"forbidden\",\"message\":\"no\"}}"; + MockTransport backend = MockTransport.ofConstant(403, error); + backend.scriptStream(200, new BrokenStream("2999-99-01T00:00:00.000Z XXXXXXXXXXXX\n")); + backend.scriptStream( + 200, + new BrokenStream( + "2999-99-01T00:00:00.000Z XXXXXXXXXXXX\n2999-99-01T00:00:01.000Z Y\n" + + "2999-99-01T00:00:02.000Z Z\n")); + backend.scriptStream(403, error); + List collected = redirectUntil(backend, new StreamedLogOptions(), 3); + assertEquals("2999-99-01T00:00:02.000Z Z", collected.get(collected.size() - 1)); + } + + /** As {@link #redirectUntil}, for a finite script: the reader ends on its own. */ + private static List redirect(MockTransport backend, StreamedLogOptions options) + throws InterruptedException { + List collected = new CopyOnWriteArrayList<>(); + StreamedLog streamedLog = + client(backend).run("run123").getStreamedLog(options.toLog(collected::add)).join(); + streamedLog.start().join(); + Thread.sleep(REOPEN_WAIT_MILLIS); + streamedLog.stop(); + return collected; + } + @Test void defaultPrefixLookupFailureStillCreatesHelper() { // The no-arg getStreamedLog() builds a cosmetic per-run prefix by GETting the run (and its @@ -640,6 +1282,37 @@ void defaultPrefixLookupFailureStillCreatesHelper() { assertNotNull(streamedLog); } + /** + * An {@link InputStream} that serves a fixed payload and then fails with an {@link IOException} + * on its own, as a log stream does when the connection is cut off. + */ + private static final class BrokenStream extends InputStream { + private final byte[] data; + private int pos; + + BrokenStream(String data) { + this.data = data.getBytes(StandardCharsets.UTF_8); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (pos >= data.length) { + throw new IOException("Connection reset"); + } + int n = Math.min(len, data.length - pos); + System.arraycopy(data, pos, b, off, n); + pos += n; + return n; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int n = read(one, 0, 1); + return n == -1 ? -1 : one[0] & 0xff; + } + } + /** * An {@link InputStream} that serves a fixed payload once and then blocks on {@code read()} until * it is closed, throwing an {@link IOException} when unblocked by the close. This models a live 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..53650de 100644 --- a/src/test/java/com/apify/client/integration/StoreIntegrationTest.java +++ b/src/test/java/com/apify/client/integration/StoreIntegrationTest.java @@ -1,10 +1,13 @@ package com.apify.client.integration; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.apify.client.ApifyClient; import com.apify.client.store.ActorStoreListItem; import com.apify.client.store.StoreListOptions; +import com.apify.client.store.StoreSearchOptions; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Flow; import java.util.concurrent.atomic.AtomicInteger; @@ -19,6 +22,59 @@ void listStore() { assertTrue(page.getItems().size() <= 5); } + @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 searchReturnsTheBestMatchesAsOnePage() { + ApifyClient client = requireClient(); + var result = client.store().search(new StoreSearchOptions("web scraper").limit(5L)).join(); + // The public Store holds thousands of scrapers, so the page is always full. + assertEquals(5, result.getItems().size()); + assertEquals(5, result.getLimit()); + assertTrue( + result.getItems().stream() + .allMatch(item -> item.getId() != null && item.getUsername() != null)); + } + + @Test + void searchReturnsAtMostOneHundredActors() { + ApifyClient client = requireClient(); + var byDefault = client.store().search(new StoreSearchOptions("scraper")).join(); + var large = client.store().search(new StoreSearchOptions("scraper").limit(1000L)).join(); + assertEquals(100, byDefault.getLimit()); + assertEquals(100, byDefault.getItems().size()); + assertEquals(100, large.getLimit()); + assertEquals(100, large.getItems().size()); + } + + @Test + void searchForAQueryThatMatchesNothingReturnsNoActors() { + ApifyClient client = requireClient(); + var result = client.store().search(new StoreSearchOptions("qzxjvkwpqzxjvkwp")).join(); + assertTrue(result.getItems().isEmpty()); + } + + @Test + void searchFiltersByUsername() { + ApifyClient client = requireClient(); + var result = + client + .store() + .search(new StoreSearchOptions("scraper").limit(10L).username("apify")) + .join(); + assertFalse(result.getItems().isEmpty()); + assertTrue(result.getItems().stream().allMatch(item -> "apify".equals(item.getUsername()))); + } + @Test void listStoreWithInputSchema() { ApifyClient client = requireClient();