diff --git a/CHANGELOG.md b/CHANGELOG.md index e219910..68f3f0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 0.15.0 + +- Synced with Apify OpenAPI spec `v2-2026-12-03T122505Z`: the API dropped the Store `allowsAgenticUsers` filter. +- **Breaking:** `StoreListOptions` loses `search`, `sortBy`, and `allowsAgenticUsers`. `store()->list()` and `iterate()` browse the Store in Store order. +- Added `store()->search()` with `StoreSearchOptions` and `StoreSearchResult`. It returns the Actors that match a query best as one page of at most 100, since the API ignores `offset` for a search. It rejects an empty query and a limit that is not positive. +- `versions()->create()` and `version()->update()` use the `long` timeout tier by default, since a version can carry its source files. +- Documented the Store `category` filter, the `search` page limit, and the `limit` of at most 10 with `includeInputSchema`. +- Documented that a signed public URL of a dataset or key-value store grants access to all items or keys, and that the options only set the default response. +- Added the `headers` argument of `ApifyClient`, which sends headers with every request (apify/apify-client-js#1058). +- Added `keyValueStore()->streamRecord()`, which reads a record as a stream, and the `$timeoutSecs` argument of `task()->publish()` and `unpublish()`. +- `streamRecord()`, `dataset()->streamItems()`, and `log()->stream()` take `$timeoutSecs` and retry opening the stream like any request. +- `call()` of an Actor and of a task redirects the run log, to the standard error stream by default (new `$log` argument, as in the reference client). +- Added `run()->redirectLog()` and the `$timeoutSecs` argument of `run()->getStreamedLog()`. +- **Breaking:** `log()->stream()` returns `null` for a missing log of a client with an ID. +- A client-wide `Authorization` header is sent as `X-Apify-Authorization` to an Actor server, so the Actor never receives it. +- Corrected the description of `includeUnrunnableActors` and documented the constructor arguments, the transport contract, and the other public methods that the docs missed. +- Raised PHPStan to level 9 and added an integration test for `user($id)->get()`. + ## 0.14.1 - Synced with Apify OpenAPI spec `v2-2026-11-18T151559Z`: `UserClient::get()` returns only `plan.availableProxyGroups`, `effectivePlatformFeatures` and `isPaying` for a proxy password. diff --git a/README.md b/README.md index 543f2fe..ecdab74 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,11 @@ $configured = new ApifyClient( | `timeoutMaxSecs` | `timeoutSecs` | Cap on the timeout of any attempt, per-call overrides, and growth across retries included. | | `compression` | `null` (brotli, else gzip) | Request body compression: `'brotli'`, `'gzip'`, `'zstd'`, or a custom `HttpCompressorInterface`, see [HTTP compression](#http-compression). | | `userAgentSuffix` | `null` | Suffix appended to the `User-Agent` header. | -| `httpClient` | Guzzle | The transport, an `Apify\Client\Http\HttpClientInterface`. | +| `headers` | `[]` | Headers sent with every request, for example an integration marker. They replace the built-in `User-Agent` and token headers, and a header a call sets for itself, such as `Content-Type`, replaces them. A client-wide `Authorization` header is sent as `X-Apify-Authorization` to an Actor server, so the Actor never receives it. | +| `httpClient` | Guzzle | The transport, an `Apify\Client\Http\HttpClientInterface`, see [Replaceable HTTP transport](#replaceable-http-transport). | +| `requestFactory` | Guzzle's | The PSR-17 `RequestFactoryInterface` that builds the requests. | +| `streamFactory` | Guzzle's | The PSR-17 `StreamFactoryInterface` that builds the request bodies. | +| `isAtHomeFn` | reads `APIFY_IS_AT_HOME` | A `callable(): bool` that replaces the detection of the `isAtHome` flag of the `User-Agent` header. | Requests are retried with exponential backoff and jitter on network errors, HTTP 429, and 5xx. Other 4xx responses throw an `ApifyApiException` subclass for the status. A 404 on a single resource is not thrown: @@ -84,7 +88,7 @@ A call that asks the API to hold its response with `waitForFinish` (`RunClient:: `ActorClient::defaultBuild()`, and the `waitForFinish` option of `ActorClient::start()`, `build()` and `TaskClient::start()`) gets that hold on top of its tier, for at most 60 seconds. -Every request method also takes a trailing `$timeoutSecs` that overrides the tier for that call: seconds, a +Every request method also takes a `$timeoutSecs` (the last argument, except that `call()` of an Actor or a task takes `$log` after it) that overrides the tier for that call: seconds, a tier name (`'short'`, `'medium'`, `'long'`), or `'noTimeout'`: ```php @@ -120,8 +124,9 @@ $client = new ApifyClient(token: 'my-api-token', compression: new ZstdHttpCompre ``` Brotli and zstd need their PECL extensions, and gzip needs `zlib`. Choosing a codec without its extension throws -`RuntimeException` when the client is created. A custom algorithm is an -`Apify\Client\Http\HttpCompressorInterface` implementation: `contentEncoding(): string` and +`RuntimeException` when the client is created. `BrotliHttpCompressor::isAvailable()`, +`GzipHttpCompressor::isAvailable()`, and `ZstdHttpCompressor::isAvailable()` tell whether the codec can be used. +A custom algorithm is an `Apify\Client\Http\HttpCompressorInterface` implementation: `contentEncoding(): string` and `compress(string $body): ?string`, which returns `null` to send the body as it is. ### Replaceable HTTP transport @@ -137,8 +142,21 @@ $psr18 = new \GuzzleHttp\Client(['timeout' => 120]); $client = new ApifyClient(token: 'my-api-token', httpClient: new Psr18HttpClient($psr18)); ``` +A transport implements two methods. Both take a prepared PSR-7 request and a per-attempt timeout in seconds, and +return a PSR-7 response. The client adds the token and the `User-Agent`, and retries failed requests. + +| Method | Returns | +|---|---| +| `send(RequestInterface $request, float $timeoutSecs): ResponseInterface` | The response with its whole body. | +| `sendStreaming(RequestInterface $request, float $timeoutSecs): ResponseInterface` | The response with a live body stream, which the caller reads to the end. | + +An error status is a normal response. Throw `TransportException` only when no response arrived (a refused +connection, DNS, a timeout, or a connection dropped before the body is complete). + `ActorClient::server()->request()` needs a transport that returns redirects as they are. It throws with -`Psr18HttpClient` and any transport that does not implement `NoRedirectHttpClientInterface`. See +`Psr18HttpClient` and any transport that does not implement `NoRedirectHttpClientInterface`, which adds +`sendWithoutRedirects(RequestInterface $request, float $timeoutSecs, bool $stream = false): ResponseInterface`. It +sends like `send()`, or like `sendStreaming()` with `$stream`, but returns a 3xx response instead of following it. See [Server Actors](docs/actors.md). ## Error handling @@ -194,8 +212,9 @@ A network failure or timeout is retried. When the retries run out, it throws means the server answered with an error, and `TransportException` means no usable response arrived. A success response whose body is not valid JSON, for an endpoint that returns JSON, is not retried and throws -`Apify\Client\Exception\InvalidResponseBodyException`. An error response with an unparsable body, such as an -HTML 502 page, throws the `ApifyApiException` subclass for its status with the raw body in the message. +`Apify\Client\Exception\InvalidResponseBodyException`, whose `getRawBody()` returns the body as received. An error +response with an unparsable body, such as an HTML 502 page, throws the `ApifyApiException` subclass for its status +with the raw body in the message. `ApifyApiException` and `InvalidResponseBodyException` extend `Apify\Client\Exception\ApifyClientException`, so one `catch` handles both: diff --git a/composer.json b/composer.json index 21e2893..f43a68c 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "apify/apify-client", - "description": "Official, experimental (AI-generated and AI-maintained) Apify API client for PHP: run Actors, manage storages (datasets, key-value stores, request queues), schedules, webhooks and more.", + "description": "Apify API client for PHP: run Actors, manage storages (datasets, key-value stores, request queues), schedules, webhooks and more.", "type": "library", "keywords": [ "apify", diff --git a/docs/README.md b/docs/README.md index 0f5d357..7cfebaf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -62,7 +62,7 @@ the [resource pages](#resource-pages). | `webhooks(): WebhookCollectionClient` | Webhook collection | List and create webhooks. | | `webhookDispatch(string $id): WebhookDispatchClient` | Webhook dispatch client | Single webhook dispatch. | | `webhookDispatches(): WebhookDispatchCollectionClient` | Webhook dispatch collection | List webhook dispatches. | -| `store(): StoreCollectionClient` | Store collection | Browse the public Apify Store. | +| `store(): StoreCollectionClient` | Store collection | Browse and search Apify Store. | | `log(string $buildOrRunId): LogClient` | Log client | Log for a build or run, by ID. | | `me(): UserClient` | User client | The authenticated user (`users/me`). | | `user(string $id): UserClient` | User client | A public user profile, by ID. | diff --git a/docs/actors.md b/docs/actors.md index 13df8bc..61edefe 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -35,7 +35,7 @@ Addressed by ID or `username~name` (a `username/name` is accepted too). - `update(mixed $newFields): Actor` - `delete(): void` - `start(mixed $input = null, ?ActorStartOptions $options = null): ActorRun`: start and return immediately. -- `call(mixed $input = null, ?ActorStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun`: start and wait. `$timeoutSecs` is the timeout of the start request and of every poll (default `'noTimeout'`). +- `call(mixed $input = null, ?ActorStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null, callable|false|null $log = null): ActorRun`: start and wait. `$timeoutSecs` is the timeout of the start request and of every poll (default `'noTimeout'`). `$log` is where the log of the run goes while the call waits: by default each message goes to the standard error stream, behind `{Actor name} runId:{run ID} -> `. Pass a callable that takes the message, or `false` for no redirection. A failure to redirect prints a warning and the call waits without it. See [`RunClient::redirectLog()`](runs.md). - `validateInput(mixed $input = null, ?ValidateInputOptions $options = null): bool` `$input` is a JSON-serializable array, or a `string` sent as it is. Set `$options->contentType` for a string, for @@ -118,7 +118,8 @@ $response = $server->request('/search', new ActorServerRequestOptions( - Single: `get(): ?ActorVersion`, `update(mixed $newFields): ActorVersion`, `delete(): void`. The endpoint returns all versions in one response, so `list()` and `iterate()` take no options and `iterate()` -makes one request. +makes one request. `create()` and `update()` use the `long` timeout tier by default, since a version can carry its +source files. ```php $version = $client->actor('me~my-actor')->versions()->create([ diff --git a/docs/examples.md b/docs/examples.md index 8cb1405..43cf708 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -3,9 +3,11 @@ The snippets assume a `$client` and imported types (see [Namespaces](README.md#namespaces)). The first [complete program](#a-complete-standalone-program) shows the scaffolding that the shorter snippets omit. -The programs on this page are in [`tests/Examples/`](../tests/Examples), and the `Test examples` CI step runs them -against the live API (`ExamplesTest`). Other snippets in the documentation are only checked with `php -l` by -`DocSnippetsTest`, which finds parse errors but not unknown classes or wrong types. +Each program on this page is the body of a class in [`tests/Examples/`](../tests/Examples), and the `Test examples` +CI step runs those classes against the live API (`ExamplesTest`). `ExampleDocsTest` checks that every snippet is +identical to the code that runs, and `ExamplesTest` also runs the standalone program. Other snippets in the +documentation are only checked with `php -l` by `DocSnippetsTest`, which finds parse errors but not unknown classes +or wrong types. ## A complete, standalone program @@ -22,7 +24,11 @@ require 'vendor/autoload.php'; use Apify\Client\ApifyClient; use Apify\Client\Exception\ApifyApiException; -$client = new ApifyClient(getenv('APIFY_TOKEN') ?: 'my-api-token'); +// APIFY_API_URL is optional. It points the client at another API, such as a staging stack. +$client = new ApifyClient( + token: getenv('APIFY_TOKEN') ?: 'my-api-token', + baseUrl: getenv('APIFY_API_URL') ?: 'https://api.apify.com', +); try { // Run a Store Actor and wait up to 120 seconds for it to finish. @@ -40,25 +46,43 @@ try { ```php $run = $client->actor('apify/hello-world')->call(null, null, 120); -// getDefaultDatasetId() is ?string, so cast it to satisfy dataset(string $id). -$items = $client->dataset((string) $run->getDefaultDatasetId())->listItems(); +$items = $client->dataset((string) $run->getDefaultDatasetId())->listItems(new DatasetListItemsOptions()); echo 'Item count: ' . $items->getCount() . PHP_EOL; ``` ## Each storage: create, push, read ```php -$dataset = $client->datasets()->getOrCreate('example-ds'); -$client->dataset($dataset->getId())->pushItems([['hello' => 'world']]); -$dsItems = $client->dataset($dataset->getId())->listItems(); +// Dataset +$dataset = $client->datasets()->getOrCreate('php-example-ds-' . bin2hex(random_bytes(4))); +try { + $client->dataset((string) $dataset->getId())->pushItems([['hello' => 'world']]); + $items = $client->dataset((string) $dataset->getId())->listItems(new DatasetListItemsOptions()); + echo 'Dataset items: ' . $items->getCount() . PHP_EOL; +} finally { + $client->dataset((string) $dataset->getId())->delete(); +} -$store = $client->keyValueStores()->getOrCreate('example-kvs'); -$client->keyValueStore($store->getId())->setRecordJson('OUTPUT', ['answer' => 42]); -$record = $client->keyValueStore($store->getId())->getRecord('OUTPUT'); +// Key-value store +$store = $client->keyValueStores()->getOrCreate('php-example-kvs-' . bin2hex(random_bytes(4))); +try { + $client->keyValueStore((string) $store->getId())->setRecordJson('OUTPUT', ['answer' => 42]); + $record = $client->keyValueStore((string) $store->getId())->getRecord('OUTPUT'); + echo 'KVS record: ' . ($record?->getValue() ?? '') . PHP_EOL; +} finally { + $client->keyValueStore((string) $store->getId())->delete(); +} -$queue = $client->requestQueues()->getOrCreate('example-rq'); -$client->requestQueue($queue->getId())->addRequest(new RequestQueueRequest('https://example.com', 'example')); -$head = $client->requestQueue($queue->getId())->listHead(10); +// Request queue +$queue = $client->requestQueues()->getOrCreate('php-example-rq-' . bin2hex(random_bytes(4))); +try { + $client->requestQueue((string) $queue->getId()) + ->addRequest(new RequestQueueRequest('https://example.com', 'example')); + $head = $client->requestQueue((string) $queue->getId())->listHead(10); + echo 'Queue head size: ' . count($head->getItems()) . PHP_EOL; +} finally { + $client->requestQueue((string) $queue->getId())->delete(); +} ``` ## Get own account details @@ -74,7 +98,7 @@ if ($user !== null) { ```php $created = $client->actors()->create([ - 'name' => 'my-example-actor', + 'name' => 'php-example-actor-' . bin2hex(random_bytes(4)), 'isPublic' => false, 'versions' => [[ 'versionNumber' => '0.0', @@ -87,31 +111,35 @@ $created = $client->actors()->create([ ]], ]); try { - $build = $client->actor($created->getId())->build('0.0', new ActorBuildOptions()); - $client->build($build->getId())->waitForFinish(300); - $run = $client->actor($created->getId())->call(null, null, 120); - $log = $client->run($run->getId())->log()->get(); + $build = $client->actor((string) $created->getId())->build('0.0', new ActorBuildOptions()); + $client->build((string) $build->getId())->waitForFinish(300); + $run = $client->actor((string) $created->getId())->call(null, null, 120); + $log = $client->run((string) $run->getId())->log()->get(); if ($log !== null) { echo $log . PHP_EOL; } } finally { - $client->actor($created->getId())->delete(); + $client->actor((string) $created->getId())->delete(); } ``` ## Start a run, wait, then fetch the Actor's last run and its storages ```php +// Start the run, then wait for it to finish. $started = $client->actor('apify/hello-world')->start(); -$client->run($started->getId())->waitForFinish(120); +$client->run((string) $started->getId())->waitForFinish(120); -// Fetch the last run and read its storages via the run-nested convenience accessors. +// Fetch the Actor's last successful run and read its storages through the run-nested +// convenience accessors, which resolve the last run's dataset, key-value store and +// request queue without needing their individual IDs. $lastRun = $client->actor('apify/hello-world')->lastRun(new LastRunOptions(status: 'SUCCEEDED')); $last = $lastRun->get(); if ($last !== null) { - $lastRun->dataset()->listItems(); + $lastRun->dataset()->listItems(new DatasetListItemsOptions()); $lastRun->keyValueStore()->getRecord('OUTPUT'); $lastRun->requestQueue()->listHead(10); + echo 'Last run: ' . $last->getId() . PHP_EOL; } ``` @@ -119,7 +147,8 @@ if ($last !== null) { ```php $shown = 0; -// The second argument is the per-page (chunk) size; StoreListOptions::limit would cap the total. +// The second argument is the per-page (chunk) size; the iterator fetches pages lazily as we +// consume items. StoreListOptions::limit (unset here) would cap the total across all pages. foreach ($client->store()->iterate(new StoreListOptions(), 10) as $item) { echo $item->getName() . PHP_EOL; if (++$shown >= 5) { @@ -131,11 +160,12 @@ foreach ($client->store()->iterate(new StoreListOptions(), 10) as $item) { ## Run an Actor with log redirection ```php -// Start the run without waiting, then redirect its log to stdout live. The streaming endpoint keeps -// the connection open and emits log lines in real time; reading to EOF also waits for the run to end. -$run = $client->actor('apify/hello-world')->start(); -$stream = $client->run($run->getId())->getStreamedLog(); -while (!$stream->eof()) { - echo $stream->read(8192); -} +// call() redirects the log of the run while it waits. Without the `log` argument, the messages go to the +// standard error stream, behind "{Actor name} runId:{run ID} -> ". A callable receives each message +// instead, and `false` turns the redirection off. +$run = $client->actor('apify/hello-world')->call(null, null, 120, log: static function (string $message): void { + echo 'Actor log: ' . $message . PHP_EOL; +}); + +echo 'Run status: ' . $run->getStatus() . PHP_EOL; ``` diff --git a/docs/misc.md b/docs/misc.md index e6fd46e..dbe554d 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -4,15 +4,19 @@ Snippets assume `$client = new ApifyClient('my-api-token');` and imported types. ## Apify Store — `$client->store()` -- `list(?StoreListOptions $options = null): PaginationList`: one page of Store Actors. -- `iterate(?StoreListOptions $options = null, ?int $chunkSize = null): iterable`: lazily yields the matching Actors. The `limit` option caps the total (unset for all), `$chunkSize` is the page size. +- `list(?StoreListOptions $options = null): PaginationList`: one page of Store Actors, in Store order. +- `iterate(?StoreListOptions $options = null, ?int $chunkSize = null): iterable`: lazily yields the Actors in Store order. The `limit` option caps the total (unset for all), `$chunkSize` is the page size. +- `search(StoreSearchOptions $options): StoreSearchResult`: the Actors that match a query best, by relevance. The API answers a search with one page of at most 100 Actors, ignores `offset`, and does not report how many Actors match, so a search cannot be paged or iterated. A result with as many Actors as `getLimit()` can be cut off: narrow the query or use the filters. `getItems()` returns the Actors and `getLimit()` the limit the API applied, and the result can be iterated and counted. An empty query or a limit that is not positive throws `InvalidArgumentException` when the options are created. ```php -$page = $client->store()->list(new StoreListOptions(search: 'scraper', limit: 10)); +$result = $client->store()->search(new StoreSearchOptions('scraper', limit: 10)); +foreach ($result->getItems() as $item) { + echo $item->getName() . PHP_EOL; +} $shown = 0; // 50 is the page size. The limit option would cap the total. -foreach ($client->store()->iterate(new StoreListOptions(search: 'scraper'), 50) as $item) { +foreach ($client->store()->iterate(new StoreListOptions(category: 'AI_AND_ML'), 50) as $item) { echo $item->getName() . PHP_EOL; if (++$shown >= 5) { break; @@ -36,7 +40,7 @@ $publicProfile = $client->user('some-username')->get(); ## Logs — `$client->log($buildOrRunId)` - `get(?LogOptions $options = null): ?string`: the log as text, with the exact bytes the API sent. -- `stream(?LogOptions $options = null): StreamInterface`: a live stream of the log. +- `stream(?LogOptions $options = null, int|float|string|null $timeoutSecs = null): ?StreamInterface`: a live stream of the log, or `null` if the log does not exist. A client without an ID, such as `run()->log()`, throws on a 404, like `get()`. Opening the stream is retried like any request, and a failure while the log is being read is not. The default timeout is the `long` tier. ```php $log = $client->log('RUN_OR_BUILD_ID')->get(new LogOptions(raw: true)); diff --git a/docs/models.md b/docs/models.md index f4194be..46eab92 100644 --- a/docs/models.md +++ b/docs/models.md @@ -121,7 +121,7 @@ The `uiState` field in `toArray()` is `null` after an API update changes the cro Private account details (plan, email, etc.) are available via `toArray()` for `me()` and for a user ID fetched with a token of that account. A proxy password gets only `plan.availableProxyGroups`, `effectivePlatformFeatures` and `isPaying`, so the ID and username are `null`. ### `ActorStoreListItem` -Returned when listing/iterating the Apify Store. +Returned when listing, iterating, or searching Apify Store. | Getter | Description | |---|---| | `getId(): ?string` | The Actor ID. | @@ -129,6 +129,13 @@ Returned when listing/iterating the Apify Store. | `getUsername(): ?string` | Username of the Actor's owner. | | `getTitle(): ?string` | Human-readable title. | +### `StoreSearchResult` +Returned by `store()->search()`. It can be iterated and counted. It has no `total` or `offset`, as the API fills them with the number of Actors returned and zero. +| Getter | Description | +|---|---| +| `getItems(): list` | The Actors matching the query, best match first. | +| `getLimit(): int` | The limit the API applied. With as many items, more Actors may match than were returned. | + ## Storage models ### `Dataset` @@ -157,6 +164,14 @@ Returned when listing/iterating the Apify Store. | `getValue(): string` | The raw record value, as a string (decode it yourself when it is JSON). | | `getContentType(): ?string` | The record's content type. | +### `KeyValueStoreRecordStream` +Returned by `streamRecord()`. +| Getter | Description | +|---|---| +| `getKey(): string` | The record key. | +| `getStream(): StreamInterface` | The raw record bytes, as a PSR-7 stream. | +| `getContentType(): ?string` | The record's content type. | + ### `KeyValueStoreKey` | Getter | Description | |---|---| @@ -232,6 +247,8 @@ Returned by single-request add/update operations. |---|---| | `getRequestId(): ?string` | ID assigned to the request. | | `getUniqueKey(): ?string` | The request's unique key. | +| `wasAlreadyPresent(): ?bool` | Whether a request with the same unique key was already in the queue. | +| `wasAlreadyHandled(): ?bool` | Whether that request was already handled. | ### `BatchAddResult` Returned by `batchAddRequests()`. diff --git a/docs/options.md b/docs/options.md index 2e0ceb2..59a4c6c 100644 --- a/docs/options.md +++ b/docs/options.md @@ -17,11 +17,10 @@ The offset-based options classes — `ListOptions`, `ActorListOptions`, `Storage It returns a copy of the options with the given `offset` and `limit`, preserving every other field. The `iterate()` helpers use it internally to request successive pages, but you can also call it to -page manually through `list()` results — most useful for the Apify Store, whose collection is -otherwise only pageable via `iterate()`: +page manually through `list()` results, for example Apify Store: ```php -$options = new StoreListOptions(search: 'scraper'); +$options = new StoreListOptions(category: 'AI_AND_ML'); for ($offset = 0; ; $offset += 100) { $page = $client->store()->list($options->withPagination($offset, 100)); foreach ($page->getItems() as $item) { @@ -74,26 +73,36 @@ Extra filters for `runs()->list()`, combined with a `ListOptions`. | `status` | `list\|null` | Filter by one or more run statuses (e.g. `SUCCEEDED`, `RUNNING`); sent comma-separated. | | `startedAfter` | `?string` | Only runs started after this ISO-8601 timestamp. | | `startedBefore` | `?string` | Only runs started before this ISO-8601 timestamp. | -| `deployment` | `list\|null` | Only Actor Standby runs of these deployments (`SINGLE_TENANT`, `MULTI_TENANT_FREE_USERS`, `MULTI_TENANT_PAYING_USERS`, `MULTI_TENANT_OWNER_PAID`); sent comma-separated. The API requires `status` to hold only non-terminal statuses (`READY`, `RUNNING`, `TIMING-OUT`, `ABORTING`) when it is used. Honoured by `runs()` and `actor($id)->runs()`. | +| `deployment` | `list\|null` | Only Server Actor runs of these deployments (`SINGLE_TENANT`, `MULTI_TENANT_FREE_USERS`, `MULTI_TENANT_PAYING_USERS`, `MULTI_TENANT_OWNER_PAID`); sent comma-separated. The API requires `status` to hold only non-terminal statuses (`READY`, `RUNNING`, `TIMING-OUT`, `ABORTING`) when it is used. Honored by `runs()` and `actor($id)->runs()`. | ### `StoreListOptions` -For `store()->list()` / `store()->iterate()`. +For `store()->list()` / `store()->iterate()`. The Actors come in Store order, which the API has no option to change. | Field | Type | Description | |---|---|---| | `offset` | `?int` | Number of Actors to skip. | -| `limit` | `?int` | Maximum number of Actors to return. When iterating, caps the total across all pages (the per-page size is `iterate()`'s separate `$chunkSize` argument). | -| `search` | `?string` | Full-text search query. | -| `sortBy` | `?string` | The sort field (e.g. `popularity`, `newest`). | -| `category` | `?string` | Filter Actors by category. | +| `limit` | `?int` | Maximum number of Actors to return. When iterating, caps the total across all pages (the per-page size is `iterate()`'s separate `$chunkSize` argument). With `includeInputSchema`, each request may ask for at most 10 Actors: the `limit` of `list()`, and for `iterate()` the smaller of `limit` and `$chunkSize`. The API rejects a larger page size. | +| `category` | `?string` | Filter Actors by one or more comma-separated category IDs, such as `AI_AND_ML`. An Actor must match all of them. | | `username` | `?string` | Filter Actors by owner username. | | `pricingModel` | `?string` | Filter by pricing model (`FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`). | -| `includeUnrunnableActors` | `?bool` | Include Actors the current user cannot run. | -| `allowsAgenticUsers` | `?bool` | Filter to Actors that allow agentic users. | +| `includeUnrunnableActors` | `?bool` | By default, the API leaves out Actors that are not safe to run automatically, such as Actors of developers who have not verified their identity. If true, those Actors are included as well. | | `responseFormat` | `?string` | The response format (`full`, `agent`). | -| `includeInputSchema` | `?bool` | Include each Actor's compact input schema (only returned when its default build succeeded and defines input properties). | +| `includeInputSchema` | `?bool` | Include each Actor's compact input schema (only returned when its default build succeeded and defines input properties). The page size must then be 10 or less, see `limit`. | Supports [`withPagination($offset, $limit)`](#manual-offset-paging-with-withpagination). +### `StoreSearchOptions` +For `store()->search()`. The API answers a search with one page, so there is no `offset`. +| Field | Type | Description | +|---|---|---| +| `search` | `string` | Required. Text to search for. It cannot be empty. | +| `limit` | `?int` | Maximum number of Actors to return, positive. The default and the maximum are 100, and the API reduces a larger value to 100. With `includeInputSchema`, the default and the maximum are 10, and the API rejects a larger value. | +| `category` | `?string` | Filter Actors by one or more comma-separated category IDs, such as `AI_AND_ML`. An Actor must match all of them. | +| `username` | `?string` | Filter Actors by owner username. | +| `pricingModel` | `?string` | Filter by pricing model (`FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`). | +| `includeUnrunnableActors` | `?bool` | By default, the API leaves out Actors that are not safe to run automatically, such as Actors of developers who have not verified their identity. If true, those Actors are included as well. | +| `responseFormat` | `?string` | The response format (`full`, `agent`). | +| `includeInputSchema` | `?bool` | Include each Actor's compact input schema (only returned when its default build succeeded and defines input properties). | + ### `RunIterateDatasetItemsOptions` For `run($id)->iterateDatasetItems()`. | Field | Type | Description | @@ -255,7 +264,7 @@ For `keyValueStore()->listKeys()` and `createKeysPublicUrl()`. | `signature` | `?string` | A pre-shared URL signature granting access without an API token. | ### `GetRecordOptions` -For `keyValueStore()->getRecord()`. +For `keyValueStore()->getRecord()` and `streamRecord()`. | Field | Type | Description | |---|---|---| | `attachment` | `?bool` | Controls `Content-Disposition: attachment` (default `true`; pass `null` to omit). | diff --git a/docs/runs.md b/docs/runs.md index f767e34..9230711 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -30,7 +30,9 @@ An Actor's or task's runs are available at `$client->actor($id)->runs()` / `$cli - `waitForFinish(?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun`: `$timeoutSecs` is the timeout of each poll request (default `'noTimeout'`). - `dataset(): DatasetClient`, `keyValueStore(): KeyValueStoreClient`, `requestQueue(): RequestQueueClient`: a 404 from `get()` or `delete()` is thrown, since the client cannot tell a missing run from a missing storage. - `iterateDatasetItems(?RunIterateDatasetItemsOptions $options = null, int|float|string|null $timeoutSecs = null): Generator`: lazily yields the items of the default dataset while the run is producing them, and returns when the run has finished and the dataset is drained. `$timeoutSecs` is the timeout of each request, polls included (default: the `long` tier). See [below](#reading-a-dataset-while-the-run-is-running). -- `log(): LogClient`, `getStreamedLog(): StreamInterface`: `log()->get()` throws on a 404 for the same reason. +- `log(): LogClient`: `log()->get()` and `log()->stream()` throw on a 404 for the same reason. +- `getStreamedLog(int|float|string|null $timeoutSecs = null): StreamInterface`: the raw log of the run as a stream, to read yourself. Read it to the end. +- `redirectLog(?callable $toLog = null, ?DateTimeInterface $since = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): void`: hands the log of the run to `$toLog` message by message while the run produces it, and returns once the run has finished and its log is read to the end, or after `$waitSecs`. `call()` of an Actor or a task uses it while it waits. A message starts with its timestamp, and a line without one is handed over as it is. `$since` skips the messages logged before it. By default, the messages go to the standard error stream, behind `{Actor name} runId:{run ID} -> `. A stream that is cut off while the run goes on is reopened, and the redirection resumes at the line where the stream was cut. `$timeoutSecs` is the timeout of the requests that fetch the run and its Actor. It throws the API error of a request that fails, and an `ApifyClientException` when a reopened stream is cut again before it reaches the point where the previous stream was cut. A stream that fails before it delivered anything throws its error. ```php $run = $client->run('RUN_ID')->waitForFinish(120); diff --git a/docs/storages.md b/docs/storages.md index 02fc95c..c46b29d 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -20,10 +20,10 @@ Single — `$client->dataset($id)`: - `listItems(?DatasetListItemsOptions $options = null): PaginationList`: one page of items decoded to PHP values. - `iterateItems(?DatasetListItemsOptions $options = null, ?int $chunkSize = null): iterable`: lazily yields the items. The `limit` option caps the total (unset for all), `$chunkSize` is the page size. Dataset items have no default limit, so without `$chunkSize` the first request loads the whole dataset. The iterator advances by the `getCount()` of a page (the rows the API scanned, or the items when that is larger), not by its number of items, which matters with `skipEmpty`, `clean` and `unwind`. - `downloadItems(DownloadItemsFormat $format, ?DatasetDownloadOptions $options = null): string`: the export as bytes. -- `streamItems(DownloadItemsFormat $format, ?DatasetDownloadOptions $options = null): StreamInterface`: the export of `downloadItems()` as a PSR-7 stream, so a large export can be read in chunks, for example piped to a file. It is not retried. +- `streamItems(DownloadItemsFormat $format, ?DatasetDownloadOptions $options = null, int|float|string|null $timeoutSecs = null): StreamInterface`: the export of `downloadItems()` as a PSR-7 stream, so a large export can be read in chunks, for example piped to a file. Opening the stream is retried like any request, and a failure while the body is being read is not. The default timeout is the `long` tier. - `pushItems(mixed $items): void` - `getStatistics(): ?array`: throws if the dataset does not exist. -- `createItemsPublicUrl(?DatasetListItemsOptions $options = null, ?int $expiresInSecs = null, ?DownloadItemsFormat $format = null, int|float|string|null $timeoutSecs = null): string`: builds a public URL for downloading the items, with the filters of the options. The URL of a private dataset is signed, and valid for `$expiresInSecs` if given. It must be positive, otherwise `InvalidArgumentException` is thrown before any request. Omit it for a URL that never expires. `$format` is the output format (default `json`). `$timeoutSecs` is for the request that fetches the dataset (default: the `long` tier). +- `createItemsPublicUrl(?DatasetListItemsOptions $options = null, ?int $expiresInSecs = null, ?DownloadItemsFormat $format = null, int|float|string|null $timeoutSecs = null): string`: builds a public URL for downloading the items. The URL of a private dataset is signed, and valid for `$expiresInSecs` if given. `$expiresInSecs` must be positive, otherwise `InvalidArgumentException` is thrown before any request. Omit it for a URL that never expires. The signature grants read access to all items for as long as the URL is valid. The options are plain query parameters that it does not cover, so they only set the default response, and anyone with the URL can change them. `$format` is the output format (default `json`). `$timeoutSecs` is for the request that fetches the dataset (default: the `long` tier). ```php $dataset = $client->datasets()->getOrCreate('my-dataset'); @@ -60,11 +60,12 @@ Single — `$client->keyValueStore($id)`: - `iterateKeys(?ListKeysOptions $options = null, ?int $chunkSize = null): iterable`: lazily yields the keys, following the cursor pages. The `limit` option caps the total (unset for all), `$chunkSize` is the page size (unset for the remaining total, or the API's default without a limit). - `recordExists(string $key): bool`: returns whether the record exists, without downloading it (a `HEAD` request). - `getRecord(string $key, ?GetRecordOptions $options = null): ?KeyValueStoreRecord`: `getValue()` returns the bytes the API sent, whatever the content type, so decode a JSON record yourself. +- `streamRecord(string $key, ?GetRecordOptions $options = null, int|float|string|null $timeoutSecs = null): ?KeyValueStoreRecordStream`: the record of `getRecord()` as a PSR-7 stream, so a large record can be read in chunks, for example piped to a file. It returns `null` if the record does not exist. Opening the stream is retried like any request, and a failure while the body is being read is not. The default timeout is the `long` tier. Close it when you stop reading. - `setRecord(string $key, string $value, string $contentType, ?SetRecordOptions $options = null, ?string $contentEncoding = null): void`: `$value` is sent as it is, also under `application/json`, so it must already be valid JSON. Use `setRecordJson()` to have a value encoded. `$contentEncoding` is the `Content-Encoding` of a `$value` that is already compressed, for example `gzip`, `br`, or `zstd`. The bytes are then sent as they are, without further compression. - `setRecordJson(string $key, mixed $value, ?SetRecordOptions $options = null): void`: JSON-encodes `$value` and stores it as a JSON record. - `deleteRecord(string $key): void`: deletes the record. - `getRecordPublicUrl(string $key, int|float|string|null $timeoutSecs = null): string`: builds a public URL of a record. The URL of a private store is signed, so it works without a token. -- `createKeysPublicUrl(?ListKeysOptions $options = null, ?int $expiresInSecs = null, int|float|string|null $timeoutSecs = null): string`: builds a public URL for listing the keys, with the filters of the options. The URL of a private store is signed, and valid for `$expiresInSecs` if given. It must be positive, otherwise `InvalidArgumentException` is thrown before any request. Omit it for a URL that never expires. `$timeoutSecs` is for the request that fetches the store (default: the `long` tier). +- `createKeysPublicUrl(?ListKeysOptions $options = null, ?int $expiresInSecs = null, int|float|string|null $timeoutSecs = null): string`: builds a public URL for listing the keys. The URL of a private store is signed, and valid for `$expiresInSecs` if given. `$expiresInSecs` must be positive, otherwise `InvalidArgumentException` is thrown before any request. Omit it for a URL that never expires. The signature grants access to the list of all keys for as long as the URL is valid. The options are plain query parameters that it does not cover, so they only set the default response, and anyone with the URL can change them. `$timeoutSecs` is for the request that fetches the store (default: the `long` tier). ```php $store = $client->keyValueStores()->getOrCreate('my-store'); diff --git a/docs/tasks.md b/docs/tasks.md index cc4d129..ef69ab5 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -24,13 +24,13 @@ foreach ($client->tasks()->iterate(new ListOptions(), 50) as $t) { ## A single task — `$client->task($id)` - `get(): ?Task`, `update(mixed $newFields): Task`, `delete(): void` -- `publish(): Task`, `unpublish(): Task`: publish or unpublish the public landing page by setting `isPublic`. +- `publish(int|float|string|null $timeoutSecs = null): Task`, `unpublish(int|float|string|null $timeoutSecs = null): Task`: publish or unpublish the public landing page by setting `isPublic`. Both need write permission to the Actor of the task. Publishing also needs a public Actor and the `publicConfig.inputSchemaFields` and `publicConfig.datasetView` of the task. An Actor can have 10 published tasks and an account 100. If a condition fails, nothing changes. - `start(mixed $input = null, ?TaskStartOptions $options = null): ActorRun`: `$options->waitForResources` is as for [`ActorClient::start()`](actors.md). -- `call(mixed $input = null, ?TaskStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun` +- `call(mixed $input = null, ?TaskStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null, callable|false|null $log = null): ActorRun`: start and wait. `$log` is where the log of the run goes while the call waits: by default each message goes to the standard error stream, behind `{Actor name} runId:{run ID} -> `. Pass a callable that takes the message, or `false` for no redirection. A failure to redirect prints a warning and the call waits without it. See [`RunClient::redirectLog()`](runs.md). - `getInput(): mixed` (throws if the task does not exist), `updateInput(mixed $input): mixed` - `lastRun(?LastRunOptions $options = null): RunClient` - `runs(): RunCollectionClient` diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 21a6f5b..08566d0 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,8 +1,5 @@ -# Level 8 checks types, nullable access, and union types. Level 9 adds strict `mixed` handling. The client exposes -# `mixed` on purpose at the API boundary (JSON input, record values, `toArray()`), so it stays at level 8. parameters: - level: 8 + level: 9 paths: - src - tests - treatPhpDocTypesAsCertain: false diff --git a/src/ApifyClient.php b/src/ApifyClient.php index 3971345..8ee3261 100644 --- a/src/ApifyClient.php +++ b/src/ApifyClient.php @@ -103,6 +103,13 @@ final class ApifyClient * is not loaded throws {@see RuntimeException}. * {@code null} picks brotli when its extension is * loaded, gzip otherwise. + * @param array $headers headers sent with every request, for example an + * integration marker; they replace the built-in + * {@code User-Agent} and token headers, and a header + * a call sets for itself replaces them. A + * {@code Authorization} header is sent as + * {@code X-Apify-Authorization} to an Actor server, + * so the Actor never receives it */ public function __construct( ?string $token = null, @@ -122,6 +129,7 @@ public function __construct( ?StreamFactoryInterface $streamFactory = null, ?callable $isAtHomeFn = null, string|HttpCompressorInterface|null $compression = null, + array $headers = [], ) { $transport = $httpClient ?? new GuzzleHttpClient(); $factory = new HttpFactory(); @@ -146,7 +154,7 @@ public function __construct( ); $userAgent = self::buildUserAgent($userAgentSuffix, $isAtHomeFn ?? self::defaultIsAtHome(...)); - $this->http = new HttpClientCore($transport, $requestFactory, $streamFactory, $token, $userAgent, $retry, $compressor); + $this->http = new HttpClientCore($transport, $requestFactory, $streamFactory, $token, $userAgent, $retry, $compressor, $headers); $this->baseUrl = self::toApiBaseUrl($baseUrl); $this->publicBaseUrl = self::toApiBaseUrl($publicBaseUrl ?? $baseUrl); @@ -287,7 +295,7 @@ public function webhookDispatch(string $id): WebhookDispatchClient return new WebhookDispatchClient($this->http, $this->baseUrl, $id); } - /** A client for the Apify Store. */ + /** A client for Apify Store. */ public function store(): StoreCollectionClient { return new StoreCollectionClient($this->http, $this->baseUrl); diff --git a/src/Http/GuzzleHttpClient.php b/src/Http/GuzzleHttpClient.php index cc60cf7..c5b81eb 100644 --- a/src/Http/GuzzleHttpClient.php +++ b/src/Http/GuzzleHttpClient.php @@ -20,6 +20,9 @@ final class GuzzleHttpClient implements NoRedirectHttpClientInterface /** Connection-establishment timeout (distinct from the per-request timeout the client applies). */ private const CONNECT_TIMEOUT_SECS = 30.0; + /** The cURL error number of a timed-out operation ({@code CURLE_OPERATION_TIMEDOUT}). */ + private const CURLE_OPERATION_TIMEDOUT = 28; + private Guzzle $client; public function __construct(?Guzzle $client = null) @@ -64,7 +67,7 @@ private function isTimeout(ConnectException $e): bool { $context = $e->getHandlerContext(); $errno = isset($context['errno']) ? (int) $context['errno'] : 0; - // 28 == CURLE_OPERATION_TIMEDOUT. Fall back to a substring check for non-cURL handlers. - return $errno === 28 || stripos($e->getMessage(), 'timed out') !== false; + // Fall back to a substring check for non-cURL handlers. + return $errno === self::CURLE_OPERATION_TIMEDOUT || stripos($e->getMessage(), 'timed out') !== false; } } diff --git a/src/Internal/HttpClientCore.php b/src/Internal/HttpClientCore.php index 95ab027..345fd87 100644 --- a/src/Internal/HttpClientCore.php +++ b/src/Internal/HttpClientCore.php @@ -57,6 +57,14 @@ public function __construct( private RetryConfig $retry, /** Replaces the default compression (brotli, then gzip). */ private ?HttpCompressorInterface $compressor = null, + /** + * Sent with every request. They replace the {@code User-Agent} and the token header, and the headers a call + * sets for itself replace them. An {@code Authorization} header goes in the header that carries the token of + * the request, which is {@code X-Apify-Authorization} for an Actor server. + * + * @var array + */ + private array $headers = [], ) { } @@ -107,7 +115,7 @@ public function call( $delayMillis = $this->retry->minDelayMillis; $maxAttempts = $this->retry->maxRetries + 1; - $path = self::extractPath($url); + $path = UrlParts::pathAndQuery($url); $baseTimeout = $timeoutSecs ?? $this->retry->timeoutSecs; $lastError = null; @@ -217,15 +225,8 @@ private static function headerValue(array $headers, string $name): ?string return null; } - /** Opens a streaming response. Makes a single attempt. */ - public function stream(string $url): ResponseInterface - { - $request = $this->buildRequest('GET', $url, null, '', [], RequestPolicy::AUTHORIZATION_HEADER); - return $this->transport->sendStreaming($request, $this->retry->timeoutSecs); - } - /** - * Builds a PSR-7 request with the token, User-Agent, content type, and extra headers. + * Builds a PSR-7 request with the token, User-Agent, client-wide headers, content type, and extra headers. * * @param array $extraHeaders * @param string $authorizationHeader the header that carries the token @@ -243,6 +244,12 @@ private function buildRequest( if ($this->token !== null && $this->token !== '') { $request = $request->withHeader($authorizationHeader, 'Bearer ' . $this->token); } + foreach ($this->headers as $name => $value) { + // A client-wide token header replaces the built-in one, so it must go where the built-in one goes. Sent + // as it is to an Actor server, it would hand the API credential to the Actor, which is third-party code. + $isTokenHeader = strcasecmp($name, RequestPolicy::AUTHORIZATION_HEADER) === 0; + $request = $request->withHeader($isTokenHeader ? $authorizationHeader : $name, $value); + } if ($contentType !== '') { $request = $request->withHeader('Content-Type', $contentType); } @@ -365,18 +372,6 @@ public static function buildApiError(int $status, string $body, int $attempt, st return new $exceptionClass($status, $type, $message, $attempt, $method, $path, $data); } - /** The path and query of a URL, for error messages. */ - public static function extractPath(string $url): string - { - $rest = $url; - $scheme = strpos($rest, '://'); - if ($scheme !== false) { - $rest = substr($rest, $scheme + 3); - } - $slash = strpos($rest, '/'); - return $slash !== false ? substr($rest, $slash) : ''; - } - /** Whether the exception is an API error with status 404, whatever its type. */ public static function isNotFound(Throwable $e): bool { diff --git a/src/Internal/LogRedirection.php b/src/Internal/LogRedirection.php new file mode 100644 index 0000000..30f0eae --- /dev/null +++ b/src/Internal/LogRedirection.php @@ -0,0 +1,41 @@ +redirectLog($log, null, $waitSecs); + } catch (Exception $e) { + (new StderrLogSink('apify-client: '))('Waiting for the run without log redirection: ' . $e->getMessage()); + } + if ($waitSecs !== null) { + $waitSecs = max(0, (int) ceil($waitSecs - (microtime(true) - $start))); + } + } + return $run->waitForFinish($waitSecs, $timeoutSecs); + } +} diff --git a/src/Internal/ResourceContext.php b/src/Internal/ResourceContext.php index 8d4c6c3..ea7338b 100644 --- a/src/Internal/ResourceContext.php +++ b/src/Internal/ResourceContext.php @@ -64,7 +64,7 @@ private function __construct( private bool $hasId = true, ) { $this->baseParams = new QueryParams(); - $this->apiOrigin = self::originOf($baseUrl); + $this->apiOrigin = UrlParts::origin($baseUrl); $this->publicOrigin = $this->apiOrigin; } @@ -91,7 +91,7 @@ public static function single(HttpClientCore $http, string $baseUrl, string $res /** Sets the origin of public URLs. */ public function withPublicOrigin(string $publicBaseUrl): self { - $this->publicOrigin = self::originOf($publicBaseUrl); + $this->publicOrigin = UrlParts::origin($publicBaseUrl); return $this; } @@ -409,24 +409,51 @@ public function headExists(string $subPath, QueryParams $params, ?float $timeout } /** - * Opens a streaming GET and returns the body, which is read incrementally. It is not retried, and an error - * status is thrown as the matching {@see ApifyApiException}. + * Opens a streaming GET and returns the body, which is read incrementally. Opening it follows the retry + * policy of any request, so a rate limit, a server error, or a transport error before the body starts is + * retried. A failure after the body has started is not. An error status is thrown as the matching + * {@see ApifyApiException}, with the error body read into it. */ - public function streamRaw(string $subPath, QueryParams $params): StreamInterface + public function streamRaw(string $subPath, QueryParams $params, float $timeoutSecs): StreamInterface { - $url = $this->mergedParams($params)->applyToUrl($this->subUrl($subPath)); - $response = $this->http->stream($url); - if ($response->getStatusCode() >= HttpClientCore::MAX_SUCCESS_STATUS) { - $body = (string) $response->getBody(); - throw HttpClientCore::buildApiError( - $response->getStatusCode(), - $body, - 1, - 'GET', - HttpClientCore::extractPath($url) - ); + return $this->streamRawResponse($subPath, $params, $timeoutSecs)->getBody(); + } + + /** + * Like {@see streamRaw()}, but returns {@code null} if the resource is not found (see {@see getRaw()}). + */ + public function streamRawOrNull(string $subPath, QueryParams $params, float $timeoutSecs): ?StreamInterface + { + return $this->streamRawResponseOrNull($subPath, $params, $timeoutSecs)?->getBody(); + } + + /** + * Like {@see streamRawResponse()}, but returns {@code null} if the resource is not found (see {@see getRaw()}). + */ + public function streamRawResponseOrNull(string $subPath, QueryParams $params, float $timeoutSecs): ?ResponseInterface + { + try { + return $this->streamRawResponse($subPath, $params, $timeoutSecs); + } catch (ApifyApiException $e) { + if (HttpClientCore::isNotFound($e) && $this->swallowsNotFound($subPath)) { + return null; + } + throw $e; } - return $response->getBody(); + } + + /** + * Like {@see streamRaw()}, but returns the whole response, for its headers. + */ + public function streamRawResponse(string $subPath, QueryParams $params, float $timeoutSecs): ResponseInterface + { + $url = $this->mergedParams($params)->applyToUrl($this->subUrl($subPath)); + return $this->http->call( + 'GET', + $url, + timeoutSecs: $timeoutSecs, + policy: new RequestPolicy(stream: true) + ); } /** @@ -592,21 +619,4 @@ public static function encodePathSegment(string $input): string } return rawurlencode($input); } - - /** The origin of a URL: {@code scheme://host[:port]}. */ - public static function originOf(string $rawUrl): string - { - $rest = $rawUrl; - $scheme = ''; - $pos = strpos($rest, '://'); - if ($pos !== false) { - $scheme = substr($rest, 0, $pos + 3); - $rest = substr($rest, $pos + 3); - } - $slash = strpos($rest, '/'); - if ($slash !== false) { - $rest = substr($rest, 0, $slash); - } - return $scheme . $rest; - } } diff --git a/src/Internal/Signatures.php b/src/Internal/Signatures.php index 288fa15..f8ff8c6 100644 --- a/src/Internal/Signatures.php +++ b/src/Internal/Signatures.php @@ -19,6 +19,12 @@ final class Signatures /** The number of leading hex characters of the HMAC digest that are used. */ private const HMAC_SIGNATURE_HEX_LEN = 30; + /** The number of values of a byte. */ + private const BYTE_RADIX = 256; + + /** The number of characters of {@see BASE62_ALPHABET}. */ + private const BASE62_RADIX = 62; + /** The base62 alphabet: digits, lowercase, uppercase. */ private const BASE62_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; @@ -80,9 +86,9 @@ private static function hexToBase62(string $hex): string $remainder = 0; $quotient = []; foreach ($digits as $byte) { - $accumulator = $remainder * 256 + $byte; - $q = intdiv($accumulator, 62); - $remainder = $accumulator % 62; + $accumulator = $remainder * self::BYTE_RADIX + $byte; + $q = intdiv($accumulator, self::BASE62_RADIX); + $remainder = $accumulator % self::BASE62_RADIX; if ($quotient !== [] || $q !== 0) { $quotient[] = $q; } diff --git a/src/Internal/StderrLogSink.php b/src/Internal/StderrLogSink.php new file mode 100644 index 0000000..c918aa1 --- /dev/null +++ b/src/Internal/StderrLogSink.php @@ -0,0 +1,50 @@ +stream = $stream; + } + + /** The sink of a run: {@code "{actorName} runId:{runId} -> "} in front of every message. */ + public static function forRun(?string $actorName, string $runId): self + { + $parts = array_filter([$actorName ?? '', $runId === '' ? '' : 'runId:' . $runId], static fn (string $part): bool => $part !== ''); + return new self(implode(' ', $parts) . ' -> '); + } + + public function getPrefix(): string + { + return $this->prefix; + } + + public function __invoke(string $message): void + { + if ($this->stream === null) { + $opened = fopen('php://stderr', 'wb'); + if ($opened === false) { + return; + } + $this->stream = $opened; + } + fwrite($this->stream, $this->prefix . $message . PHP_EOL); + } +} diff --git a/src/Internal/StoreFilters.php b/src/Internal/StoreFilters.php new file mode 100644 index 0000000..d319d1f --- /dev/null +++ b/src/Internal/StoreFilters.php @@ -0,0 +1,35 @@ +addString('category', $category) + ->addString('username', $username) + ->addString('pricingModel', $pricingModel) + ->addBool('includeUnrunnableActors', $includeUnrunnableActors) + ->addString('responseFormat', $responseFormat) + ->addBool('includeInputSchema', $includeInputSchema); + } +} diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php new file mode 100644 index 0000000..f04e27a --- /dev/null +++ b/src/Internal/StreamedLog.php @@ -0,0 +1,296 @@ +sink = $sink; + $this->since = $since === null + ? null + : DateTimeImmutable::createFromInterface($since)->setTimezone(new DateTimeZone('UTC'))->format(self::TIMESTAMP_FORMAT); + } + + /** + * Redirects the log until the run has finished and its log is read to the end, or until the deadline. + * + * @param callable(): bool $runFinished whether the run has finished, asked when a stream ends + * @param float|null $deadline a {@code microtime(true)} value at which to stop, {@code null} for none + * + * @throws ApifyClientException if a reopened stream is cut again before it reaches where the stream before it was + */ + public function redirect(callable $runFinished, ?float $deadline = null): void + { + $emptyRetryMillis = self::EMPTY_STREAM_RETRY_MILLIS; + while (!self::passed($deadline)) { + $timeLeft = $deadline === null ? null : $deadline - microtime(true); + if ($timeLeft !== null && $timeLeft < self::MIN_STREAM_TIMEOUT_SECS) { + return; + } + try { + // A read that waits for a quiet run must not outlast the deadline, so the stream gets the time left. + $stream = $this->logClient->stream(new LogOptions(raw: true), $timeLeft); + } catch (Exception $e) { + // A request that was still going when the time ran out is not a failure of the redirection. + if (self::passed($deadline)) { + return; + } + throw $e; + } + if ($stream === null) { + return; + } + $outcome = $this->redirectStream($stream, $deadline, $runFinished); + if ($outcome === self::OUTCOME_DEADLINE) { + return; + } + if ($this->receivedData) { + if ($outcome === self::OUTCOME_ENDED) { + return; + } + self::pause(self::BROKEN_STREAM_REOPEN_MILLIS, $deadline); + continue; + } + if ($runFinished()) { + // A run that finished without a stream delivering anything: read what it logged in one request. + $this->redirectWholeLog(); + return; + } + self::pause($emptyRetryMillis, $deadline); + $emptyRetryMillis = min($emptyRetryMillis * 2, self::EMPTY_STREAM_MAX_RETRY_MILLIS); + } + } + + private function redirectWholeLog(): void + { + $log = $this->logClient->get(new LogOptions(raw: true)); + if ($log !== null && $log !== '') { + $this->receivedData = true; + $this->redirectMessages($log); + } + } + + /** + * Redirects one stream until it ends, breaks off, or the deadline passes. A stream that ends cleanly after it + * delivered data while the run has not finished was cut, which the transport does not always report as an error. + * + * @param callable(): bool $runFinished + * + * @return self::OUTCOME_* + */ + private function redirectStream(StreamInterface $stream, ?float $deadline, callable $runFinished): string + { + // A reopened stream replays the log from its start, so it first skips what was handled already. + $toSkip = $this->handledBytes; + // A chunk may end in the middle of a line. The incomplete rest waits here for the next chunk, and starts + // with the end of line before it, which a timestamp has to follow to be the start of a message. + $remainder = ''; + $outcome = self::OUTCOME_ENDED; + while (!$stream->eof()) { + if (self::passed($deadline)) { + $outcome = self::OUTCOME_DEADLINE; + break; + } + try { + $chunk = $stream->read(self::READ_CHUNK_BYTES); + } catch (RuntimeException $e) { + if (self::passed($deadline)) { + // The read timed out because the time ran out, which is not a cut. + $outcome = self::OUTCOME_DEADLINE; + break; + } + // A stream that failed before it delivered anything is not a cut, so it is not reopened. + if (!$this->receivedData) { + throw $e; + } + return $this->reopenAfterCut($stream, $toSkip, $e); + } + if ($chunk === '') { + usleep(self::EMPTY_READ_PAUSE_MICROS); + continue; + } + $this->receivedData = true; + if ($toSkip > 0) { + $skipped = min(strlen($chunk), $toSkip); + $toSkip -= $skipped; + $chunk = substr($chunk, $skipped); + if ($chunk === '') { + continue; + } + } + $text = $remainder . $chunk; + // Everything before the last end of line is complete. + $lastNewline = strrpos($text, "\n"); + if ($lastNewline === false) { + $remainder = $text; + continue; + } + $remainder = substr($text, $lastNewline); + $this->handledBytes += $lastNewline; + $this->redirectMessages(substr($text, 0, $lastNewline)); + } + + if ($outcome === self::OUTCOME_ENDED && $this->receivedData && !$runFinished()) { + return $this->reopenAfterCut($stream, $toSkip, null); + } + + // Maybe it is incomplete, maybe it is the last message without an end of line. + $this->redirectMessages($remainder); + $stream->close(); + return $outcome; + } + + /** + * Prepares the reopening of a stream that was cut. The reopened stream replays the log and skips the handled + * bytes, so the unfinished line, which is dropped here, is read again whole. + * + * @param int $toSkip how many bytes of the replay this stream had still to skip when it was cut + * + * @return self::OUTCOME_BROKE_OFF + * + * @throws ApifyClientException if the stream is a reopened one that was cut before it got as far as the one before + */ + private function reopenAfterCut(StreamInterface $stream, int $toSkip, ?RuntimeException $cause): string + { + if ($toSkip > 0) { + throw new ApifyClientException( + 'Log redirection stopped: the reopened log stream was cut again before it reached the point where the previous stream was cut.', + 0, + $cause + ); + } + $stream->close(); + return self::OUTCOME_BROKE_OFF; + } + + /** Splits complete text into messages and hands each one to the sink. */ + private function redirectMessages(string $text): void + { + $parts = preg_split(self::MESSAGE_START, $text, -1, PREG_SPLIT_DELIM_CAPTURE); + if ($parts === false) { + return; + } + // Text before the first timestamp continues a message that an earlier chunk started. + $leading = trim((string) array_shift($parts)); + if ($leading !== '' && !$this->lastMessageSkipped) { + ($this->sink)($leading); + } + + for ($i = 0; $i + 1 < count($parts); $i += 2) { + $timestamp = $parts[$i]; + $this->lastMessageSkipped = $this->since !== null && $timestamp < $this->since; + if ($this->lastMessageSkipped) { + continue; + } + // The original log level is not available, so every message is redirected as it is. + ($this->sink)(trim($timestamp . $parts[$i + 1])); + } + } + + /** + * Whether the deadline has passed. The answer changes with the time, so it is asked again, not remembered. + * + * @phpstan-impure + */ + private static function passed(?float $deadline): bool + { + return $deadline !== null && microtime(true) >= $deadline; + } + + /** Sleeps for the given time, or until the deadline if that comes first. */ + private static function pause(int $millis, ?float $deadline): void + { + if ($deadline !== null) { + $millis = min($millis, max(0, (int) floor(($deadline - microtime(true)) * self::MILLIS_PER_SEC))); + } + if ($millis > 0) { + usleep($millis * self::MICROS_PER_MILLI); + } + } +} diff --git a/src/Internal/UrlParts.php b/src/Internal/UrlParts.php new file mode 100644 index 0000000..a18b19f --- /dev/null +++ b/src/Internal/UrlParts.php @@ -0,0 +1,41 @@ +key; + } + + /** The raw record bytes, as a stream. */ + public function getStream(): StreamInterface + { + return $this->stream; + } + + /** The record's MIME type, as reported by the API. */ + public function getContentType(): ?string + { + return $this->contentType; + } +} diff --git a/src/Model/StoreSearchResult.php b/src/Model/StoreSearchResult.php new file mode 100644 index 0000000..be4cd1c --- /dev/null +++ b/src/Model/StoreSearchResult.php @@ -0,0 +1,75 @@ + + */ +final class StoreSearchResult implements IteratorAggregate, Countable +{ + /** + * @internal + * + * @param list $items + */ + public function __construct( + private array $items, + private int $limit, + ) { + } + + /** + * Builds the result from a decoded Store response page. + * + * @internal + */ + public static function fromData(mixed $data): self + { + $page = PaginationList::fromData($data, static fn (array $d) => new ActorStoreListItem($d)); + return new self($page->getItems(), $page->getLimit()); + } + + /** + * The Actors matching the query, best match first. + * + * @return list + */ + public function getItems(): array + { + return $this->items; + } + + /** + * The maximum number of Actors the API allowed in this result: the requested limit, or the API's maximum when + * none or a larger one was requested. When the result holds that many Actors, more may match the query than + * were returned, so narrow the search with a more specific query or with the filters. + */ + public function getLimit(): int + { + return $this->limit; + } + + /** @return Traversable */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } + + public function count(): int + { + return count($this->items); + } +} diff --git a/src/Options/ActorServerRequestOptions.php b/src/Options/ActorServerRequestOptions.php index 62835f8..1534ae0 100644 --- a/src/Options/ActorServerRequestOptions.php +++ b/src/Options/ActorServerRequestOptions.php @@ -57,7 +57,11 @@ public function __construct( ) { } - /** The HTTP method in upper case. */ + /** + * The HTTP method in upper case. + * + * @internal + */ public function methodOrDefault(): string { return $this->method === null || $this->method === '' ? self::DEFAULT_METHOD : strtoupper($this->method); @@ -86,7 +90,10 @@ public function appendTo(QueryParams $q): void } } - /** @param list $values */ + /** + * @param list $values + * @phpstan-assert-if-true list $values + */ private static function isScalarList(array $values): bool { foreach ($values as $value) { diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index 830c250..65da6d5 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -5,8 +5,12 @@ namespace Apify\Client\Options; use Apify\Client\Internal\QueryParams; +use Apify\Client\Internal\StoreFilters; -/** Options for listing/iterating the Apify Store ({@code GET /v2/store}). */ +/** + * Options for browsing 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 {@see StoreSearchOptions}. + */ final class StoreListOptions { public function __construct( @@ -14,26 +18,28 @@ public function __construct( public readonly ?int $offset = null, /** * The maximum number of Actors. When iterating, it caps the total over all pages, not the page size - * ({@code chunkSize}). + * ({@code chunkSize}). With {@code includeInputSchema}, each request may ask for at most 10 Actors: the + * {@code limit} of {@code list()}, and for {@code iterate()} the smaller of {@code limit} and + * {@code chunkSize}. The API rejects a larger page size. */ public readonly ?int $limit = null, - /** Full-text search query. */ - public readonly ?string $search = null, - /** The sort field (e.g. {@code "popularity"}, {@code "newest"}). */ - public readonly ?string $sortBy = null, - /** Filter Actors by category. */ + /** Filter Actors by one or more comma-separated category IDs, such as {@code AI_AND_ML}. An Actor must match all of them. */ public readonly ?string $category = null, /** Filter Actors by owner username. */ public readonly ?string $username = null, /** Filters by pricing model ({@code FREE}, {@code PRICE_PER_DATASET_ITEM}, {@code PAY_PER_EVENT}). */ public readonly ?string $pricingModel = null, - /** Include Actors the current user cannot run. */ + /** + * By default, the API leaves out Actors that are not safe to run automatically, such as Actors of developers + * who have not verified their identity. If true, those Actors are included as well. + */ public readonly ?bool $includeUnrunnableActors = null, - /** Filter to Actors that allow agentic users. */ - public readonly ?bool $allowsAgenticUsers = null, /** The response format ({@code full}, {@code agent}). */ public readonly ?string $responseFormat = null, - /** Includes the compact input schema of the default build, when it succeeded and defines input properties. */ + /** + * Includes the compact input schema of the default build, when it succeeded and defines input properties. + * The page size must then be 10 or less, see {@code limit}. + */ public readonly ?bool $includeInputSchema = null, ) { } @@ -44,13 +50,10 @@ public function withPagination(?int $offset, ?int $limit): self return new self( $offset, $limit, - $this->search, - $this->sortBy, $this->category, $this->username, $this->pricingModel, $this->includeUnrunnableActors, - $this->allowsAgenticUsers, $this->responseFormat, $this->includeInputSchema, ); @@ -59,16 +62,15 @@ public function withPagination(?int $offset, ?int $limit): self /** @internal */ public function appendTo(QueryParams $q): void { - $q->addInt('offset', $this->offset) - ->addInt('limit', $this->limit) - ->addString('search', $this->search) - ->addString('sortBy', $this->sortBy) - ->addString('category', $this->category) - ->addString('username', $this->username) - ->addString('pricingModel', $this->pricingModel) - ->addBool('includeUnrunnableActors', $this->includeUnrunnableActors) - ->addBool('allowsAgenticUsers', $this->allowsAgenticUsers) - ->addString('responseFormat', $this->responseFormat) - ->addBool('includeInputSchema', $this->includeInputSchema); + $q->addInt('offset', $this->offset)->addInt('limit', $this->limit); + StoreFilters::append( + $q, + $this->category, + $this->username, + $this->pricingModel, + $this->includeUnrunnableActors, + $this->responseFormat, + $this->includeInputSchema, + ); } } diff --git a/src/Options/StoreSearchOptions.php b/src/Options/StoreSearchOptions.php new file mode 100644 index 0000000..1ac024f --- /dev/null +++ b/src/Options/StoreSearchOptions.php @@ -0,0 +1,65 @@ +list() to browse the Store.'); + } + if ($limit !== null && $limit <= 0) { + throw new InvalidArgumentException('The Store search limit must be positive.'); + } + } + + /** @internal */ + public function appendTo(QueryParams $q): void + { + $q->addString('search', $this->search)->addInt('limit', $this->limit); + StoreFilters::append( + $q, + $this->category, + $this->username, + $this->pricingModel, + $this->includeUnrunnableActors, + $this->responseFormat, + $this->includeInputSchema, + ); + } +} diff --git a/src/Resource/ActorClient.php b/src/Resource/ActorClient.php index ef861ba..5dbd0e2 100644 --- a/src/Resource/ActorClient.php +++ b/src/Resource/ActorClient.php @@ -6,6 +6,7 @@ use Apify\Client\ApifyClient; use Apify\Client\Internal\HttpClientCore; +use Apify\Client\Internal\LogRedirection; use Apify\Client\Internal\QueryParams; use Apify\Client\Internal\ResourceContext; use Apify\Client\Internal\TimeoutTiers; @@ -100,13 +101,24 @@ public function start( * {@code $options->waitForResources} start do not count. * @param int|float|string|null $timeoutSecs timeout of the start request and of each poll (default * {@code 'noTimeout'}) + * @param (callable(string): void)|false|null $log where the log of the run goes while the call waits. By default, + * each message goes to the standard error stream, behind + * {@code "{Actor name} runId:{run ID} -> "}. A callable receives each message, and + * {@code false} turns the redirection off. A failure to redirect the log does not fail + * the call: it prints a warning and waits without the redirection. See + * {@see RunClient::redirectLog()}. */ - public function call(mixed $input = null, ?ActorStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun - { + public function call( + mixed $input = null, + ?ActorStartOptions $options = null, + ?int $waitSecs = null, + int|float|string|null $timeoutSecs = null, + callable|false|null $log = null, + ): ActorRun { // The start request and every poll have no request timeout by default. $timeoutSecs ??= TimeoutTiers::NO_TIMEOUT; $run = $this->start($input, $options, $timeoutSecs); - return $this->root->run((string) $run->getId())->waitForFinish($waitSecs, $timeoutSecs); + return LogRedirection::waitForFinish($this->root->run((string) $run->getId()), $waitSecs, $timeoutSecs, $log); } /** diff --git a/src/Resource/ActorVersionClient.php b/src/Resource/ActorVersionClient.php index 7d28960..927875d 100644 --- a/src/Resource/ActorVersionClient.php +++ b/src/Resource/ActorVersionClient.php @@ -31,13 +31,14 @@ public function get(int|float|string|null $timeoutSecs = null): ?ActorVersion } /** - * Updates the version and returns it. + * Updates the version and returns it. The default timeout is the {@code long} tier, since the version can + * carry its source files. * * @param mixed $newFields any JSON-serializable fields */ public function update(mixed $newFields, int|float|string|null $timeoutSecs = null): ActorVersion { - return new ActorVersion($this->ctx->updateResource('', $newFields, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_SHORT))); + return new ActorVersion($this->ctx->updateResource('', $newFields, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG))); } /** Deletes the version. */ diff --git a/src/Resource/ActorVersionCollectionClient.php b/src/Resource/ActorVersionCollectionClient.php index 3e35c79..8486a9a 100644 --- a/src/Resource/ActorVersionCollectionClient.php +++ b/src/Resource/ActorVersionCollectionClient.php @@ -46,12 +46,13 @@ public function iterate(int|float|string|null $timeoutSecs = null): Generator } /** - * Creates a version of the Actor. + * Creates a version of the Actor. The default timeout is the {@code long} tier, since the version can carry + * its source files. * * @param mixed $version any JSON-serializable version definition */ public function create(mixed $version, int|float|string|null $timeoutSecs = null): ActorVersion { - return new ActorVersion($this->ctx->createResource(new QueryParams(), $version, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_SHORT))); + return new ActorVersion($this->ctx->createResource(new QueryParams(), $version, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG))); } } diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index f7b8a9e..1f98d25 100644 --- a/src/Resource/DatasetClient.php +++ b/src/Resource/DatasetClient.php @@ -101,8 +101,8 @@ public function listItems(?DatasetListItemsOptions $options = null, int|float|st * apply to every page. * * The filters {@code skipEmpty} and {@code clean}, and {@code unwind}, change the number of items per page, - * so the iterator advances as {@see ResourceContext::paginateOffset()} does: by the page's - * {@see PaginationList::getCount()}, capped at the limit asked for. + * so a page can hold fewer items than it scanned. The iterator advances by the rows a page + * scanned, or by the items it returned when that is larger, capped at the limit asked for. * * @return Generator */ @@ -139,8 +139,8 @@ public function downloadItems( } /** - * Opens a stream of the items in a format, so a large export can be read in chunks. The stream is not - * retried. + * Opens a stream of the items in a format, so a large export can be read in chunks. Opening the stream is + * retried like any request, but a failure while the body is being read is not. * * This is a separate method from {@see downloadItems()}, since a PHP method cannot change its return type * with an option. @@ -148,11 +148,12 @@ public function downloadItems( public function streamItems( DownloadItemsFormat $format, ?DatasetDownloadOptions $options = null, + int|float|string|null $timeoutSecs = null, ): StreamInterface { $params = new QueryParams(); $params->addString('format', $format->value); ($options ?? new DatasetDownloadOptions())->appendTo($params); - return $this->ctx->streamRaw('items', $params); + return $this->ctx->streamRaw('items', $params, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG)); } /** @@ -195,6 +196,10 @@ public function getStatistics(int|float|string|null $timeoutSecs = null): ?array * {@code $format} defaults to {@code json}. {@code $timeoutSecs} is for the request that fetches the * dataset (default: the {@code long} tier). * + * The signature grants read access to all items of the dataset for as long as the URL is valid. The options + * are added to the URL as plain query parameters that the signature does not cover, so they only set the + * default shape of the response. Anyone holding the URL can change or remove them. + * * @throws InvalidArgumentException if {@code $expiresInSecs} is zero or negative */ public function createItemsPublicUrl( diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index 66c82f2..77faaf5 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -14,6 +14,7 @@ use Apify\Client\Model\KeyValueStoreKey; use Apify\Client\Model\KeyValueStoreKeysPage; use Apify\Client\Model\KeyValueStoreRecord; +use Apify\Client\Model\KeyValueStoreRecordStream; use Apify\Client\Options\GetRecordOptions; use Apify\Client\Options\ListKeysOptions; use Apify\Client\Options\SetRecordOptions; @@ -169,6 +170,28 @@ public function getRecord(string $key, ?GetRecordOptions $options = null, int|fl return new KeyValueStoreRecord($key, (string) $response->getBody(), $contentType === '' ? null : $contentType); } + /** + * Opens a record as a stream, so a large record can be read in chunks, or returns {@code null} if it does not + * exist. Opening the stream is retried like any request, but a failure while the body is being read is not. + * This is a separate method from {@see getRecord()}, since a PHP method cannot change its return type with an + * option. + */ + public function streamRecord(string $key, ?GetRecordOptions $options = null, int|float|string|null $timeoutSecs = null): ?KeyValueStoreRecordStream + { + $params = new QueryParams(); + ($options ?? new GetRecordOptions())->appendTo($params); + $response = $this->ctx->streamRawResponseOrNull( + 'records/' . ResourceContext::encodePathSegment($key), + $params, + $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG) + ); + if ($response === null) { + return null; + } + $contentType = $response->getHeaderLine('Content-Type'); + return new KeyValueStoreRecordStream($key, $response->getBody(), $contentType === '' ? null : $contentType); + } + /** * Stores a record of raw bytes. {@code $value} is sent as it is, also under {@code application/json}, so it * must already be valid JSON. Use {@see setRecordJson()} to have a value encoded. @@ -234,10 +257,13 @@ public function getRecordPublicUrl(string $key, int|float|string|null $timeoutSe } /** - * Builds a public URL for listing the keys, with the filters of {@code $options}. As for - * {@see getRecordPublicUrl()}, the URL of a private store is signed, unless the options carry a signature. - * {@code $expiresInSecs} limits the validity of a signed URL. {@code $timeoutSecs} is for the request that - * fetches the store (default: the {@code long} tier). + * Builds a public URL for listing the keys. As for {@see getRecordPublicUrl()}, the URL of a private store + * is signed, unless the options carry a signature. {@code $expiresInSecs} limits the validity of a signed URL. + * {@code $timeoutSecs} is for the request that fetches the store (default: the {@code long} tier). + * + * The signature grants access to the list of all keys of the store for as long as the URL is valid. The + * options are added to the URL as plain query parameters that the signature does not cover, so they only set + * the default shape of the response. Anyone holding the URL can change or remove them. * * @throws InvalidArgumentException if {@code $expiresInSecs} is zero or negative */ diff --git a/src/Resource/LogClient.php b/src/Resource/LogClient.php index 171c6e6..21377b3 100644 --- a/src/Resource/LogClient.php +++ b/src/Resource/LogClient.php @@ -52,12 +52,18 @@ public function get(?LogOptions $options = null, int|float|string|null $timeoutS return $response === null ? null : (string) $response->getBody(); } - /** Opens a stream of the log, to follow it while the run produces it. The stream is not retried. */ - public function stream(?LogOptions $options = null): StreamInterface + /** + * Opens a stream of the log, to follow it while the run produces it, or returns {@code null} if the log does + * not exist. A client without an ID, such as {@see \Apify\Client\Resource\RunClient::log()} or + * {@see \Apify\Client\Resource\BuildClient::log()}, rethrows the 404, like {@see get()}. + * + * Opening the stream is retried like any request, but a failure while the log is being read is not. + */ + public function stream(?LogOptions $options = null, int|float|string|null $timeoutSecs = null): ?StreamInterface { $params = new QueryParams(); $params->addBool('stream', true); ($options ?? new LogOptions())->appendTo($params); - return $this->ctx->streamRaw('', $params); + return $this->ctx->streamRawOrNull('', $params, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG)); } } diff --git a/src/Resource/RunClient.php b/src/Resource/RunClient.php index 4d0ddfc..55b4766 100644 --- a/src/Resource/RunClient.php +++ b/src/Resource/RunClient.php @@ -5,11 +5,14 @@ namespace Apify\Client\Resource; use Apify\Client\ApifyClient; +use Apify\Client\Exception\ApifyClientException; use Apify\Client\Internal\DatasetItemsPage; use Apify\Client\Internal\HttpClientCore; use Apify\Client\Internal\Json; use Apify\Client\Internal\QueryParams; use Apify\Client\Internal\ResourceContext; +use Apify\Client\Internal\StderrLogSink; +use Apify\Client\Internal\StreamedLog; use Apify\Client\Internal\TimeoutTiers; use Apify\Client\Model\ActorRun; use Apify\Client\Options\DatasetListItemsOptions; @@ -19,6 +22,7 @@ use Apify\Client\Options\RunChargeOptions; use Apify\Client\Options\RunIterateDatasetItemsOptions; use Apify\Client\Options\RunResurrectOptions; +use DateTimeInterface; use Generator; use InvalidArgumentException; use Psr\Http\Message\StreamInterface; @@ -254,10 +258,54 @@ public function log(): LogClient return LogClient::nested($this->http, $this->ctx->subUrl(''), $this->ctx->baseParams); } - /** Opens a stream of the raw log of the run. Read it to the end. */ - public function getStreamedLog(): StreamInterface + /** + * Opens a stream of the raw log of the run, to read it yourself. Read it to the end. To have the messages + * handed to a callable instead, use {@see redirectLog()}. + * + * @throws \Apify\Client\Exception\NotFoundException if the run or its log does not exist + */ + public function getStreamedLog(int|float|string|null $timeoutSecs = null): StreamInterface + { + // The log client of a run has no ID of its own, so it rethrows a 404 and never returns null. + return $this->log()->stream(new LogOptions(raw: true), $timeoutSecs) + ?? throw new ApifyClientException('The log of the run was not found.'); + } + + /** + * Redirects the log of the run, message by message, while the run produces it. It returns once the run has + * finished and its log is read to the end, or after {@code $waitSecs}. This is what {@code call()} of an Actor + * or a task does while it waits. + * + * A stream that is cut off while the run goes on is reopened, and the redirection resumes at the line where the + * stream was cut. A message starts with its timestamp, and a line without one is redirected as it is. + * + * @param (callable(string): void)|null $toLog receives each message. By default, the messages go to the + * standard error stream, behind {@code "{Actor name} runId:{run ID} -> "}. + * @param DateTimeInterface|null $since redirect only the messages logged at this time or later + * @param int|null $waitSecs stops after this many seconds ({@code null} waits for the run to finish) + * @param int|float|string|null $timeoutSecs timeout of the requests that fetch the run and its Actor + */ + public function redirectLog( + ?callable $toLog = null, + ?DateTimeInterface $since = null, + ?int $waitSecs = null, + int|float|string|null $timeoutSecs = null, + ): void { + $deadline = $waitSecs === null ? null : microtime(true) + $waitSecs; + $sink = $toLog ?? $this->defaultLogSink($timeoutSecs); + (new StreamedLog($this->log(), $sink, $since))->redirect( + fn (): bool => ($this->get(timeoutSecs: $timeoutSecs)?->isTerminal() ?? true), + $deadline + ); + } + + /** The sink that prefixes each message with the name of the Actor and the ID of the run. */ + private function defaultLogSink(int|float|string|null $timeoutSecs): StderrLogSink { - return $this->log()->stream(new LogOptions(raw: true)); + $run = $this->get(timeoutSecs: $timeoutSecs); + $actorId = $run?->getActId() ?? ''; + $actor = $actorId === '' ? null : $this->root->actor($actorId)->get($timeoutSecs); + return StderrLogSink::forRun($actor?->getName(), $run?->getId() ?? ''); } /** diff --git a/src/Resource/StoreCollectionClient.php b/src/Resource/StoreCollectionClient.php index 64f9c15..b775ee6 100644 --- a/src/Resource/StoreCollectionClient.php +++ b/src/Resource/StoreCollectionClient.php @@ -10,10 +10,12 @@ use Apify\Client\Internal\TimeoutTiers; use Apify\Client\Model\ActorStoreListItem; use Apify\Client\Model\PaginationList; +use Apify\Client\Model\StoreSearchResult; use Apify\Client\Options\StoreListOptions; +use Apify\Client\Options\StoreSearchOptions; use Generator; -/** A client for browsing the Apify Store ({@code GET /v2/store}). */ +/** A client for browsing and searching Apify Store ({@code GET /v2/store}). */ final class StoreCollectionClient { private ResourceContext $ctx; @@ -25,7 +27,7 @@ public function __construct(HttpClientCore $http, string $baseUrl) } /** - * Returns a single page of Store Actors matching the options. + * Returns a single page of Store Actors, in Store order. To find Actors by a text query, use {@see search()}. * * @return PaginationList */ @@ -37,7 +39,7 @@ public function list(?StoreListOptions $options = null, int|float|string|null $t } /** - * Lazily yields Store Actors matching the options. The {@code limit} option caps the total ({@code null} for all) and + * Lazily yields Store Actors in Store order. The {@code limit} option caps the total ({@code null} for all) and * {@code $chunkSize} sets the page size ({@code null} for the API's default). * * @return Generator @@ -52,4 +54,21 @@ public function iterate(?StoreListOptions $options = null, ?int $chunkSize = nul fn (int $offset, ?int $pageLimit) => $this->list($options->withPagination($offset, $pageLimit), $timeoutSecs), ); } + + /** + * Returns the Actors that match a query best, ordered by relevance. + * + * The API answers a search with one page of at most 100 Actors. There is no next page, and it does not report + * how many Actors match in total. A result holding as many Actors as {@see StoreSearchResult::getLimit()} can + * therefore be cut off, so narrow the search with a more specific query or with the filters. A search cannot + * be iterated. To go through the whole Store, use {@see iterate()}. + */ + public function search(StoreSearchOptions $options, int|float|string|null $timeoutSecs = null): StoreSearchResult + { + $params = new QueryParams(); + $options->appendTo($params); + return StoreSearchResult::fromData( + $this->ctx->getResourceRequired('', $params, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_MEDIUM)), + ); + } } diff --git a/src/Resource/TaskClient.php b/src/Resource/TaskClient.php index 337b166..319957d 100644 --- a/src/Resource/TaskClient.php +++ b/src/Resource/TaskClient.php @@ -7,6 +7,7 @@ use Apify\Client\ApifyClient; use Apify\Client\Internal\HttpClientCore; use Apify\Client\Internal\Json; +use Apify\Client\Internal\LogRedirection; use Apify\Client\Internal\QueryParams; use Apify\Client\Internal\ResourceContext; use Apify\Client\Internal\TimeoutTiers; @@ -65,9 +66,9 @@ public function delete(int|float|string|null $timeoutSecs = null): void * {@code publicConfig.datasetView}. An Actor can have 10 published tasks and an account 100. If a condition * fails, nothing changes. Publishing a published task does nothing. */ - public function publish(): Task + public function publish(int|float|string|null $timeoutSecs = null): Task { - return $this->update(['isPublic' => true]); + return $this->update(['isPublic' => true], $timeoutSecs); } /** @@ -75,9 +76,9 @@ public function publish(): Task * {@code publicConfig} is kept, so the task can be published again. Unpublishing an unpublished task does * nothing. */ - public function unpublish(): Task + public function unpublish(int|float|string|null $timeoutSecs = null): Task { - return $this->update(['isPublic' => false]); + return $this->update(['isPublic' => false], $timeoutSecs); } /** @@ -114,13 +115,24 @@ public function start( * {@code $options->waitForResources} start do not count. * @param int|float|string|null $timeoutSecs timeout of the start request and of each poll (default * {@code 'noTimeout'}) + * @param (callable(string): void)|false|null $log where the log of the run goes while the call waits. By default, + * each message goes to the standard error stream, behind + * {@code "{Actor name} runId:{run ID} -> "}. A callable receives each message, and + * {@code false} turns the redirection off. A failure to redirect the log does not fail + * the call: it prints a warning and waits without the redirection. See + * {@see RunClient::redirectLog()}. */ - public function call(mixed $input = null, ?TaskStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun - { + public function call( + mixed $input = null, + ?TaskStartOptions $options = null, + ?int $waitSecs = null, + int|float|string|null $timeoutSecs = null, + callable|false|null $log = null, + ): ActorRun { // The start request and every poll have no request timeout by default. $timeoutSecs ??= TimeoutTiers::NO_TIMEOUT; $run = $this->start($input, $options, $timeoutSecs); - return $this->root->run((string) $run->getId())->waitForFinish($waitSecs, $timeoutSecs); + return LogRedirection::waitForFinish($this->root->run((string) $run->getId()), $waitSecs, $timeoutSecs, $log); } /** diff --git a/src/Version.php b/src/Version.php index 24c1aab..1cd076b 100644 --- a/src/Version.php +++ b/src/Version.php @@ -17,13 +17,13 @@ final class Version * The semantic version of this client library (see https://semver.org/). * Changes to the public interface other than additive ones are considered breaking changes. */ - public const CLIENT_VERSION = '0.14.1'; + public const 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 const API_SPEC_VERSION = 'v2-2026-11-18T151559Z'; + public const API_SPEC_VERSION = 'v2-2026-12-03T122505Z'; private function __construct() { diff --git a/tests/Examples/DocSnippetsTest.php b/tests/Examples/DocSnippetsTest.php index ef80c53..ccff379 100644 --- a/tests/Examples/DocSnippetsTest.php +++ b/tests/Examples/DocSnippetsTest.php @@ -54,7 +54,8 @@ public function testSnippetIsValidPhp(string $code, int $index, string $file): v . $code . "\n"; } - $tmp = tempnam(sys_get_temp_dir(), 'apify_snippet_') . '.php'; + $tmp = tempnam(sys_get_temp_dir(), 'apify_snippet_'); + self::assertNotFalse($tmp); file_put_contents($tmp, $harness); try { $output = []; @@ -62,7 +63,7 @@ public function testSnippetIsValidPhp(string $code, int $index, string $file): v exec(escapeshellarg(PHP_BINARY) . ' -l ' . escapeshellarg($tmp) . ' 2>&1', $output, $exit); self::assertSame(0, $exit, sprintf("snippet %s#%d is not valid PHP:\n%s", $file, $index, implode("\n", $output))); } finally { - @unlink($tmp); + unlink($tmp); } } @@ -86,6 +87,7 @@ private function imports(): string 'Apify\Client\Options\ListOptions', 'Apify\Client\Options\StorageListOptions', 'Apify\Client\Options\StoreListOptions', + 'Apify\Client\Options\StoreSearchOptions', 'Apify\Client\Options\RunListOptions', 'Apify\Client\Options\DatasetListItemsOptions', 'Apify\Client\Options\DatasetDownloadOptions', diff --git a/tests/Examples/ExampleDocsTest.php b/tests/Examples/ExampleDocsTest.php new file mode 100644 index 0000000..395b014 --- /dev/null +++ b/tests/Examples/ExampleDocsTest.php @@ -0,0 +1,56 @@ + */ + public static function exampleProvider(): array + { + return ExamplesTest::exampleProvider(); + } + + /** @param class-string $exampleClass */ + #[DataProvider('exampleProvider')] + public function testDocsContainTheTestedCode(string $exampleClass): void + { + $docs = (string) file_get_contents(dirname(__DIR__, 2) . '/docs/examples.md'); + + self::assertContains( + self::runBody($exampleClass), + self::phpBlocks($docs), + $exampleClass . ' differs from its snippet in docs/examples.md', + ); + } + + /** The body of {@code run()} of an example class, without the indentation of the method. */ + private static function runBody(string $exampleClass): string + { + $file = dirname(__DIR__) . '/Examples/' . substr($exampleClass, (int) strrpos($exampleClass, '\\') + 1) . '.php'; + $source = (string) file_get_contents($file); + if (preg_match('/public static function run\(ApifyClient \$client\): void\n \{\n(.*)\n \}\n\}\n$/s', $source, $matches) !== 1) { + self::fail($file . ' does not end with the run() method'); + } + $lines = array_map( + static fn (string $line): string => trim($line) === '' ? '' : substr($line, 8), + explode("\n", $matches[1]), + ); + return implode("\n", $lines); + } + + /** @return list the code of every php block, without the final newline */ + private static function phpBlocks(string $markdown): array + { + preg_match_all('/```php\n(.*?)\n```/s', $markdown, $matches); + return $matches[1]; + } +} diff --git a/tests/Examples/ExamplesTest.php b/tests/Examples/ExamplesTest.php index d11b761..8520a43 100644 --- a/tests/Examples/ExamplesTest.php +++ b/tests/Examples/ExamplesTest.php @@ -5,6 +5,7 @@ namespace Apify\Client\Tests\Examples; use Apify\Client\ApifyClient; +use Apify\Client\Tests\Integration\IntegrationTestCase; use PHPUnit\Framework\TestCase; use Throwable; @@ -21,11 +22,7 @@ private function client(): ApifyClient self::markTestSkipped('skipping: APIFY_TOKEN is not set'); } $apiUrl = getenv('APIFY_API_URL'); - $baseUrl = ($apiUrl === false || $apiUrl === '') ? 'https://api.apify.com' : rtrim($apiUrl, '/'); - if (str_ends_with($baseUrl, '/v2')) { - $baseUrl = substr($baseUrl, 0, -3); - } - return new ApifyClient(token: $token, baseUrl: $baseUrl); + return new ApifyClient(token: $token, baseUrl: IntegrationTestCase::resolveBaseUrl($apiUrl === false ? null : $apiUrl)); } /** @@ -63,4 +60,32 @@ public function testExampleRuns(string $exampleClass): void ob_end_clean(); self::assertTrue(true); } + + /** Runs the standalone program of {@code docs/examples.md} as a separate PHP process, as a reader would. */ + public function testStandaloneProgramRuns(): void + { + $this->client(); + $root = dirname(__DIR__, 2); + $docs = (string) file_get_contents($root . '/docs/examples.md'); + if (preg_match('/```php\n(<\?php.*?)\n```/s', $docs, $matches) !== 1) { + self::fail('no standalone program in docs/examples.md'); + } + + // The program must call the API that the tests target, not always production. + self::assertStringContainsString("getenv('APIFY_API_URL')", $matches[1]); + + $program = tempnam(sys_get_temp_dir(), 'apify_example_'); + self::assertNotFalse($program); + try { + file_put_contents($program, $matches[1] . "\n"); + $output = []; + $exit = 0; + // The program requires 'vendor/autoload.php' relative to the project root, like a reader's project. + exec('cd ' . escapeshellarg($root) . ' && ' . escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($program) . ' 2>&1', $output, $exit); + self::assertSame(0, $exit, implode("\n", $output)); + self::assertStringContainsString('Item count: ', implode("\n", $output)); + } finally { + unlink($program); + } + } } diff --git a/tests/Examples/LogRedirection.php b/tests/Examples/LogRedirection.php index 194d2b6..a26aae9 100644 --- a/tests/Examples/LogRedirection.php +++ b/tests/Examples/LogRedirection.php @@ -6,21 +6,18 @@ use Apify\Client\ApifyClient; -/** Run an Actor with log redirection turned on (stream the run's log). */ +/** Run an Actor with log redirection turned on (hand the run's log to a callable while the call waits). */ final class LogRedirection { public static function run(ApifyClient $client): void { - // Start the run without waiting for it to finish. - $run = $client->actor('apify/hello-world')->start(); + // call() redirects the log of the run while it waits. Without the `log` argument, the messages go to the + // standard error stream, behind "{Actor name} runId:{run ID} -> ". A callable receives each message + // instead, and `false` turns the redirection off. + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: static function (string $message): void { + echo 'Actor log: ' . $message . PHP_EOL; + }); - // Open a live streaming connection to the run's log (the `stream=1` endpoint) and redirect it - // to stdout as the run produces it. The server keeps the connection open and emits log lines - // in real time; the stream ends once the run finishes, so reading it to EOF also waits for - // the run to complete. - $stream = $client->run((string) $run->getId())->getStreamedLog(); - while (!$stream->eof()) { - echo $stream->read(8192); - } + echo 'Run status: ' . $run->getStatus() . PHP_EOL; } } diff --git a/tests/Integration/ActorRunIntegrationTest.php b/tests/Integration/ActorRunIntegrationTest.php index 98f84bf..9f4ae75 100644 --- a/tests/Integration/ActorRunIntegrationTest.php +++ b/tests/Integration/ActorRunIntegrationTest.php @@ -46,7 +46,7 @@ public function testIterateRuns(): void // Ensure at least one run exists for this account, then iterate with a small total cap and a // page size that forces multi-page paging. Runs are shared account state, so the test asserts // the cap and shape rather than an exact set, keeping it parallel-safe. - $client->actor('apify/hello-world')->call(null, null, 120); + $client->actor('apify/hello-world')->call(null, null, 120, log: false); $count = 0; foreach ($client->runs()->iterate(new ListOptions(limit: 3), new RunListOptions(), 2) as $run) { self::assertNotNull($run->getId()); @@ -57,10 +57,33 @@ public function testIterateRuns(): void self::assertLessThanOrEqual(3, $count, 'the total-item cap (limit) must bound iteration'); } + public function testCallRedirectsTheLogOfTheRun(): void + { + $client = $this->requireClient(); + $messages = []; + + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: static function (string $message) use (&$messages): void { + $messages[] = $message; + }); + + self::assertSame('SUCCEEDED', $run->getStatus()); + self::assertNotSame([], $messages, 'the log of the run is redirected'); + foreach ($messages as $message) { + self::assertMatchesRegularExpression('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /', $message); + } + + // The log of a finished run is redirected in full too. + $again = []; + $client->run((string) $run->getId())->redirectLog(static function (string $message) use (&$again): void { + $again[] = $message; + }); + self::assertNotSame([], $again); + } + public function testRunActorAndReadOutputs(): void { $client = $this->requireClient(); - $run = $client->actor('apify/hello-world')->call(null, null, 120); + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: false); self::assertSame('SUCCEEDED', $run->getStatus()); self::assertNotNull($client->run((string) $run->getId())->get()); @@ -73,10 +96,22 @@ public function testRunActorAndReadOutputs(): void $client->run((string) $run->getId())->keyValueStore()->getRecord('OUTPUT'); } + public function testUpdateRunStatusMessage(): void + { + $client = $this->requireClient(); + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: false); + $runClient = $client->run((string) $run->getId()); + + $updated = $runClient->update(['statusMessage' => 'Updated by the PHP client test', 'isStatusMessageTerminal' => true]); + + self::assertSame('Updated by the PHP client test', $updated->getStatusMessage()); + self::assertSame('Updated by the PHP client test', $runClient->get()?->getStatusMessage()); + } + public function testReadRunStoragesAndLogById(): void { $client = $this->requireClient(); - $run = $client->actor('apify/hello-world')->call(null, null, 120); + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: false); $runClient = $client->run((string) $run->getId()); $dataset = $runClient->dataset()->get(); @@ -100,7 +135,7 @@ public function testReadRunStoragesAndLogById(): void public function testIterateDatasetItemsOfAFinishedRunYieldsEveryItem(): void { $client = $this->requireClient(); - $run = $client->actor('apify/hello-world')->call(null, null, 120); + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: false); self::assertSame('SUCCEEDED', $run->getStatus()); $runClient = $client->run((string) $run->getId()); @@ -139,6 +174,7 @@ public function testIterateDatasetItemsReadsItemsWhileTheRunIsStillRunning(): vo $statusWhenReceived = []; $items = []; foreach ($runClient->iterateDatasetItems(new RunIterateDatasetItemsOptions(pollIntervalSecs: 1)) as $item) { + /** @var array $item */ $items[] = $item['n']; $statusWhenReceived[] = $runClient->get()?->getStatus(); } @@ -223,6 +259,7 @@ public function testMetamorphWithTheRunsOwnTokenTransformsTheRunKeepingItsId(): */ private function createBuiltActor(ApifyClient $client, string $label, string $mainJs): string { + /** @var array{versions: list>}>} $definition */ $definition = self::minimalActor(self::uniqueName($label)); $definition['versions'][0]['sourceFiles'][1]['content'] = $mainJs; $actorId = (string) $client->actors()->create($definition)->getId(); @@ -289,7 +326,7 @@ private static function listedRunIds(RunCollectionClient $runs, ListOptions $opt public function testRunUrlFieldsAreNormalized(): void { $client = $this->requireClient(); - $run = $client->actor('apify/hello-world')->call(null, null, 120); + $run = $client->actor('apify/hello-world')->call(null, null, 120, log: false); foreach (['consoleUrl', 'containerUrl'] as $field) { $url = $run->get($field); @@ -302,7 +339,7 @@ public function testRunUrlFieldsAreNormalized(): void public function testLastRunAccess(): void { $client = $this->requireClient(); - $client->actor('apify/hello-world')->call(null, null, 120); + $client->actor('apify/hello-world')->call(null, null, 120, log: false); $lastRun = $client->actor('apify/hello-world')->lastRun(new LastRunOptions(status: 'SUCCEEDED'))->get(); self::assertNotNull($lastRun); diff --git a/tests/Integration/BuildIntegrationTest.php b/tests/Integration/BuildIntegrationTest.php index 46bed2d..f5bc4a6 100644 --- a/tests/Integration/BuildIntegrationTest.php +++ b/tests/Integration/BuildIntegrationTest.php @@ -48,11 +48,6 @@ public function testBuildActorFlow(): void $build = $client->actor((string) $created->getId())->build('0.0', new ActorBuildOptions()); $finished = $client->build((string) $build->getId())->waitForFinish(300); self::assertTrue($finished->isTerminal(), 'build did not finish: ' . $finished->getStatus()); - // The field is nullable even for a finished build (e.g. `imageSizeBytes` is also null on - // this test environment's build backend), so only exercise the getter's type, not its - // presence — RequestShapeTest covers the populated case against a scripted response. - self::assertTrue($finished->getImageDigest() === null || is_string($finished->getImageDigest())); - self::assertNotNull($client->build((string) $build->getId())->get()); $client->build((string) $build->getId())->log()->get(); $client->build((string) $build->getId())->getOpenApiDefinition(); @@ -60,4 +55,25 @@ public function testBuildActorFlow(): void $client->actor((string) $created->getId())->delete(); } } + + public function testDeleteBuild(): void + { + $client = $this->requireClient(); + $created = $client->actors()->create(self::minimalActor(self::uniqueName('build-delete'))); + try { + $actor = $client->actor((string) $created->getId()); + // The newest build becomes the default one, which the API refuses to delete, so delete the first. + $first = $actor->build('0.0', new ActorBuildOptions()); + $client->build((string) $first->getId())->waitForFinish(300); + $second = $actor->build('0.0', new ActorBuildOptions()); + $client->build((string) $second->getId())->waitForFinish(300); + + $client->build((string) $first->getId())->delete(); + + self::assertNull($client->build((string) $first->getId())->get()); + self::assertNotNull($client->build((string) $second->getId())->get()); + } finally { + $client->actor((string) $created->getId())->delete(); + } + } } diff --git a/tests/Integration/DatasetIntegrationTest.php b/tests/Integration/DatasetIntegrationTest.php index 1c3bdb6..35db547 100644 --- a/tests/Integration/DatasetIntegrationTest.php +++ b/tests/Integration/DatasetIntegrationTest.php @@ -70,6 +70,7 @@ public function testIterateDatasetItems(): void $values = []; // chunkSize=2 across 5 items => three pages (2, 2, 1). foreach ($dataset->iterateItems(new DatasetListItemsOptions(), 2) as $item) { + /** @var array $item */ $values[] = $item['n']; } sort($values); @@ -140,7 +141,9 @@ public function testDatasetCrudFlow(): void $page = $dataset->listItems(new DatasetListItemsOptions()); self::assertSame(3, $page->getCount()); self::assertCount(3, $page->getItems()); - self::assertSame(1, $page->getItems()[0]['n']); + /** @var array $first */ + $first = $page->getItems()[0]; + self::assertSame(1, $first['n']); // isDesc() is sourced from the server's X-Apify-Pagination-Desc response header. self::assertFalse($page->isDesc()); diff --git a/tests/Integration/IntegrationTestCase.php b/tests/Integration/IntegrationTestCase.php index 0218671..f5eae37 100644 --- a/tests/Integration/IntegrationTestCase.php +++ b/tests/Integration/IntegrationTestCase.php @@ -26,7 +26,7 @@ abstract class IntegrationTestCase extends TestCase /** * Derives the client base URL from {@code APIFY_API_URL}. The client adds {@code /v2} itself, so it is stripped. */ - protected static function resolveBaseUrl(?string $apiUrl): string + public static function resolveBaseUrl(?string $apiUrl): string { if ($apiUrl === null || $apiUrl === '') { $apiUrl = self::DEFAULT_API_URL; diff --git a/tests/Integration/KeyValueStoreIntegrationTest.php b/tests/Integration/KeyValueStoreIntegrationTest.php index 444fce9..3ce0a20 100644 --- a/tests/Integration/KeyValueStoreIntegrationTest.php +++ b/tests/Integration/KeyValueStoreIntegrationTest.php @@ -108,6 +108,10 @@ public function testKeyValueStoreCrudFlow(): void $record = $kvs->getRecord('OUTPUT'); self::assertNotNull($record); self::assertStringContainsString('world', $record->getValue()); + $streamed = $kvs->streamRecord('OUTPUT'); + self::assertNotNull($streamed); + self::assertSame($record->getValue(), (string) $streamed->getStream()); + self::assertNull($kvs->streamRecord('MISSING')); $kvs->getRecord('OUTPUT', new GetRecordOptions(attachment: false)); $keys = $kvs->listKeys(new ListKeysOptions()); self::assertNotEmpty($keys->getItems()); diff --git a/tests/Integration/RequestQueueIntegrationTest.php b/tests/Integration/RequestQueueIntegrationTest.php index 293426c..30eff17 100644 --- a/tests/Integration/RequestQueueIntegrationTest.php +++ b/tests/Integration/RequestQueueIntegrationTest.php @@ -72,6 +72,13 @@ public function testRequestQueueCrudFlow(): void self::assertNotNull($got); self::assertSame('https://example.com', $got->getUrl()); + $got->setUserData(['label' => 'updated']); + $updated = $queue->updateRequest($got); + self::assertSame($info->getRequestId(), $updated->getRequestId()); + $reloaded = $queue->getRequest((string) $info->getRequestId()); + self::assertNotNull($reloaded); + self::assertSame(['label' => 'updated'], $reloaded->getUserData()); + self::assertNotEmpty($queue->listHead(10)->getItems()); $queue->update(['name' => self::uniqueName('rq-renamed')]); $queue->deleteRequest((string) $info->getRequestId()); diff --git a/tests/Integration/StoreIntegrationTest.php b/tests/Integration/StoreIntegrationTest.php index 5bfd455..7fb0650 100644 --- a/tests/Integration/StoreIntegrationTest.php +++ b/tests/Integration/StoreIntegrationTest.php @@ -5,6 +5,7 @@ namespace Apify\Client\Tests\Integration; use Apify\Client\Options\StoreListOptions; +use Apify\Client\Options\StoreSearchOptions; final class StoreIntegrationTest extends IntegrationTestCase { @@ -18,9 +19,9 @@ public function testListStore(): void public function testListStoreWithInputSchema(): void { $client = $this->requireClient(); - $withSchema = $client->store()->list(new StoreListOptions(search: 'website content crawler', limit: 10, includeInputSchema: true)); + $withSchema = $client->store()->list(new StoreListOptions(limit: 10, includeInputSchema: true)); self::assertNotEmpty($withSchema->getItems()); - $withoutSchema = $client->store()->list(new StoreListOptions(search: 'website content crawler', limit: 10)); + $withoutSchema = $client->store()->list(new StoreListOptions(limit: 10)); foreach ($withoutSchema->getItems() as $item) { self::assertNull($item->get('inputSchema'), 'the input schema is only returned on request'); } @@ -31,6 +32,70 @@ public function testListStoreWithInputSchema(): void self::assertNotEmpty($schemas, 'at least one Store Actor carries its input schema'); } + public function testListStoreFiltersByUsername(): void + { + $client = $this->requireClient(); + $page = $client->store()->list(new StoreListOptions(limit: 10, username: 'apify')); + self::assertNotEmpty($page->getItems()); + foreach ($page->getItems() as $item) { + self::assertSame('apify', $item->getUsername()); + } + } + + public function testSearchReturnsTheBestMatchesAsOnePage(): void + { + $client = $this->requireClient(); + $result = $client->store()->search(new StoreSearchOptions('web scraper', limit: 5)); + // The public Store holds many scrapers, so the page is full. + self::assertCount(5, $result); + self::assertSame(5, $result->getLimit()); + foreach ($result->getItems() as $item) { + self::assertNotEmpty($item->getId()); + self::assertNotEmpty($item->getName()); + self::assertNotEmpty($item->getUsername()); + } + } + + public function testSearchReturnsAtMostOneHundredActorsWhateverTheLimit(): void + { + $client = $this->requireClient(); + $default = $client->store()->search(new StoreSearchOptions('scraper')); + $large = $client->store()->search(new StoreSearchOptions('scraper', limit: 1000)); + self::assertSame(100, $default->getLimit()); + self::assertCount(100, $default); + self::assertSame(100, $large->getLimit()); + self::assertCount(100, $large); + } + + public function testSearchReturnsNothingForAQueryThatMatchesNoActor(): void + { + $client = $this->requireClient(); + $result = $client->store()->search(new StoreSearchOptions('qzxjvkwpqzxjvkwp')); + self::assertSame([], $result->getItems()); + } + + public function testSearchFiltersByUsername(): void + { + $client = $this->requireClient(); + $result = $client->store()->search(new StoreSearchOptions('scraper', limit: 10, username: 'apify')); + self::assertNotEmpty($result->getItems()); + foreach ($result->getItems() as $item) { + self::assertSame('apify', $item->getUsername()); + } + } + + public function testSearchWithInputSchema(): void + { + $client = $this->requireClient(); + $result = $client->store()->search(new StoreSearchOptions('website content crawler', limit: 10, includeInputSchema: true)); + self::assertNotEmpty($result->getItems()); + $schemas = array_filter( + array_map(static fn ($item) => $item->get('inputSchema'), $result->getItems()), + static fn ($schema) => $schema !== null, + ); + self::assertNotEmpty($schemas, 'at least one Store Actor carries its input schema'); + } + public function testIterateStore(): void { $client = $this->requireClient(); diff --git a/tests/Integration/TaskIntegrationTest.php b/tests/Integration/TaskIntegrationTest.php index b199b3b..bc52a20 100644 --- a/tests/Integration/TaskIntegrationTest.php +++ b/tests/Integration/TaskIntegrationTest.php @@ -103,7 +103,7 @@ public function testTaskLastRun(): void $task = $client->tasks()->create(self::taskDef(self::uniqueName('task-last'))); try { $tc = $client->task((string) $task->getId()); - $run = $tc->call(null, null, 120); + $run = $tc->call(null, null, 120, log: false); self::assertSame('SUCCEEDED', $run->getStatus()); $lastRun = $tc->lastRun()->get(); diff --git a/tests/Integration/UserIntegrationTest.php b/tests/Integration/UserIntegrationTest.php index fd6d5e4..d0d0b12 100644 --- a/tests/Integration/UserIntegrationTest.php +++ b/tests/Integration/UserIntegrationTest.php @@ -15,6 +15,16 @@ public function testGetOwnAccount(): void self::assertNotSame('', $user->getId()); } + public function testGetAccountById(): void + { + $client = $this->requireClient(); + $id = $client->me()->get()?->getId(); + self::assertNotNull($id); + $user = $client->user($id)->get(); + self::assertNotNull($user); + self::assertSame($id, $user->getId()); + } + public function testGetMonthlyUsage(): void { $client = $this->requireClient(); diff --git a/tests/Integration/ZstdCompressionIntegrationTest.php b/tests/Integration/ZstdCompressionIntegrationTest.php index 3cc40f4..d6c36bc 100644 --- a/tests/Integration/ZstdCompressionIntegrationTest.php +++ b/tests/Integration/ZstdCompressionIntegrationTest.php @@ -64,7 +64,9 @@ public function testDatasetItemsAreStoredFromAZstdBody(): void self::waitForDatasetItemCount($items, 2); $stored = $items->listItems()->getItems(); self::assertSame([1, 2], array_column($stored, 'n')); - self::assertSame($padding, $stored[0]['padding']); + /** @var array $firstStored */ + $firstStored = $stored[0]; + self::assertSame($padding, $firstStored['padding']); self::assertContains('zstd', $this->recorder->encodings); } finally { $client->dataset((string) $dataset->getId())->delete(); diff --git a/tests/Unit/ClientHeadersTest.php b/tests/Unit/ClientHeadersTest.php new file mode 100644 index 0000000..9049678 --- /dev/null +++ b/tests/Unit/ClientHeadersTest.php @@ -0,0 +1,88 @@ + $headers */ + private function client(MockTransport $transport, array $headers): ApifyClient + { + return new ApifyClient( + token: 't', + minDelayBetweenRetriesMillis: 1, + timeoutSecs: 5, + httpClient: $transport, + headers: $headers, + ); + } + + public function testHeadersAreSentWithEveryRequest(): void + { + $transport = (new MockTransport())->queueResponse(200, '{"data":{}}')->queueResponse(200, '{"data":{}}'); + $client = $this->client($transport, ['X-Integration' => 'my-platform']); + + $client->actor('a1')->get(); + $client->dataset('d1')->get(); + + self::assertCount(2, $transport->received); + foreach ($transport->received as $request) { + self::assertSame('my-platform', $request->getHeaderLine('X-Integration')); + self::assertSame('Bearer t', $request->getHeaderLine('Authorization')); + } + } + + public function testHeadersReplaceTheBuiltInDefaults(): void + { + $transport = (new MockTransport())->queueResponse(200, '{"data":{}}'); + $this->client($transport, ['User-Agent' => 'my-agent/1.0'])->actor('a1')->get(); + + self::assertSame('my-agent/1.0', $transport->lastRequest()->getHeaderLine('User-Agent')); + } + + public function testHeaderOfASingleCallWinsOverTheClientHeaders(): void + { + $transport = (new MockTransport())->queueResponse(200, ''); + $this->client($transport, ['Content-Type' => 'text/plain']) + ->keyValueStore('s1') + ->setRecord('k', 'abc', 'application/octet-stream'); + + self::assertSame('application/octet-stream', $transport->lastRequest()->getHeaderLine('Content-Type')); + } + + public function testAuthorizationHeaderReplacesTheTokenOnAnApiRequest(): void + { + $transport = (new MockTransport())->queueResponse(200, '{"data":{}}'); + $this->client($transport, ['authorization' => 'Bearer other'])->actor('a1')->get(); + + self::assertSame(['Bearer other'], $transport->lastRequest()->getHeader('Authorization')); + self::assertFalse($transport->lastRequest()->hasHeader('X-Apify-Authorization')); + } + + public function testAuthorizationHeaderDoesNotReachAnActorServer(): void + { + $transport = (new MockTransport()) + ->queueResponse(200, '{"data":{"id":"a1","standbyUrl":"https://jane--my-actor.apify.actor"}}') + ->queueResponse(200, 'ok'); + + $this->client($transport, ['Authorization' => 'Bearer api-secret'])->actor('a1')->server()->request('/'); + + $request = $transport->lastRequest(); + self::assertStringStartsWith('https://jane--my-actor.apify.actor', (string) $request->getUri()); + self::assertFalse($request->hasHeader('Authorization')); + self::assertSame(['Bearer api-secret'], $request->getHeader('X-Apify-Authorization')); + } + + public function testNoHeadersByDefault(): void + { + $transport = (new MockTransport())->queueResponse(200, '{"data":{}}'); + $this->client($transport, [])->actor('a1')->get(); + + self::assertFalse($transport->lastRequest()->hasHeader('X-Integration')); + } +} diff --git a/tests/Unit/DatasetStreamItemsTest.php b/tests/Unit/DatasetStreamItemsTest.php index 440f228..87dc268 100644 --- a/tests/Unit/DatasetStreamItemsTest.php +++ b/tests/Unit/DatasetStreamItemsTest.php @@ -14,9 +14,9 @@ /** Tests of {@see \Apify\Client\Resource\DatasetClient::streamItems()}. */ final class DatasetStreamItemsTest extends TestCase { - private function client(MockTransport $transport): ApifyClient + private function client(MockTransport $transport, int $maxRetries = 8): ApifyClient { - return new ApifyClient(token: 't', minDelayBetweenRetriesMillis: 1, timeoutSecs: 5, httpClient: $transport); + return new ApifyClient(token: 't', maxRetries: $maxRetries, minDelayBetweenRetriesMillis: 1, timeoutSecs: 5, httpClient: $transport); } public function testStreamItemsRequestsSameUrlAsDownloadItems(): void @@ -34,19 +34,30 @@ public function testStreamItemsRequestsSameUrlAsDownloadItems(): void self::assertStringContainsString('bom=1', $uri); } - public function testStreamItemsUsesStreamingTransportNotRetrying(): void + public function testStreamItemsRetriesOpeningTheStreamOnAServerError(): void { - // A server error on a streamed request must surface immediately (streaming bypasses retries), - // unlike the buffered downloadItems()/get() calls, which retry 5xx responses. $transport = (new MockTransport()) - ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])); + ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])) + ->queueResponse(200, '[]'); + + $stream = $this->client($transport)->dataset('ds1')->streamItems(DownloadItemsFormat::JSON); + + self::assertSame('[]', (string) $stream); + self::assertSame(2, $transport->callCount()); + self::assertSame([true, true], $transport->streamed); + } + + public function testStreamItemsThrowsTheErrorOnceTheRetriesRunOut(): void + { + $body = Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']]); + $transport = (new MockTransport())->queueResponse(500, $body)->queueResponse(500, $body)->queueResponse(500, $body); try { - $this->client($transport)->dataset('ds1')->streamItems(DownloadItemsFormat::JSON); + $this->client($transport, 2)->dataset('ds1')->streamItems(DownloadItemsFormat::JSON); self::fail('expected ApifyApiException'); } catch (ApifyApiException $e) { self::assertSame(500, $e->getStatusCode()); - self::assertSame(1, $transport->callCount()); + self::assertSame(3, $transport->callCount()); } } } diff --git a/tests/Unit/HttpClientTest.php b/tests/Unit/HttpClientTest.php index 7a9968c..2e999b6 100644 --- a/tests/Unit/HttpClientTest.php +++ b/tests/Unit/HttpClientTest.php @@ -256,7 +256,9 @@ public function testDatasetItemsUseHeaderPagination(): void self::assertSame(42, $page->getTotal()); self::assertSame(3, $page->getCount()); - self::assertSame(1, $page->getItems()[0]['n']); + /** @var array $first */ + $first = $page->getItems()[0]; + self::assertSame(1, $first['n']); self::assertFalse($page->isDesc()); } diff --git a/tests/Unit/IterationTest.php b/tests/Unit/IterationTest.php index c532da9..e381527 100644 --- a/tests/Unit/IterationTest.php +++ b/tests/Unit/IterationTest.php @@ -208,6 +208,7 @@ public function testDatasetIterateItemsPagesViaHeaders(): void ]); $values = []; foreach ($this->client($transport)->dataset('ds')->iterateItems(null, 2) as $item) { + /** @var array $item */ $values[] = $item['n']; } self::assertSame([1, 2, 3], $values); @@ -244,6 +245,7 @@ public function testDatasetIterateItemsAdvancesByScannedCountNotItemCount(): voi ]); $values = []; foreach ($this->client($transport)->dataset('ds')->iterateItems(new DatasetListItemsOptions(skipEmpty: true), 3) as $item) { + /** @var array $item */ $values[] = $item['n']; } self::assertSame([0, 1, 3, 4, 5], $values); @@ -279,6 +281,7 @@ public function testDatasetIterateItemsCapsScannedCountWhenUnwindInflatesItemsPa ]); $values = []; foreach ($this->client($transport)->dataset('ds')->iterateItems(new DatasetListItemsOptions(unwind: ['parts']), 2) as $item) { + /** @var array $item */ $values[] = $item['n']; } self::assertSame(range(0, 11), $values); diff --git a/tests/Unit/KeyValueStoreStreamRecordTest.php b/tests/Unit/KeyValueStoreStreamRecordTest.php new file mode 100644 index 0000000..d4feea7 --- /dev/null +++ b/tests/Unit/KeyValueStoreStreamRecordTest.php @@ -0,0 +1,92 @@ +queueResponse(200, 'raw bytes', ['Content-Type' => 'application/octet-stream']); + $record = $this->client($transport)->keyValueStore('s1')->streamRecord('my key', new GetRecordOptions(signature: 'sig')); + + self::assertNotNull($record); + self::assertSame('my key', $record->getKey()); + self::assertSame('application/octet-stream', $record->getContentType()); + self::assertSame('raw bytes', (string) $record->getStream()); + + $uri = (string) $transport->lastRequest()->getUri(); + self::assertStringContainsString('/key-value-stores/s1/records/my%20key', $uri); + self::assertStringContainsString('attachment=1', $uri); + self::assertStringContainsString('signature=sig', $uri); + self::assertSame([true], $transport->streamed); + } + + public function testStreamRecordWithoutContentTypeHasNullContentType(): void + { + $transport = (new MockTransport())->queueResponse(200, 'x'); + $record = $this->client($transport)->keyValueStore('s1')->streamRecord('k'); + + self::assertNotNull($record); + self::assertNull($record->getContentType()); + } + + public function testStreamRecordOfMissingRecordReturnsNull(): void + { + $body = Json::encode(['error' => ['type' => 'record-not-found', 'message' => 'not here']]); + $transport = (new MockTransport())->queueResponse(404, $body); + + self::assertNull($this->client($transport)->keyValueStore('s1')->streamRecord('missing')); + } + + public function testStreamRecordRetriesOpeningTheStreamOnAServerError(): void + { + $transport = (new MockTransport()) + ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])) + ->queueError() + ->queueResponse(200, 'raw bytes'); + + $record = $this->client($transport)->keyValueStore('s1')->streamRecord('k'); + + self::assertNotNull($record); + self::assertSame('raw bytes', (string) $record->getStream()); + self::assertSame(3, $transport->callCount()); + self::assertSame([true, true, true], $transport->streamed); + } + + public function testStreamRecordThrowsTheErrorOnceTheRetriesRunOut(): void + { + $body = Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']]); + $transport = (new MockTransport())->queueResponse(500, $body)->queueResponse(500, $body)->queueResponse(500, $body); + + try { + $this->client($transport, 2)->keyValueStore('s1')->streamRecord('k'); + self::fail('expected ApifyApiException'); + } catch (ApifyApiException $e) { + self::assertSame(500, $e->getStatusCode()); + self::assertSame('boom', $e->getApiMessage()); + self::assertSame(3, $transport->callCount()); + } + } + + public function testStreamRecordTakesTheTimeoutOfTheCall(): void + { + $transport = (new MockTransport())->queueResponse(200, 'x'); + $this->client($transport)->keyValueStore('s1')->streamRecord('k', null, 3); + + self::assertSame([3.0], $transport->timeouts); + } +} diff --git a/tests/Unit/LogClientTest.php b/tests/Unit/LogClientTest.php index ed1df47..666b0a2 100644 --- a/tests/Unit/LogClientTest.php +++ b/tests/Unit/LogClientTest.php @@ -5,6 +5,7 @@ namespace Apify\Client\Tests\Unit; use Apify\Client\ApifyClient; +use Apify\Client\Exception\NotFoundException; use Apify\Client\Options\LogOptions; use PHPUnit\Framework\TestCase; @@ -66,4 +67,29 @@ public function testStreamedLogUsesStreamQueryAndReturnsReadableStream(): void self::assertStringContainsString('raw=1', $uri); self::assertSame('streamed log body', (string) $stream); } + + public function testStreamOfAMissingLogReturnsNullForAClientWithAnId(): void + { + $body = json_encode(['error' => ['type' => 'record-not-found', 'message' => 'no log']]); + $transport = (new MockTransport())->queueResponse(404, (string) $body); + + self::assertNull($this->client($transport)->log('missing')->stream()); + } + + public function testStreamOfAMissingRunLogRethrowsTheNotFoundError(): void + { + $body = json_encode(['error' => ['type' => 'record-not-found', 'message' => 'no run']]); + $transport = (new MockTransport())->queueResponse(404, (string) $body); + + $this->expectException(NotFoundException::class); + $this->client($transport)->run('missing')->log()->stream(); + } + + public function testGetStreamedLogTakesTheTimeoutOfTheCall(): void + { + $transport = (new MockTransport())->queueResponse(200, 'log'); + $this->client($transport)->run('run1')->getStreamedLog(3); + + self::assertSame([3.0], $transport->timeouts); + } } diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php new file mode 100644 index 0000000..f3105bc --- /dev/null +++ b/tests/Unit/LogRedirectionTest.php @@ -0,0 +1,598 @@ + ['id' => 'r1', 'actId' => 'a1', 'status' => $status]]); + } + + private function client(MockTransport $transport): ApifyClient + { + return new ApifyClient(token: 't', maxRetries: 0, minDelayBetweenRetriesMillis: 1, httpClient: $transport); + } + + /** @return list the path of each received request, without the API version */ + private static function paths(MockTransport $transport): array + { + return array_map( + static fn (RequestInterface $request): string => str_replace('/v2', '', $request->getUri()->getPath()) . ($request->getUri()->getQuery() === '' ? '' : '?' . $request->getUri()->getQuery()), + $transport->received + ); + } + + public function testCallRedirectsTheLogOfTheRunToTheGivenTarget(): void + { + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueResponse(200, self::LOG) + ->queueResponse(200, self::runBody('SUCCEEDED')) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $run = $this->client($transport)->actor('a1')->call(null, null, 60, log: $sink); + + self::assertSame('SUCCEEDED', $run->getStatus()); + self::assertSame([ + '2024-05-01T10:00:00.000Z ACTOR: starting', + "2024-05-01T10:00:01.000Z hello\n continued", + '2024-05-01T10:00:02.000Z bye', + ], $sink->messages); + $paths = self::paths($transport); + self::assertSame('/actors/a1/runs', explode('?', $paths[0])[0]); + self::assertSame('/actor-runs/r1/log?stream=1&raw=1', $paths[1]); + // The run is asked for once the stream ends, to tell a finished log from a cut one. + self::assertSame('/actor-runs/r1', $paths[2]); + self::assertStringStartsWith('/actor-runs/r1?waitForFinish=', $paths[3]); + self::assertCount(4, $paths); + } + + public function testTaskCallRedirectsTheLogToo(): void + { + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueResponse(200, "2024-05-01T10:00:00.000Z one\n") + ->queueResponse(200, self::runBody('SUCCEEDED')) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->task('t1')->call(null, null, null, null, $sink); + + self::assertSame(['2024-05-01T10:00:00.000Z one'], $sink->messages); + } + + public function testCallWithoutRedirectionOnlyStartsAndPolls(): void + { + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueResponse(200, self::runBody('SUCCEEDED')); + + $this->client($transport)->actor('a1')->call(log: false); + + self::assertCount(2, $transport->received); + } + + public function testTheDefaultTargetNeedsTheRunAndTheActorForThePrefix(): void + { + // The run finished without logging anything, so nothing is written to the standard error stream. + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueResponse(200, self::runBody('SUCCEEDED')) + ->queueResponse(200, Json::encode(['data' => ['id' => 'a1', 'name' => 'my-actor']])) + ->queueResponse(200, '') + ->queueResponse(200, self::runBody('SUCCEEDED')) + ->queueResponse(200, '') + ->queueResponse(200, self::runBody('SUCCEEDED')); + + $run = $this->client($transport)->actor('a1')->call(); + + self::assertSame('SUCCEEDED', $run->getStatus()); + $paths = self::paths($transport); + self::assertSame('/actor-runs/r1', $paths[1]); + self::assertSame('/actors/a1', $paths[2]); + self::assertSame('/actor-runs/r1/log?stream=1&raw=1', $paths[3]); + self::assertSame('/actor-runs/r1', $paths[4]); + self::assertSame('/actor-runs/r1/log?raw=1', $paths[5]); + } + + public function testAFailureToSetUpTheRedirectionStillReturnsTheRun(): void + { + $error = Json::encode(['error' => ['type' => 'invalid-request', 'message' => 'no log for you']]); + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueResponse(400, $error) + ->queueResponse(200, self::runBody('SUCCEEDED')); + + // The run is fetched for the default prefix and the request fails. This prints one warning to STDERR. + $run = $this->client($transport)->actor('a1')->call(); + + self::assertSame('SUCCEEDED', $run->getStatus()); + self::assertCount(3, $transport->received); + } + + public function testAStreamThatEndedEmptyIsReopenedWhileTheRunGoesOn(): void + { + $transport = (new MockTransport()) + ->queueResponse(200, '') + ->queueResponse(200, self::runBody('RUNNING')) + ->queueResponse(200, "2024-05-01T10:00:00.000Z first\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['2024-05-01T10:00:00.000Z first'], $sink->messages); + self::assertSame([true, false, true, false], $transport->streamed); + } + + public function testACutStreamIsReopenedAndResumesAfterTheLastRedirectedMessage(): void + { + $log = "2024-05-01T10:00:00.000Z a\n2024-05-01T10:00:00.000Z b\n2024-05-01T10:00:01.000Z c\n"; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream([$log], new RuntimeException('connection reset')))) + ->queueResponse(200, $log . "2024-05-01T10:00:02.000Z d\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame([ + '2024-05-01T10:00:00.000Z a', + '2024-05-01T10:00:00.000Z b', + '2024-05-01T10:00:01.000Z c', + '2024-05-01T10:00:02.000Z d', + ], $sink->messages); + self::assertCount(3, $transport->received); + } + + public function testAStreamThatBreaksOffAgainBeforeCatchingUpStopsTheRedirection(): void + { + $log = "2024-05-01T10:00:00.000Z a\n"; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream([$log], new RuntimeException('first cut')))) + ->queueRawResponse(new Response(200, [], new ScriptedStream([], new RuntimeException('second cut')))); + $sink = new MessageCollector(); + + $this->expectException(ApifyClientException::class); + $this->expectExceptionMessage('was cut again'); + $this->client($transport)->run('r1')->redirectLog($sink); + } + + public function testAStreamThatEndsCleanlyWhileTheRunGoesOnIsReopened(): void + { + $transport = (new MockTransport()) + ->queueResponse(200, "2024-05-01T10:00:00.000Z a\n2024-05-01T10:00:01.000Z b\n") + ->queueResponse(200, self::runBody('RUNNING')) + ->queueResponse(200, "2024-05-01T10:00:00.000Z a\n2024-05-01T10:00:01.000Z b\n2024-05-01T10:00:02.000Z c\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['2024-05-01T10:00:00.000Z a', '2024-05-01T10:00:01.000Z b', '2024-05-01T10:00:02.000Z c'], $sink->messages); + self::assertSame([true, false, true, false], $transport->streamed); + } + + public function testWaitSecsBoundsAQuietStream(): void + { + $transport = (new MockTransport())->queueRawResponse(new Response(200, [], new ScriptedStream([], null, 100_000, true))); + $sink = new MessageCollector(); + + $start = microtime(true); + $this->client($transport)->run('r1')->redirectLog($sink, null, 1); + + self::assertLessThan(2.5, microtime(true) - $start); + self::assertSame([], $sink->messages); + self::assertCount(1, $transport->received); + // The stream is opened with the time left as its timeout. + self::assertGreaterThan(0.0, $transport->timeouts[0]); + self::assertLessThanOrEqual(1.0, $transport->timeouts[0]); + } + + public function testAReadThatFailsAfterTheDeadlineIsNotACut(): void + { + $transport = (new MockTransport())->queueRawResponse(new Response(200, [], new ScriptedStream([], new RuntimeException('read timed out'), 1_200_000))); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink, null, 1); + + self::assertCount(1, $transport->received); + } + + public function testCallWaitsOnlyTheTimeThatIsLeftAfterTheRedirection(): void + { + $transport = (new MockTransport()) + ->queueResponse(201, self::runBody('READY')) + ->queueRawResponse(new Response(200, [], new ScriptedStream([], null, 100_000, true))) + ->queueResponse(200, self::runBody('RUNNING')); + + $run = $this->client($transport)->actor('a1')->call(null, null, 1, log: new MessageCollector()); + + self::assertSame('RUNNING', $run->getStatus()); + self::assertSame('0', explode('waitForFinish=', self::paths($transport)[2])[1]); + } + + public function testTheDefaultTargetWritesPrefixedLinesToStderr(): void + { + $root = dirname(__DIR__, 2); + $script = tempnam(sys_get_temp_dir(), 'apify_log_'); + self::assertNotFalse($script); + $run = static fn (string $status): string => var_export(self::runBody($status), true); + $program = 'queueResponse(201, ' . $run('READY') . ') + ->queueResponse(200, ' . $run('RUNNING') . ') + ->queueResponse(200, \'{"data":{"id":"a1","name":"my-actor"}}\') + ->queueResponse(200, "2024-05-01T10:00:00.000Z hello\n") + ->queueResponse(200, ' . $run('SUCCEEDED') . ') + ->queueResponse(200, ' . $run('SUCCEEDED') . '); +$client = new Apify\Client\ApifyClient(token: \'t\', maxRetries: 0, httpClient: $transport); +$client->actor(\'a1\')->call(); +'; + try { + file_put_contents($script, $program); + $process = proc_open([PHP_BINARY, $script], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + self::assertIsResource($process); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $exit = proc_close($process); + + self::assertSame(0, $exit, (string) $stderr); + self::assertStringContainsString("my-actor runId:r1 -> 2024-05-01T10:00:00.000Z hello\n", (string) $stderr); + self::assertStringNotContainsString('hello', (string) $stdout); + } finally { + unlink($script); + } + } + + public function testSinceAlsoSkipsTheContinuationOfASkippedMessage(): void + { + $chunks = ["2024-05-01T10:00:00.000Z old error\n", " at oldFrame()\n2024-05-01T10:00:02.000Z new\n"]; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream($chunks))) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink, new DateTimeImmutable('2024-05-01T10:00:01Z')); + + self::assertSame(['2024-05-01T10:00:02.000Z new'], $sink->messages); + } + + public function testAnUntimestampedFirstLineIsNotRedirectedAgainByAReopenedStream(): void + { + $log = "Starting container\n2024-05-01T10:00:00.000Z a\n"; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream([$log], new RuntimeException('connection reset')))) + ->queueResponse(200, $log . "2024-05-01T10:00:01.000Z b\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['Starting container', '2024-05-01T10:00:00.000Z a', '2024-05-01T10:00:01.000Z b'], $sink->messages); + } + + public function testAFirstLineThatIsCutBeforeItsEndIsRedirectedByTheReopenedStream(): void + { + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream(['Starting contai'], new RuntimeException('connection reset')))) + ->queueResponse(200, "Starting container\n2024-05-01T10:00:00.000Z a\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['Starting container', '2024-05-01T10:00:00.000Z a'], $sink->messages); + } + + public function testAReadThatFailsAfterTheDeadlineWhileTheLogIsReplayedIsNotACutAgain(): void + { + // The reopened stream replays only the first message when its read fails after the deadline. It has not + // caught up with the stream before it, which would be an error if the stream were cut within the time. + $first = new ScriptedStream(["2024-05-01T10:00:00.000Z a\n2024-05-01T10:00:01.000Z b\n"], new RuntimeException('connection reset')); + $second = new ScriptedStream(["2024-05-01T10:00:00.000Z a\n"], new RuntimeException('read timed out'), 600_000); + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], $first)) + ->queueRawResponse(new Response(200, [], $second)); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink, null, 2); + + self::assertSame(['2024-05-01T10:00:00.000Z a', '2024-05-01T10:00:01.000Z b'], $sink->messages); + self::assertCount(2, $transport->received); + } + + public function testACutInsideALaterLineOfTheOpeningTextLosesNothing(): void + { + $log = "Starting container\nPulling image\n2024-05-01T10:00:00.000Z a\n"; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream(["Starting container\n", 'Pulling im'], new RuntimeException('connection reset')))) + ->queueResponse(200, $log) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['Starting container', 'Pulling image', '2024-05-01T10:00:00.000Z a'], $sink->messages); + } + + public function testACutInsideAContinuationLineLosesNothing(): void + { + $log = "2024-05-01T10:00:00.000Z error\n at f1\n at f2\n2024-05-01T10:00:01.000Z b\n"; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream(["2024-05-01T10:00:00.000Z error\n at f1\n at", ' f2'], new RuntimeException('connection reset')))) + ->queueResponse(200, $log) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + // The lines of the message that arrive after its first chunk are redirected as a message of their own. + self::assertSame(["2024-05-01T10:00:00.000Z error\n at f1", 'at f2', '2024-05-01T10:00:01.000Z b'], $sink->messages); + } + + public function testAReopenedStreamThatEndsCleanlyBeforeCatchingUpStopsTheRedirection(): void + { + $transport = (new MockTransport()) + ->queueResponse(200, "2024-05-01T10:00:00.000Z a\n") + ->queueResponse(200, self::runBody('RUNNING')) + ->queueResponse(200, '') + ->queueResponse(200, self::runBody('RUNNING')); + $sink = new MessageCollector(); + + try { + $this->client($transport)->run('r1')->redirectLog($sink); + self::fail('expected ApifyClientException'); + } catch (ApifyClientException $e) { + self::assertStringContainsString('was cut again', $e->getMessage()); + self::assertNull($e->getPrevious()); + } + self::assertSame(['2024-05-01T10:00:00.000Z a'], $sink->messages); + } + + public function testAReadThatFailsAfterTheDeadlineKeepsWhatWasRedirected(): void + { + $stream = new ScriptedStream(["2024-05-01T10:00:00.000Z a\n"], new RuntimeException('read timed out'), 600_000); + $transport = (new MockTransport())->queueRawResponse(new Response(200, [], $stream)); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink, null, 1); + + self::assertSame(['2024-05-01T10:00:00.000Z a'], $sink->messages); + self::assertCount(1, $transport->received); + } + + public function testNoStreamIsOpenedWithTooLittleTimeLeft(): void + { + // The run has not logged anything yet, so the empty stream is reopened until the deadline, which falls a + // millisecond after a pause ends. A stream request with a timeout below the minimum fails, as it does + // against the real API. + $mock = (new MockTransport())->queueResponse(200, '')->queueResponse(200, '')->queueResponse(200, ''); + $client = new ApifyClient(token: 't', maxRetries: 0, minDelayBetweenRetriesMillis: 1, httpClient: new MinStreamTimeoutTransport($mock)); + $streamedLog = new StreamedLog($client->run('r1')->log(), new MessageCollector()); + + $start = microtime(true); + $streamedLog->redirect(static fn (): bool => false, $start + 1.5009); + + self::assertLessThan(2.5, microtime(true) - $start); + self::assertSame(2, $mock->callCount()); + } + + public function testSinceSkipsOlderMessages(): void + { + $transport = (new MockTransport())->queueResponse(200, self::LOG)->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink, new DateTimeImmutable('2024-05-01T10:00:01Z')); + + self::assertSame(["2024-05-01T10:00:01.000Z hello\n continued", '2024-05-01T10:00:02.000Z bye'], $sink->messages); + } + + public function testALineWithoutATimestampInALaterChunkIsRedirectedAsItIs(): void + { + $chunks = ["2024-05-01T10:00:00.000Z first\n", " more of first\n2024-05-01T10:00:01.000Z second\n"]; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream($chunks))) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['2024-05-01T10:00:00.000Z first', 'more of first', '2024-05-01T10:00:01.000Z second'], $sink->messages); + } + + public function testAMessageThatEndsInTheMiddleOfAChunkIsJoinedWithItsRest(): void + { + $chunks = ['2024-05-01T10:00:00.000Z fir', "st\n2024-05-01T10:00:01.000Z second"]; + $transport = (new MockTransport()) + ->queueRawResponse(new Response(200, [], new ScriptedStream($chunks))) + ->queueResponse(200, self::runBody('SUCCEEDED')); + $sink = new MessageCollector(); + + $this->client($transport)->run('r1')->redirectLog($sink); + + self::assertSame(['2024-05-01T10:00:00.000Z first', '2024-05-01T10:00:01.000Z second'], $sink->messages); + } + + public function testStderrSinkPrefixesEveryMessage(): void + { + $stream = fopen('php://memory', 'w+b'); + self::assertIsResource($stream); + + $sink = new StderrLogSink('my-actor runId:r1 -> ', $stream); + $sink('one'); + $sink('two'); + + rewind($stream); + self::assertSame("my-actor runId:r1 -> one\nmy-actor runId:r1 -> two\n", stream_get_contents($stream)); + } + + public function testTheSinkOfARunNamesTheActorAndTheRun(): void + { + self::assertSame('my-actor runId:r1 -> ', StderrLogSink::forRun('my-actor', 'r1')->getPrefix()); + self::assertSame('runId:r1 -> ', StderrLogSink::forRun(null, 'r1')->getPrefix()); + self::assertSame(' -> ', StderrLogSink::forRun(null, '')->getPrefix()); + } +} + +/** Collects the messages that a log redirection hands over. */ +final class MessageCollector +{ + /** @var list */ + public array $messages = []; + + public function __invoke(string $message): void + { + $this->messages[] = $message; + } +} + +/** A readable stream that delivers its chunks one by one, then ends, fails with the given error, or goes quiet. */ +final class ScriptedStream implements StreamInterface +{ + /** + * @param list $chunks delivered one per read + * @param Throwable|null $thenFail thrown by the read after the chunks, instead of ending the stream + * @param int $waitMicros how long each read waits first + * @param bool $endless whether the stream never ends, so a read after the chunks returns nothing + */ + public function __construct( + private array $chunks, + private ?Throwable $thenFail = null, + private int $waitMicros = 0, + private bool $endless = false, + ) { + } + + public function __toString(): string + { + return ''; + } + + public function close(): void + { + $this->chunks = []; + $this->thenFail = null; + } + + public function detach() + { + return null; + } + + public function getSize(): ?int + { + return null; + } + + public function tell(): int + { + return 0; + } + + public function eof(): bool + { + return !$this->endless && $this->chunks === [] && $this->thenFail === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + throw new RuntimeException('not seekable'); + } + + public function rewind(): void + { + throw new RuntimeException('not seekable'); + } + + public function isWritable(): bool + { + return false; + } + + public function write(string $string): int + { + throw new RuntimeException('not writable'); + } + + public function isReadable(): bool + { + return true; + } + + public function read(int $length): string + { + if ($this->waitMicros > 0) { + usleep($this->waitMicros); + } + if ($this->chunks !== []) { + return (string) array_shift($this->chunks); + } + if ($this->thenFail !== null) { + throw $this->thenFail; + } + return ''; + } + + public function getContents(): string + { + return ''; + } + + public function getMetadata(?string $key = null) + { + return $key === null ? [] : null; + } +} + +/** Fails the requests that open a stream with less than the minimum timeout, as the API would. */ +final class MinStreamTimeoutTransport implements HttpClientInterface +{ + public function __construct(private MockTransport $inner) + { + } + + public function send(RequestInterface $request, float $timeoutSecs): ResponseInterface + { + return $this->inner->send($request, $timeoutSecs); + } + + public function sendStreaming(RequestInterface $request, float $timeoutSecs): ResponseInterface + { + if ($timeoutSecs < StreamedLog::MIN_STREAM_TIMEOUT_SECS) { + throw new TransportException('timed out', null, true); + } + return $this->inner->sendStreaming($request, $timeoutSecs); + } +} diff --git a/tests/Unit/MethodTierTest.php b/tests/Unit/MethodTierTest.php index 0cff93b..e5b2f26 100644 --- a/tests/Unit/MethodTierTest.php +++ b/tests/Unit/MethodTierTest.php @@ -8,6 +8,7 @@ use Apify\Client\Internal\Json; use Apify\Client\Model\ActorEnvVar; use Apify\Client\Model\RequestQueueRequest; +use Apify\Client\Options\DownloadItemsFormat; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -29,7 +30,8 @@ public static function tierCases(): iterable yield 'Actor env var list' => [static fn (ApifyClient $c) => $c->actor('a')->version('0.1')->envVars()->list(), self::SHORT, self::PAGE_BODY]; yield 'Actor env var create' => [static fn (ApifyClient $c) => $c->actor('a')->version('0.1')->envVars()->create(new ActorEnvVar('N', 'v')), self::SHORT, self::ITEM_BODY]; yield 'Actor version list' => [static fn (ApifyClient $c) => $c->actor('a')->versions()->list(), self::SHORT, self::PAGE_BODY]; - yield 'Actor version create' => [static fn (ApifyClient $c) => $c->actor('a')->versions()->create(['versionNumber' => '0.1']), self::SHORT, self::ITEM_BODY]; + yield 'Actor version create' => [static fn (ApifyClient $c) => $c->actor('a')->versions()->create(['versionNumber' => '0.1']), self::LONG, self::ITEM_BODY]; + yield 'Actor version update' => [static fn (ApifyClient $c) => $c->actor('a')->version('0.1')->update(['buildTag' => 'latest']), self::LONG, self::ITEM_BODY]; yield 'Dataset getOrCreate' => [static fn (ApifyClient $c) => $c->datasets()->getOrCreate('d'), self::SHORT, self::ITEM_BODY]; yield 'Key-value store getOrCreate' => [static fn (ApifyClient $c) => $c->keyValueStores()->getOrCreate('s'), self::SHORT, self::ITEM_BODY]; yield 'Request queue getOrCreate' => [static fn (ApifyClient $c) => $c->requestQueues()->getOrCreate('q'), self::SHORT, self::ITEM_BODY]; @@ -44,11 +46,16 @@ public static function tierCases(): iterable ]; yield 'Request queue deleteRequestLock' => [static fn (ApifyClient $c) => $c->requestQueue('q')->deleteRequestLock('r1'), self::SHORT, '']; yield 'Key-value store update' => [static fn (ApifyClient $c) => $c->keyValueStore('s')->update(['title' => 't']), self::LONG, self::ITEM_BODY]; + yield 'Key-value store streamRecord' => [static fn (ApifyClient $c) => $c->keyValueStore('s')->streamRecord('k'), self::LONG, 'x']; + yield 'Dataset streamItems' => [static fn (ApifyClient $c) => $c->dataset('d')->streamItems(DownloadItemsFormat::JSON), self::LONG, '[]']; + yield 'Log stream' => [static fn (ApifyClient $c) => $c->log('r')->stream(), self::LONG, 'log']; yield 'Key-value store recordExists' => [static fn (ApifyClient $c) => $c->keyValueStore('s')->recordExists('k'), self::LONG, '']; yield 'Key-value store getRecordPublicUrl' => [static fn (ApifyClient $c) => $c->keyValueStore('s')->getRecordPublicUrl('k'), self::LONG, self::ITEM_BODY]; yield 'Key-value store createKeysPublicUrl' => [static fn (ApifyClient $c) => $c->keyValueStore('s')->createKeysPublicUrl(), self::LONG, self::ITEM_BODY]; yield 'Dataset createItemsPublicUrl' => [static fn (ApifyClient $c) => $c->dataset('d')->createItemsPublicUrl(), self::LONG, self::ITEM_BODY]; yield 'Dataset pushItems' => [static fn (ApifyClient $c) => $c->dataset('d')->pushItems([['a' => 1]]), self::MEDIUM, '']; + yield 'Task publish' => [static fn (ApifyClient $c) => $c->task('t')->publish(), self::SHORT, self::ITEM_BODY]; + yield 'Task unpublish' => [static fn (ApifyClient $c) => $c->task('t')->unpublish(), self::SHORT, self::ITEM_BODY]; yield 'Schedule getLog' => [static fn (ApifyClient $c) => $c->schedule('s')->getLog(), self::MEDIUM, '{"data":[]}']; } diff --git a/tests/Unit/RunIterateDatasetItemsTest.php b/tests/Unit/RunIterateDatasetItemsTest.php index 4b42774..f6c8b79 100644 --- a/tests/Unit/RunIterateDatasetItemsTest.php +++ b/tests/Unit/RunIterateDatasetItemsTest.php @@ -61,6 +61,7 @@ private static function ids(iterable $items): array { $ids = []; foreach ($items as $item) { + /** @var array{id: int} $item */ $ids[] = $item['id']; } return $ids; diff --git a/tests/Unit/SpecSyncTest.php b/tests/Unit/SpecSyncTest.php index 8f33308..6d1a067 100644 --- a/tests/Unit/SpecSyncTest.php +++ b/tests/Unit/SpecSyncTest.php @@ -157,7 +157,9 @@ public function testUserFetchedWithAProxyPasswordHasNoIdOrUsername(): void self::assertNotNull($user); self::assertNull($user->getId()); self::assertNull($user->getUsername()); - self::assertSame(200, $user->toArray()['plan']['availableProxyGroups']['GOOGLE_SERP']); + /** @var array{plan: array{availableProxyGroups: array}} $fields */ + $fields = $user->toArray(); + self::assertSame(200, $fields['plan']['availableProxyGroups']['GOOGLE_SERP']); self::assertTrue($user->get('isPaying')); } diff --git a/tests/Unit/StoreSearchTest.php b/tests/Unit/StoreSearchTest.php new file mode 100644 index 0000000..c9910b3 --- /dev/null +++ b/tests/Unit/StoreSearchTest.php @@ -0,0 +1,119 @@ +search()}, which the API answers with one page and no pagination. */ +final class StoreSearchTest extends TestCase +{ + private function client(MockTransport $transport): ApifyClient + { + return new ApifyClient(token: 't', minDelayBetweenRetriesMillis: 1, timeoutSecs: 5, httpClient: $transport); + } + + /** @return array|string> */ + private static function queryOf(MockTransport $transport): array + { + parse_str($transport->lastRequest()->getUri()->getQuery(), $query); + return $query; + } + + /** A search response. The API fills `total` with the count and `offset` with zero. */ + private static function searchResponse(): string + { + return Json::encode(['data' => [ + 'items' => [['id' => 'a1', 'name' => 'one'], ['id' => 'a2', 'name' => 'two']], + 'total' => 2, + 'offset' => 0, + 'limit' => 100, + 'count' => 2, + 'desc' => false, + ]]); + } + + public function testSearchSendsOneRequestWithTheQueryAlone(): void + { + $transport = (new MockTransport())->queueResponse(200, self::searchResponse()); + + $this->client($transport)->store()->search(new StoreSearchOptions('my search')); + + self::assertSame(1, $transport->callCount()); + self::assertSame(['search' => 'my search'], self::queryOf($transport)); + self::assertStringContainsString('/v2/store?', (string) $transport->lastRequest()->getUri()); + } + + public function testSearchSendsEveryOption(): void + { + $transport = (new MockTransport())->queueResponse(200, self::searchResponse()); + $options = new StoreSearchOptions( + 'my search', + limit: 5, + category: 'AI_AND_ML', + username: 'apify', + pricingModel: 'FREE', + includeUnrunnableActors: true, + responseFormat: 'agent', + includeInputSchema: true, + ); + + $this->client($transport)->store()->search($options); + + self::assertSame([ + 'search' => 'my search', + 'limit' => '5', + 'category' => 'AI_AND_ML', + 'username' => 'apify', + 'pricingModel' => 'FREE', + 'includeUnrunnableActors' => '1', + 'responseFormat' => 'agent', + 'includeInputSchema' => '1', + ], self::queryOf($transport)); + } + + public function testSearchResolvesToTheItemsAndTheLimitTheApiApplied(): void + { + $transport = (new MockTransport())->queueResponse(200, self::searchResponse()); + + $result = $this->client($transport)->store()->search(new StoreSearchOptions('my search')); + + self::assertSame(['a1', 'a2'], array_map(static fn ($item) => $item->getId(), $result->getItems())); + self::assertSame(100, $result->getLimit()); + self::assertCount(2, $result); + self::assertSame(['a1', 'a2'], array_map(static fn ($item) => $item->getId(), iterator_to_array($result))); + } + + public function testListSendsNoSearchParameters(): void + { + $transport = (new MockTransport())->queueResponse(200, self::searchResponse()); + + $this->client($transport)->store()->list(new StoreListOptions(limit: 3, offset: 2, username: 'apify')); + + self::assertSame(['offset' => '2', 'limit' => '3', 'username' => 'apify'], self::queryOf($transport)); + } + + /** @return iterable */ + public static function invalidSearchOptions(): iterable + { + yield 'an empty query' => [static fn () => new StoreSearchOptions('')]; + yield 'a limit of zero' => [static fn () => new StoreSearchOptions('my search', limit: 0)]; + yield 'a negative limit' => [static fn () => new StoreSearchOptions('my search', limit: -1)]; + } + + /** @param callable():StoreSearchOptions $build */ + #[DataProvider('invalidSearchOptions')] + public function testSearchOptionsRejectInvalidValuesBeforeAnyRequest(callable $build): void + { + $this->expectException(InvalidArgumentException::class); + + $build(); + } +} diff --git a/tests/Unit/TaskPublishUnpublishTest.php b/tests/Unit/TaskPublishUnpublishTest.php index 266adb9..8c38f99 100644 --- a/tests/Unit/TaskPublishUnpublishTest.php +++ b/tests/Unit/TaskPublishUnpublishTest.php @@ -51,4 +51,17 @@ public function testUnpublishSendsIsPublicFalse(): void self::assertStringContainsString('/actor-tasks/task1', (string) $request->getUri()); self::assertSame(['isPublic' => false], Json::decode(MockTransport::readBody($request))); } + + public function testPublishAndUnpublishUseTheGivenTimeout(): void + { + $transport = (new MockTransport()) + ->queueResponse(200, Json::encode(['data' => ['id' => 'task1']])) + ->queueResponse(200, Json::encode(['data' => ['id' => 'task1']])); + $task = $this->client($transport)->task('task1'); + + $task->publish(7); + $task->unpublish(9); + + self::assertSame([7.0, 9.0], $transport->timeouts); + } } diff --git a/tests/Unit/TimeoutTiersTest.php b/tests/Unit/TimeoutTiersTest.php index 8ab69d1..f751e10 100644 --- a/tests/Unit/TimeoutTiersTest.php +++ b/tests/Unit/TimeoutTiersTest.php @@ -236,8 +236,8 @@ public function testCallStartsAndPollsWithoutARequestTimeoutByDefault(): void ->queueResponse(200, self::runBody('SUCCEEDED')); $client = new ApifyClient(token: 't', httpClient: $transport); - $client->actor('a1')->call(); - $client->task('t1')->call(null, null, null, 40); + $client->actor('a1')->call(log: false); + $client->task('t1')->call(null, null, null, 40, false); self::assertSame([0.0, 0.0, 40.0, 40.0], $transport->timeouts); } diff --git a/tests/Unit/UrlNormalizerTest.php b/tests/Unit/UrlNormalizerTest.php index af3b436..b2fe32e 100644 --- a/tests/Unit/UrlNormalizerTest.php +++ b/tests/Unit/UrlNormalizerTest.php @@ -123,6 +123,7 @@ public function testNormalizeFieldsFollowsPathsAndWildcards(): void 'notAString' => 5, ]; + /** @var array{a: string, nested: array, map: array, notAString: int} $normalized */ $normalized = UrlNormalizer::normalizeFields($data, ['a', 'nested.b', 'map.*', 'notAString', 'missing.key']); self::assertSame('https://example.com/', $normalized['a']); @@ -141,7 +142,9 @@ public function testModelsNormalizeTheirUrlFields(): void ]); self::assertSame('https://abc.runs.apify.net/', $run->getContainerUrl()); self::assertSame('https://abc.runs.apify.net/', $run->get('containerUrl')); - self::assertSame('https://api.apify.com/v2/datasets/d1/items', $run->toArray()['output']['results']); + /** @var array{output: array{results: string}} $runFields */ + $runFields = $run->toArray(); + self::assertSame('https://api.apify.com/v2/datasets/d1/items', $runFields['output']['results']); self::assertSame('https://x.example/', (new Dataset(['itemsPublicUrl' => 'https://X.example']))->get('itemsPublicUrl')); self::assertSame('https://x.example/', (new KeyValueStore(['keysPublicUrl' => 'https://X.example']))->get('keysPublicUrl')); @@ -149,11 +152,12 @@ public function testModelsNormalizeTheirUrlFields(): void self::assertSame('https://x.example/', (new KeyValueStoreKey(['recordPublicUrl' => 'https://X.example']))->get('recordPublicUrl')); self::assertSame('https://x.example/', (new Task(['standbyUrl' => 'https://X.example']))->get('standbyUrl')); self::assertSame('https://x.example/hook', (new Webhook(['requestUrl' => 'https://X.example:443/hook']))->getRequestUrl()); - self::assertSame( - 'https://x.example/hook', - (new WebhookDispatch(['webhook' => ['requestUrl' => 'https://X.example/hook']]))->toArray()['webhook']['requestUrl'], - ); + /** @var array{webhook: array{requestUrl: string}} $dispatchFields */ + $dispatchFields = (new WebhookDispatch(['webhook' => ['requestUrl' => 'https://X.example/hook']]))->toArray(); + self::assertSame('https://x.example/hook', $dispatchFields['webhook']['requestUrl']); $user = new User(['profile' => ['pictureUrl' => 'https://X.example', 'websiteUrl' => 'https://Y.example', 'name' => 'Not A URL']]); - self::assertSame(['https://x.example/', 'https://y.example/', 'Not A URL'], array_values($user->toArray()['profile'])); + /** @var array{profile: array} $userFields */ + $userFields = $user->toArray(); + self::assertSame(['https://x.example/', 'https://y.example/', 'Not A URL'], array_values($userFields['profile'])); } } diff --git a/tests/Unit/UrlPartsTest.php b/tests/Unit/UrlPartsTest.php new file mode 100644 index 0000000..6e6eaea --- /dev/null +++ b/tests/Unit/UrlPartsTest.php @@ -0,0 +1,30 @@ + */ + public static function urls(): iterable + { + yield 'path and query' => ['https://api.apify.com/v2/acts?limit=1', 'https://api.apify.com', '/v2/acts?limit=1']; + yield 'port' => ['http://localhost:3000/v2/x', 'http://localhost:3000', '/v2/x']; + yield 'no path' => ['https://api.apify.com', 'https://api.apify.com', '']; + yield 'trailing slash' => ['https://api.apify.com/', 'https://api.apify.com', '/']; + yield 'no scheme' => ['api.apify.com/v2', 'api.apify.com', '/v2']; + yield 'empty' => ['', '', '']; + } + + #[DataProvider('urls')] + public function testOriginAndPathAndQuery(string $url, string $origin, string $pathAndQuery): void + { + self::assertSame($origin, UrlParts::origin($url)); + self::assertSame($pathAndQuery, UrlParts::pathAndQuery($url)); + } +}