From d031f9503b53bfddad7eae1a97d5ca1b6f61dad6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:41:46 +0000 Subject: [PATCH 01/20] fix: iterate Store search as one page, long timeout for Actor version uploads, deprecate Store sortBy --- CHANGELOG.md | 8 ++++++++ docs/actors.md | 3 ++- docs/misc.md | 4 ++-- docs/options.md | 10 +++++----- src/Options/StoreListOptions.php | 15 +++++++++----- src/Resource/ActorVersionClient.php | 5 +++-- src/Resource/ActorVersionCollectionClient.php | 5 +++-- src/Resource/StoreCollectionClient.php | 16 +++++++++++++++ src/Version.php | 2 +- tests/Integration/StoreIntegrationTest.php | 20 +++++++++++++++++++ tests/Unit/IterationTest.php | 17 ++++++++++++++++ tests/Unit/MethodTierTest.php | 3 ++- 12 files changed, 89 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e219910..0e2bfee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.14.2 + +- Synced with the Apify OpenAPI spec `v2-2026-11-18T151559Z`, as updated: Store Actors have the new `stats` and `isVerified` fields, the run origin `APIFY_AI` exists, and some response fields can be `null`. The models return them as received. +- `StoreListOptions::$sortBy` is deprecated, as the API ignores it. +- `store()->iterate()` with `search` makes one request, as the API returns a single page of at most 100 Actors and ignores `offset`. It used to repeat that page. +- `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 and the `search` page limit. + ## 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/docs/actors.md b/docs/actors.md index 13df8bc..93182a2 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -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/misc.md b/docs/misc.md index e6fd46e..040d3e5 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -5,14 +5,14 @@ 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. +- `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. With `search`, the API returns one page of at most 100 Actors and ignores `offset`, so `iterate()` makes one request and ignores `$chunkSize`. ```php $page = $client->store()->list(new StoreListOptions(search: 'scraper', limit: 10)); $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; diff --git a/docs/options.md b/docs/options.md index 2e0ceb2..e2dac3b 100644 --- a/docs/options.md +++ b/docs/options.md @@ -80,11 +80,11 @@ Extra filters for `runs()->list()`, combined with a `ListOptions`. For `store()->list()` / `store()->iterate()`. | 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. | +| `offset` | `?int` | Number of Actors to skip. The API ignores it with `search`. | +| `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 `search`, the API returns at most 100. | +| `search` | `?string` | Full-text search query. The API ranks the results by relevance and returns one page of at most 100 Actors. | +| `sortBy` | `?string` | Deprecated: the API accepts it and ignores it. Sort the results on the client instead. | +| `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. | diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index 830c250..0a01159 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -10,18 +10,23 @@ final class StoreListOptions { public function __construct( - /** Number of Actors to skip. */ + /** Number of Actors to skip. The API ignores it with {@code search}. */ 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 search}, the API returns at most 100. */ public readonly ?int $limit = null, - /** Full-text search query. */ + /** Full-text search query. The API ranks the results by relevance and returns one page of at most 100 Actors. */ public readonly ?string $search = null, - /** The sort field (e.g. {@code "popularity"}, {@code "newest"}). */ + /** + * Deprecated: the API accepts it and ignores it. Results are ordered by relevance with {@code search} and by + * Store position otherwise, so sort them on the client. + * + * @deprecated + */ 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, 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/StoreCollectionClient.php b/src/Resource/StoreCollectionClient.php index 64f9c15..973f0d1 100644 --- a/src/Resource/StoreCollectionClient.php +++ b/src/Resource/StoreCollectionClient.php @@ -40,11 +40,17 @@ 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 * {@code $chunkSize} sets the page size ({@code null} for the API's default). * + * With {@code search}, the API ignores {@code offset} and returns one page of at most 100 Actors, so this makes + * one request with the {@code limit} option and ignores {@code $chunkSize}. + * * @return Generator */ public function iterate(?StoreListOptions $options = null, ?int $chunkSize = null, int|float|string|null $timeoutSecs = null): Generator { $options ??= new StoreListOptions(); + if ($options->search !== null && $options->search !== '') { + return $this->iterateSearchPage($options, $timeoutSecs); + } return ResourceContext::paginateOffset( $options->offset ?? 0, $options->limit, @@ -52,4 +58,14 @@ public function iterate(?StoreListOptions $options = null, ?int $chunkSize = nul fn (int $offset, ?int $pageLimit) => $this->list($options->withPagination($offset, $pageLimit), $timeoutSecs), ); } + + /** + * Yields the single page of a search, which the API cannot continue with an offset. + * + * @return Generator + */ + private function iterateSearchPage(StoreListOptions $options, int|float|string|null $timeoutSecs): Generator + { + yield from $this->list($options->withPagination(null, $options->limit), $timeoutSecs)->getItems(); + } } diff --git a/src/Version.php b/src/Version.php index 24c1aab..4c870b7 100644 --- a/src/Version.php +++ b/src/Version.php @@ -17,7 +17,7 @@ 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.14.2'; /** * The version of the Apify OpenAPI specification this client was generated and verified diff --git a/tests/Integration/StoreIntegrationTest.php b/tests/Integration/StoreIntegrationTest.php index 5bfd455..107fd96 100644 --- a/tests/Integration/StoreIntegrationTest.php +++ b/tests/Integration/StoreIntegrationTest.php @@ -31,6 +31,26 @@ public function testListStoreWithInputSchema(): void self::assertNotEmpty($schemas, 'at least one Store Actor carries its input schema'); } + public function testListStoreAcceptsTheDeprecatedSortBy(): void + { + $client = $this->requireClient(); + // The API accepts `sortBy` and ignores it, so the order is not asserted. + $page = $client->store()->list(new StoreListOptions(limit: 10, sortBy: 'popularity')); + self::assertNotEmpty($page->getItems()); + } + + public function testIterateStoreSearchReturnsOnePage(): void + { + $client = $this->requireClient(); + $ids = []; + foreach ($client->store()->iterate(new StoreListOptions(search: 'website content crawler', limit: 20), 5) as $item) { + $ids[] = $item->getId(); + } + self::assertNotEmpty($ids); + self::assertLessThanOrEqual(20, count($ids)); + self::assertSame($ids, array_unique($ids), 'a search must not repeat its page'); + } + public function testIterateStore(): void { $client = $this->requireClient(); diff --git a/tests/Unit/IterationTest.php b/tests/Unit/IterationTest.php index c532da9..1828533 100644 --- a/tests/Unit/IterationTest.php +++ b/tests/Unit/IterationTest.php @@ -172,6 +172,23 @@ public function testStorePageCountIsCappedAtTheRequestedLimit(): void self::assertStringContainsString('offset=2', (string) $transport->received[1]->getUri()); } + public function testStoreSearchIsASinglePageThatIgnoresTheOffset(): void + { + // With `search` the API ignores the offset, so a second request would repeat the first page forever. + $transport = (new MockTransport()) + ->queueResponse(200, self::pageWithCount(self::actors(1, 2), 2, 0)); + $ids = []; + foreach ($this->client($transport)->store()->iterate(new StoreListOptions(search: 'scraper', limit: 50, offset: 7), 1) as $item) { + $ids[] = $item->getId(); + } + self::assertSame(['a1', 'a2'], $ids); + self::assertSame(1, $transport->callCount()); + $uri = (string) $transport->received[0]->getUri(); + self::assertStringContainsString('search=scraper', $uri); + self::assertStringContainsString('limit=50', $uri); + self::assertStringNotContainsString('offset=', $uri); + } + public function testLimitCapStopsBeforeExhaustingPages(): void { // limit=2 with a big first page: only 2 items are yielded and no second request is made. diff --git a/tests/Unit/MethodTierTest.php b/tests/Unit/MethodTierTest.php index 0cff93b..f9313f1 100644 --- a/tests/Unit/MethodTierTest.php +++ b/tests/Unit/MethodTierTest.php @@ -29,7 +29,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]; From c31388c64be0e21a0a834ac531c8c3e21352410f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:56:56 +0000 Subject: [PATCH 02/20] fix: address review of Store search docs, deprecation tag, PHPStan level 9, user by ID test --- CHANGELOG.md | 2 +- composer.json | 2 +- docs/options.md | 6 +++--- phpstan.neon.dist | 4 +--- src/Options/ActorServerRequestOptions.php | 5 ++++- src/Options/StoreListOptions.php | 6 +++--- tests/Integration/ActorRunIntegrationTest.php | 2 ++ tests/Integration/DatasetIntegrationTest.php | 5 ++++- tests/Integration/UserIntegrationTest.php | 10 ++++++++++ .../ZstdCompressionIntegrationTest.php | 4 +++- tests/Unit/HttpClientTest.php | 4 +++- tests/Unit/IterationTest.php | 3 +++ tests/Unit/RunIterateDatasetItemsTest.php | 1 + tests/Unit/SpecSyncTest.php | 4 +++- tests/Unit/UrlNormalizerTest.php | 16 ++++++++++------ 15 files changed, 52 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e2bfee..46ddf46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,11 @@ ## 0.14.2 -- Synced with the Apify OpenAPI spec `v2-2026-11-18T151559Z`, as updated: Store Actors have the new `stats` and `isVerified` fields, the run origin `APIFY_AI` exists, and some response fields can be `null`. The models return them as received. - `StoreListOptions::$sortBy` is deprecated, as the API ignores it. - `store()->iterate()` with `search` makes one request, as the API returns a single page of at most 100 Actors and ignores `offset`. It used to repeat that page. - `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 and the `search` page limit. +- Raised PHPStan to level 9 and added an integration test for `user($id)->get()`. ## 0.14.1 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/options.md b/docs/options.md index e2dac3b..36117c9 100644 --- a/docs/options.md +++ b/docs/options.md @@ -17,11 +17,11 @@ 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 the Apify Store. A Store `search` is one page that ignores +`offset`, so page by a filter such as `category`: ```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) { diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 21a6f5b..42888f2 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,7 +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 diff --git a/src/Options/ActorServerRequestOptions.php b/src/Options/ActorServerRequestOptions.php index 62835f8..f54b212 100644 --- a/src/Options/ActorServerRequestOptions.php +++ b/src/Options/ActorServerRequestOptions.php @@ -86,7 +86,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 0a01159..13665f6 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -20,10 +20,10 @@ public function __construct( /** Full-text search query. The API ranks the results by relevance and returns one page of at most 100 Actors. */ public readonly ?string $search = null, /** - * Deprecated: the API accepts it and ignores it. Results are ordered by relevance with {@code search} and by - * Store position otherwise, so sort them on the client. + * The sort field. * - * @deprecated + * @deprecated The API ignores it. Results are ordered by relevance with {@code search} and by Store position + * otherwise, so sort them on the client. */ public readonly ?string $sortBy = null, /** Filter Actors by one or more comma-separated category IDs, such as {@code AI_AND_ML}. An Actor must match all of them. */ diff --git a/tests/Integration/ActorRunIntegrationTest.php b/tests/Integration/ActorRunIntegrationTest.php index 98f84bf..52a178a 100644 --- a/tests/Integration/ActorRunIntegrationTest.php +++ b/tests/Integration/ActorRunIntegrationTest.php @@ -139,6 +139,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 +224,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(); 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/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/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 1828533..f6f6c65 100644 --- a/tests/Unit/IterationTest.php +++ b/tests/Unit/IterationTest.php @@ -225,6 +225,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); @@ -261,6 +262,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); @@ -296,6 +298,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/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/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'])); } } From 6b06fa9a7c506a708631f7e4fdd45b372850904d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:32:48 +0000 Subject: [PATCH 03/20] feat!: split Store search from the Store listing, sync with spec v2-2026-12-02T102104Z store()->list() and iterate() lose search and sortBy, and the new store()->search() returns the best matches as one page. Removes the allowsAgenticUsers filter dropped from the spec. --- CHANGELOG.md | 7 +- docs/README.md | 2 +- docs/misc.md | 10 +- docs/models.md | 9 +- docs/options.md | 25 +++-- src/Internal/StoreFilters.php | 35 ++++++ src/Model/StoreSearchResult.php | 69 ++++++++++++ src/Options/StoreListOptions.php | 48 +++------ src/Options/StoreSearchOptions.php | 61 +++++++++++ src/Resource/StoreCollectionClient.php | 29 ++--- src/Version.php | 4 +- tests/Examples/DocSnippetsTest.php | 1 + tests/Integration/StoreIntegrationTest.php | 69 +++++++++--- tests/Unit/IterationTest.php | 17 --- tests/Unit/StoreSearchTest.php | 119 +++++++++++++++++++++ 15 files changed, 414 insertions(+), 91 deletions(-) create mode 100644 src/Internal/StoreFilters.php create mode 100644 src/Model/StoreSearchResult.php create mode 100644 src/Options/StoreSearchOptions.php create mode 100644 tests/Unit/StoreSearchTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 46ddf46..e740e0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,10 @@ # Changelog -## 0.14.2 +## 0.15.0 -- `StoreListOptions::$sortBy` is deprecated, as the API ignores it. -- `store()->iterate()` with `search` makes one request, as the API returns a single page of at most 100 Actors and ignores `offset`. It used to repeat that page. +- Synced with Apify OpenAPI spec `v2-2026-12-02T102104Z`: the API dropped the Store `allowsAgenticUsers` filter. +- **Breaking:** `StoreListOptions` loses `search`, `sortBy` and `allowsAgenticUsers`. `store()->list()` and `iterate()` browse the Store in Store order, and `iterate()` no longer special-cases a search. +- 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 and the `search` page limit. - Raised PHPStan to level 9 and added an integration test for `user($id)->get()`. diff --git a/docs/README.md b/docs/README.md index 0f5d357..9f3b095 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 the public 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/misc.md b/docs/misc.md index 040d3e5..d395238 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -4,11 +4,15 @@ 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. With `search`, the API returns one page of at most 100 Actors and ignores `offset`, so `iterate()` makes one request and ignores `$chunkSize`. +- `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. diff --git a/docs/models.md b/docs/models.md index f4194be..3d18c6f 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 the 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` diff --git a/docs/options.md b/docs/options.md index 36117c9..f9fdc42 100644 --- a/docs/options.md +++ b/docs/options.md @@ -17,8 +17,7 @@ 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, for example the Apify Store. A Store `search` is one page that ignores -`offset`, so page by a filter such as `category`: +page manually through `list()` results, for example the Apify Store: ```php $options = new StoreListOptions(category: 'AI_AND_ML'); @@ -77,23 +76,33 @@ Extra filters for `runs()->list()`, combined with a `ListOptions`. | `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()`. | ### `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. The API ignores it with `search`. | -| `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 `search`, the API returns at most 100. | -| `search` | `?string` | Full-text search query. The API ranks the results by relevance and returns one page of at most 100 Actors. | -| `sortBy` | `?string` | Deprecated: the API accepts it and ignores it. Sort the results on the client instead. | +| `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). | | `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. | | `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). | 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 is 100, and the API reduces a larger value to 100. With `includeInputSchema`, the default and the maximum are 10. | +| `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. | +| `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 | 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/Model/StoreSearchResult.php b/src/Model/StoreSearchResult.php new file mode 100644 index 0000000..970216b --- /dev/null +++ b/src/Model/StoreSearchResult.php @@ -0,0 +1,69 @@ + + */ +final class StoreSearchResult implements IteratorAggregate, Countable +{ + /** + * @param list $items + */ + public function __construct( + private array $items, + private int $limit, + ) { + } + + /** Builds the result from a decoded Store response page. */ + public static function fromPage(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/StoreListOptions.php b/src/Options/StoreListOptions.php index 13665f6..cc12aba 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -5,27 +5,19 @@ 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 the Apify Store ({@code GET /v2/store}). The Actors come in Store order, which the API + * has no option to change. To find Actors by a text query, use {@see StoreSearchOptions}. + */ final class StoreListOptions { public function __construct( - /** Number of Actors to skip. The API ignores it with {@code search}. */ + /** Number of Actors to skip. */ 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}). With {@code search}, the API returns at most 100. - */ + /** The maximum number of Actors. When iterating, it caps the total over all pages, not the page size ({@code chunkSize}). */ public readonly ?int $limit = null, - /** Full-text search query. The API ranks the results by relevance and returns one page of at most 100 Actors. */ - public readonly ?string $search = null, - /** - * The sort field. - * - * @deprecated The API ignores it. Results are ordered by relevance with {@code search} and by Store position - * otherwise, so sort them on the client. - */ - public readonly ?string $sortBy = null, /** 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. */ @@ -34,8 +26,6 @@ public function __construct( public readonly ?string $pricingModel = null, /** Include Actors the current user cannot run. */ 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. */ @@ -49,13 +39,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, ); @@ -64,16 +51,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..b2f3bea --- /dev/null +++ b/src/Options/StoreSearchOptions.php @@ -0,0 +1,61 @@ +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/StoreCollectionClient.php b/src/Resource/StoreCollectionClient.php index 973f0d1..29b1fcb 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 the 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,20 +39,14 @@ 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). * - * With {@code search}, the API ignores {@code offset} and returns one page of at most 100 Actors, so this makes - * one request with the {@code limit} option and ignores {@code $chunkSize}. - * * @return Generator */ public function iterate(?StoreListOptions $options = null, ?int $chunkSize = null, int|float|string|null $timeoutSecs = null): Generator { $options ??= new StoreListOptions(); - if ($options->search !== null && $options->search !== '') { - return $this->iterateSearchPage($options, $timeoutSecs); - } return ResourceContext::paginateOffset( $options->offset ?? 0, $options->limit, @@ -60,12 +56,19 @@ public function iterate(?StoreListOptions $options = null, ?int $chunkSize = nul } /** - * Yields the single page of a search, which the API cannot continue with an offset. + * Returns the Actors that match a query best, ordered by relevance. * - * @return Generator + * 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()}. */ - private function iterateSearchPage(StoreListOptions $options, int|float|string|null $timeoutSecs): Generator + public function search(StoreSearchOptions $options, int|float|string|null $timeoutSecs = null): StoreSearchResult { - yield from $this->list($options->withPagination(null, $options->limit), $timeoutSecs)->getItems(); + $params = new QueryParams(); + $options->appendTo($params); + return StoreSearchResult::fromPage( + $this->ctx->getResourceRequired('', $params, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_MEDIUM)), + ); } } diff --git a/src/Version.php b/src/Version.php index 4c870b7..f84515d 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.2'; + 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-02T102104Z'; private function __construct() { diff --git a/tests/Examples/DocSnippetsTest.php b/tests/Examples/DocSnippetsTest.php index ef80c53..1082d0d 100644 --- a/tests/Examples/DocSnippetsTest.php +++ b/tests/Examples/DocSnippetsTest.php @@ -86,6 +86,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/Integration/StoreIntegrationTest.php b/tests/Integration/StoreIntegrationTest.php index 107fd96..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,24 +32,68 @@ public function testListStoreWithInputSchema(): void self::assertNotEmpty($schemas, 'at least one Store Actor carries its input schema'); } - public function testListStoreAcceptsTheDeprecatedSortBy(): void + public function testListStoreFiltersByUsername(): void { $client = $this->requireClient(); - // The API accepts `sortBy` and ignores it, so the order is not asserted. - $page = $client->store()->list(new StoreListOptions(limit: 10, sortBy: 'popularity')); + $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 testIterateStoreSearchReturnsOnePage(): void + public function testSearchFiltersByUsername(): void { $client = $this->requireClient(); - $ids = []; - foreach ($client->store()->iterate(new StoreListOptions(search: 'website content crawler', limit: 20), 5) as $item) { - $ids[] = $item->getId(); + $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()); } - self::assertNotEmpty($ids); - self::assertLessThanOrEqual(20, count($ids)); - self::assertSame($ids, array_unique($ids), 'a search must not repeat its page'); + } + + 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 diff --git a/tests/Unit/IterationTest.php b/tests/Unit/IterationTest.php index f6f6c65..e381527 100644 --- a/tests/Unit/IterationTest.php +++ b/tests/Unit/IterationTest.php @@ -172,23 +172,6 @@ public function testStorePageCountIsCappedAtTheRequestedLimit(): void self::assertStringContainsString('offset=2', (string) $transport->received[1]->getUri()); } - public function testStoreSearchIsASinglePageThatIgnoresTheOffset(): void - { - // With `search` the API ignores the offset, so a second request would repeat the first page forever. - $transport = (new MockTransport()) - ->queueResponse(200, self::pageWithCount(self::actors(1, 2), 2, 0)); - $ids = []; - foreach ($this->client($transport)->store()->iterate(new StoreListOptions(search: 'scraper', limit: 50, offset: 7), 1) as $item) { - $ids[] = $item->getId(); - } - self::assertSame(['a1', 'a2'], $ids); - self::assertSame(1, $transport->callCount()); - $uri = (string) $transport->received[0]->getUri(); - self::assertStringContainsString('search=scraper', $uri); - self::assertStringContainsString('limit=50', $uri); - self::assertStringNotContainsString('offset=', $uri); - } - public function testLimitCapStopsBeforeExhaustingPages(): void { // limit=2 with a big first page: only 2 items are yielded and no second request is made. 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(); + } +} From cd9b0d0413eabd59da0168a20fe80e37beb307e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:41:39 +0000 Subject: [PATCH 04/20] fix: address review of Store search split, document public URL scope and input schema limit --- CHANGELOG.md | 5 +++-- docs/README.md | 2 +- docs/misc.md | 2 +- docs/models.md | 4 ++-- docs/options.md | 8 ++++---- docs/storages.md | 4 ++-- phpstan.neon.dist | 1 - src/ApifyClient.php | 2 +- src/Model/ActorStoreListItem.php | 2 +- src/Model/StoreSearchResult.php | 2 +- src/Options/StoreListOptions.php | 12 +++++++++--- src/Options/StoreSearchOptions.php | 5 +++-- src/Resource/DatasetClient.php | 4 ++++ src/Resource/KeyValueStoreClient.php | 11 +++++++---- src/Resource/StoreCollectionClient.php | 2 +- 15 files changed, 40 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e740e0f..9e1c68c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,11 @@ ## 0.15.0 - Synced with Apify OpenAPI spec `v2-2026-12-02T102104Z`: the API dropped the Store `allowsAgenticUsers` filter. -- **Breaking:** `StoreListOptions` loses `search`, `sortBy` and `allowsAgenticUsers`. `store()->list()` and `iterate()` browse the Store in Store order, and `iterate()` no longer special-cases a search. +- **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 and the `search` page limit. +- 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. - Raised PHPStan to level 9 and added an integration test for `user($id)->get()`. ## 0.14.1 diff --git a/docs/README.md b/docs/README.md index 9f3b095..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 and search 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/misc.md b/docs/misc.md index d395238..47ac5a6 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -6,7 +6,7 @@ Snippets assume `$client = new ApifyClient('my-api-token');` and imported types. - `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. +- `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 $result = $client->store()->search(new StoreSearchOptions('scraper', limit: 10)); diff --git a/docs/models.md b/docs/models.md index 3d18c6f..33413dd 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 or searching the Apify Store. +Returned when listing, iterating, or searching Apify Store. | Getter | Description | |---|---| | `getId(): ?string` | The Actor ID. | @@ -134,7 +134,7 @@ Returned by `store()->search()`. It can be iterated and counted. It has no `tota | 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. | +| `getLimit(): int` | The limit the API applied. With as many items, more Actors may match than were returned. With `includeInputSchema`, a limit above 10 is rejected. | ## Storage models diff --git a/docs/options.md b/docs/options.md index f9fdc42..4bda0fe 100644 --- a/docs/options.md +++ b/docs/options.md @@ -17,7 +17,7 @@ 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, for example the Apify Store: +page manually through `list()` results, for example Apify Store: ```php $options = new StoreListOptions(category: 'AI_AND_ML'); @@ -80,13 +80,13 @@ For `store()->list()` / `store()->iterate()`. The Actors come in Store order, wh | 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). | +| `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`, the API rejects a limit or `$chunkSize` above 10. | | `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. | | `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 API then rejects a `limit` or `$chunkSize` above 10. | Supports [`withPagination($offset, $limit)`](#manual-offset-paging-with-withpagination). @@ -95,7 +95,7 @@ For `store()->search()`. The API answers a search with one page, so there is no | 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 is 100, and the API reduces a larger value to 100. With `includeInputSchema`, the default and the maximum are 10. | +| `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`). | diff --git a/docs/storages.md b/docs/storages.md index 02fc95c..85e56d2 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -23,7 +23,7 @@ Single — `$client->dataset($id)`: - `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. - `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. The signature grants read access to all items until it expires. 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. 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). ```php $dataset = $client->datasets()->getOrCreate('my-dataset'); @@ -64,7 +64,7 @@ Single — `$client->keyValueStore($id)`: - `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. The signature grants access to the list of all keys until it expires. 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. 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). ```php $store = $client->keyValueStores()->getOrCreate('my-store'); diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 42888f2..08566d0 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -3,4 +3,3 @@ parameters: paths: - src - tests - treatPhpDocTypesAsCertain: false diff --git a/src/ApifyClient.php b/src/ApifyClient.php index 3971345..c09b129 100644 --- a/src/ApifyClient.php +++ b/src/ApifyClient.php @@ -287,7 +287,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/Model/ActorStoreListItem.php b/src/Model/ActorStoreListItem.php index cdf0a0d..f589246 100644 --- a/src/Model/ActorStoreListItem.php +++ b/src/Model/ActorStoreListItem.php @@ -4,7 +4,7 @@ namespace Apify\Client\Model; -/** An Actor as listed in the Apify Store. */ +/** An Actor as listed in Apify Store. */ final class ActorStoreListItem extends ApifyResource { protected const URL_FIELDS = ['userPictureUrl', 'url']; diff --git a/src/Model/StoreSearchResult.php b/src/Model/StoreSearchResult.php index 970216b..31b5a3e 100644 --- a/src/Model/StoreSearchResult.php +++ b/src/Model/StoreSearchResult.php @@ -48,7 +48,7 @@ public function getItems(): array /** * 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 + * none or a larger one was requested (with {@code includeInputSchema}, a limit above 10 is rejected). 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 diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index cc12aba..262b7dd 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -8,7 +8,7 @@ use Apify\Client\Internal\StoreFilters; /** - * Options for browsing the Apify Store ({@code GET /v2/store}). The Actors come in Store order, which the API + * 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 @@ -16,7 +16,10 @@ final class StoreListOptions public function __construct( /** Number of Actors to skip. */ 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}). */ + /** + * The maximum number of Actors. When iterating, it caps the total over all pages, not the page size + * ({@code chunkSize}). With {@code includeInputSchema}, the API rejects a limit above 10. + */ public readonly ?int $limit = null, /** 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, @@ -28,7 +31,10 @@ public function __construct( public readonly ?bool $includeUnrunnableActors = 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 API then rejects a {@code limit}, or a {@code chunkSize} when iterating, above 10. + */ public readonly ?bool $includeInputSchema = null, ) { } diff --git a/src/Options/StoreSearchOptions.php b/src/Options/StoreSearchOptions.php index b2f3bea..ea9fd7c 100644 --- a/src/Options/StoreSearchOptions.php +++ b/src/Options/StoreSearchOptions.php @@ -9,7 +9,7 @@ use InvalidArgumentException; /** - * Options for searching the Apify Store ({@code GET /v2/store} with {@code search}). The API answers a search + * Options for searching Apify Store ({@code GET /v2/store} with {@code search}). The API answers a search * with one page of at most 100 Actors, so there is no {@code offset}. To go through the whole Store, use * {@see StoreListOptions}. */ @@ -20,7 +20,8 @@ public function __construct( public readonly string $search, /** * The maximum number of Actors. It defaults to 100, which is also the most the API returns: it reduces a - * larger value to 100. With {@code includeInputSchema}, the default and the maximum are 10. + * larger value to 100. With {@code includeInputSchema}, the default and the maximum are 10, and the API + * rejects a larger value. */ public readonly ?int $limit = null, /** Filter Actors by one or more comma-separated category IDs, such as {@code AI_AND_ML}. An Actor must match all of them. */ diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index f7b8a9e..9ab1c0e 100644 --- a/src/Resource/DatasetClient.php +++ b/src/Resource/DatasetClient.php @@ -195,6 +195,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 until it expires. 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..2cdcc29 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -234,10 +234,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 until it expires. 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/StoreCollectionClient.php b/src/Resource/StoreCollectionClient.php index 29b1fcb..68031b9 100644 --- a/src/Resource/StoreCollectionClient.php +++ b/src/Resource/StoreCollectionClient.php @@ -15,7 +15,7 @@ use Apify\Client\Options\StoreSearchOptions; use Generator; -/** A client for browsing and searching 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; From 2b82662264151d9e7228b511801bdee5a6d48729 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:43:22 +0000 Subject: [PATCH 05/20] fix: drop a vacuous build digest assertion that PHPStan reports without treatPhpDocTypesAsCertain --- tests/Integration/BuildIntegrationTest.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/Integration/BuildIntegrationTest.php b/tests/Integration/BuildIntegrationTest.php index 46bed2d..de10342 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(); From 54bb3d79fef29daacfcd4ff727152e82edddcdb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:50:25 +0000 Subject: [PATCH 06/20] docs: correct the includeInputSchema page size rule and the public URL wording --- docs/models.md | 2 +- docs/options.md | 4 ++-- docs/storages.md | 4 ++-- src/Model/StoreSearchResult.php | 2 +- src/Options/StoreListOptions.php | 6 ++++-- src/Resource/DatasetClient.php | 2 +- src/Resource/KeyValueStoreClient.php | 2 +- 7 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/models.md b/docs/models.md index 33413dd..4ba417e 100644 --- a/docs/models.md +++ b/docs/models.md @@ -134,7 +134,7 @@ Returned by `store()->search()`. It can be iterated and counted. It has no `tota | 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. With `includeInputSchema`, a limit above 10 is rejected. | +| `getLimit(): int` | The limit the API applied. With as many items, more Actors may match than were returned. | ## Storage models diff --git a/docs/options.md b/docs/options.md index 4bda0fe..12ff090 100644 --- a/docs/options.md +++ b/docs/options.md @@ -80,13 +80,13 @@ For `store()->list()` / `store()->iterate()`. The Actors come in Store order, wh | 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). With `includeInputSchema`, the API rejects a limit or `$chunkSize` above 10. | +| `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`, the page size must be 10 or less: the API rejects a larger `limit` of `list()`, and a larger page size of `iterate()`, which is its `$chunkSize`, or the `limit` when there is no `$chunkSize`. | | `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. | | `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). The API then rejects a `limit` or `$chunkSize` above 10. | +| `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). diff --git a/docs/storages.md b/docs/storages.md index 85e56d2..4c1d4ee 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -23,7 +23,7 @@ Single — `$client->dataset($id)`: - `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. - `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. The URL of a private dataset is signed, and valid for `$expiresInSecs` if given. The signature grants read access to all items until it expires. 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. 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'); @@ -64,7 +64,7 @@ Single — `$client->keyValueStore($id)`: - `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. The URL of a private store is signed, and valid for `$expiresInSecs` if given. The signature grants access to the list of all keys until it expires. 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. 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/src/Model/StoreSearchResult.php b/src/Model/StoreSearchResult.php index 31b5a3e..970216b 100644 --- a/src/Model/StoreSearchResult.php +++ b/src/Model/StoreSearchResult.php @@ -48,7 +48,7 @@ public function getItems(): array /** * 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 (with {@code includeInputSchema}, a limit above 10 is rejected). When the result holds that many Actors, more may match the query than + * 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 diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index 262b7dd..570eec0 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -18,7 +18,9 @@ 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}). With {@code includeInputSchema}, the API rejects a limit above 10. + * ({@code chunkSize}). With {@code includeInputSchema}, the page size must be 10 or less: the API rejects + * a larger {@code limit} of {@code list()}, and a larger page size of {@code iterate()}, which is its + * {@code chunkSize}, or the {@code limit} when there is no {@code chunkSize}. */ public readonly ?int $limit = null, /** Filter Actors by one or more comma-separated category IDs, such as {@code AI_AND_ML}. An Actor must match all of them. */ @@ -33,7 +35,7 @@ public function __construct( public readonly ?string $responseFormat = null, /** * Includes the compact input schema of the default build, when it succeeded and defines input properties. - * The API then rejects a {@code limit}, or a {@code chunkSize} when iterating, above 10. + * The page size must then be 10 or less, see {@code limit}. */ public readonly ?bool $includeInputSchema = null, ) { diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index 9ab1c0e..caa50e3 100644 --- a/src/Resource/DatasetClient.php +++ b/src/Resource/DatasetClient.php @@ -195,7 +195,7 @@ 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 until it expires. The options are added to + * 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. * diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index 2cdcc29..bbb0707 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -238,7 +238,7 @@ public function getRecordPublicUrl(string $key, int|float|string|null $timeoutSe * 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 until it expires. The options are added to + * 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. * From a441a3e7be605328366421a24f4faa39163c9ee2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:56:53 +0000 Subject: [PATCH 07/20] docs: state the includeInputSchema page size rule plainly and rewrap two docblocks --- docs/options.md | 2 +- src/Options/StoreListOptions.php | 6 +++--- src/Resource/DatasetClient.php | 6 +++--- src/Resource/KeyValueStoreClient.php | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/options.md b/docs/options.md index 12ff090..3f25711 100644 --- a/docs/options.md +++ b/docs/options.md @@ -80,7 +80,7 @@ For `store()->list()` / `store()->iterate()`. The Actors come in Store order, wh | 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). With `includeInputSchema`, the page size must be 10 or less: the API rejects a larger `limit` of `list()`, and a larger page size of `iterate()`, which is its `$chunkSize`, or the `limit` when there is no `$chunkSize`. | +| `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`). | diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index 570eec0..841c60d 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -18,9 +18,9 @@ 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}). With {@code includeInputSchema}, the page size must be 10 or less: the API rejects - * a larger {@code limit} of {@code list()}, and a larger page size of {@code iterate()}, which is its - * {@code chunkSize}, or the {@code limit} when there is no {@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, /** Filter Actors by one or more comma-separated category IDs, such as {@code AI_AND_ML}. An Actor must match all of them. */ diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index caa50e3..e60860c 100644 --- a/src/Resource/DatasetClient.php +++ b/src/Resource/DatasetClient.php @@ -195,9 +195,9 @@ 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. + * 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 */ diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index bbb0707..ea38f0a 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -238,9 +238,9 @@ public function getRecordPublicUrl(string $key, int|float|string|null $timeoutSe * 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. + * 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 */ From 07b61880411533aa8c897551de83b688baa4c3ea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:19:02 +0000 Subject: [PATCH 08/20] chore: sync with spec v2-2026-12-03T122505Z --- CHANGELOG.md | 2 +- src/Version.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e1c68c..aa313a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 0.15.0 -- Synced with Apify OpenAPI spec `v2-2026-12-02T102104Z`: the API dropped the Store `allowsAgenticUsers` filter. +- Synced with Apify OpenAPI spec `v2-2026-12-03T122505Z`: the API dropped the Store `allowsAgenticUsers` filter. The latest spec change only fixes error examples. - **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. diff --git a/src/Version.php b/src/Version.php index f84515d..1cd076b 100644 --- a/src/Version.php +++ b/src/Version.php @@ -23,7 +23,7 @@ final class Version * The version of the Apify OpenAPI specification this client was generated and verified * against. Corresponds to the {@code info.version} field of the Apify OpenAPI document. */ - public const API_SPEC_VERSION = 'v2-2026-12-02T102104Z'; + public const API_SPEC_VERSION = 'v2-2026-12-03T122505Z'; private function __construct() { From 1070e309030f20cf1cbac89bbc1454079ab34efd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:34:02 +0000 Subject: [PATCH 09/20] feat: add client-wide headers and streamRecord, address full review --- CHANGELOG.md | 5 +- README.md | 31 +++++-- docs/examples.md | 83 +++++++++++++------ docs/models.md | 10 +++ docs/options.md | 8 +- docs/storages.md | 1 + docs/tasks.md | 2 +- src/ApifyClient.php | 7 +- src/Http/GuzzleHttpClient.php | 7 +- src/Internal/HttpClientCore.php | 26 +++--- src/Internal/ResourceContext.php | 33 +++----- src/Internal/Signatures.php | 12 ++- src/Internal/UrlParts.php | 41 +++++++++ src/Model/KeyValueStoreRecordStream.php | 39 +++++++++ src/Model/StoreSearchResult.php | 10 ++- src/Options/ActorServerRequestOptions.php | 6 +- src/Options/StoreListOptions.php | 5 +- src/Options/StoreSearchOptions.php | 5 +- src/Resource/DatasetClient.php | 4 +- src/Resource/KeyValueStoreClient.php | 23 +++++ src/Resource/StoreCollectionClient.php | 2 +- src/Resource/TaskClient.php | 8 +- tests/Examples/DocSnippetsTest.php | 5 +- tests/Examples/ExampleDocsTest.php | 56 +++++++++++++ tests/Examples/ExamplesTest.php | 32 +++++-- tests/Integration/ActorRunIntegrationTest.php | 12 +++ tests/Integration/BuildIntegrationTest.php | 21 +++++ tests/Integration/IntegrationTestCase.php | 2 +- .../KeyValueStoreIntegrationTest.php | 4 + .../RequestQueueIntegrationTest.php | 7 ++ tests/Unit/ClientHeadersTest.php | 65 +++++++++++++++ tests/Unit/KeyValueStoreStreamRecordTest.php | 68 +++++++++++++++ tests/Unit/MethodTierTest.php | 2 + tests/Unit/TaskPublishUnpublishTest.php | 13 +++ tests/Unit/UrlPartsTest.php | 30 +++++++ 35 files changed, 585 insertions(+), 100 deletions(-) create mode 100644 src/Internal/UrlParts.php create mode 100644 src/Model/KeyValueStoreRecordStream.php create mode 100644 tests/Examples/ExampleDocsTest.php create mode 100644 tests/Unit/ClientHeadersTest.php create mode 100644 tests/Unit/KeyValueStoreStreamRecordTest.php create mode 100644 tests/Unit/UrlPartsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index aa313a4..e3d4f8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,15 @@ ## 0.15.0 -- Synced with Apify OpenAPI spec `v2-2026-12-03T122505Z`: the API dropped the Store `allowsAgenticUsers` filter. The latest spec change only fixes error examples. +- 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()`. +- 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 diff --git a/README.md b/README.md index 543f2fe..c5be683 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. | +| `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: @@ -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/docs/examples.md b/docs/examples.md index 8cb1405..4f12045 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 @@ -40,25 +42,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 +94,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 +107,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 +143,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,10 +156,14 @@ 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. +// Start the run without waiting for it to finish. $run = $client->actor('apify/hello-world')->start(); -$stream = $client->run($run->getId())->getStreamedLog(); + +// 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); } diff --git a/docs/models.md b/docs/models.md index 4ba417e..46eab92 100644 --- a/docs/models.md +++ b/docs/models.md @@ -164,6 +164,14 @@ Returned by `store()->search()`. It can be iterated and counted. It has no `tota | `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 | |---|---| @@ -239,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 3f25711..59a4c6c 100644 --- a/docs/options.md +++ b/docs/options.md @@ -73,7 +73,7 @@ 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()`. The Actors come in Store order, which the API has no option to change. @@ -84,7 +84,7 @@ For `store()->list()` / `store()->iterate()`. The Actors come in Store order, wh | `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. | +| `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). The page size must then be 10 or less, see `limit`. | @@ -99,7 +99,7 @@ For `store()->search()`. The API answers a search with one page, so there is no | `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. | +| `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). | @@ -264,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/storages.md b/docs/storages.md index 4c1d4ee..69a4450 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -60,6 +60,7 @@ 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): ?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. The stream is not retried. 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. diff --git a/docs/tasks.md b/docs/tasks.md index cc4d129..3b2a821 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -24,7 +24,7 @@ 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. diff --git a/src/ApifyClient.php b/src/ApifyClient.php index c09b129..046d22e 100644 --- a/src/ApifyClient.php +++ b/src/ApifyClient.php @@ -103,6 +103,10 @@ 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 */ public function __construct( ?string $token = null, @@ -122,6 +126,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 +151,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); 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..ea64fcf 100644 --- a/src/Internal/HttpClientCore.php +++ b/src/Internal/HttpClientCore.php @@ -57,6 +57,13 @@ 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. + * + * @var array + */ + private array $headers = [], ) { } @@ -107,7 +114,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; @@ -225,7 +232,7 @@ public function stream(string $url): ResponseInterface } /** - * 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 +250,9 @@ private function buildRequest( if ($this->token !== null && $this->token !== '') { $request = $request->withHeader($authorizationHeader, 'Bearer ' . $this->token); } + foreach ($this->headers as $name => $value) { + $request = $request->withHeader($name, $value); + } if ($contentType !== '') { $request = $request->withHeader('Content-Type', $contentType); } @@ -365,18 +375,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/ResourceContext.php b/src/Internal/ResourceContext.php index 8d4c6c3..b6f90f7 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; } @@ -413,6 +413,14 @@ public function headExists(string $subPath, QueryParams $params, ?float $timeout * status is thrown as the matching {@see ApifyApiException}. */ public function streamRaw(string $subPath, QueryParams $params): StreamInterface + { + return $this->streamRawResponse($subPath, $params)->getBody(); + } + + /** + * Like {@see streamRaw()}, but returns the whole response, for its headers. + */ + public function streamRawResponse(string $subPath, QueryParams $params): ResponseInterface { $url = $this->mergedParams($params)->applyToUrl($this->subUrl($subPath)); $response = $this->http->stream($url); @@ -423,10 +431,10 @@ public function streamRaw(string $subPath, QueryParams $params): StreamInterface $body, 1, 'GET', - HttpClientCore::extractPath($url) + UrlParts::pathAndQuery($url) ); } - return $response->getBody(); + return $response; } /** @@ -592,21 +600,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/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 index 970216b..be4cd1c 100644 --- a/src/Model/StoreSearchResult.php +++ b/src/Model/StoreSearchResult.php @@ -21,6 +21,8 @@ final class StoreSearchResult implements IteratorAggregate, Countable { /** + * @internal + * * @param list $items */ public function __construct( @@ -29,8 +31,12 @@ public function __construct( ) { } - /** Builds the result from a decoded Store response page. */ - public static function fromPage(mixed $data): self + /** + * 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()); diff --git a/src/Options/ActorServerRequestOptions.php b/src/Options/ActorServerRequestOptions.php index f54b212..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); diff --git a/src/Options/StoreListOptions.php b/src/Options/StoreListOptions.php index 841c60d..65da6d5 100644 --- a/src/Options/StoreListOptions.php +++ b/src/Options/StoreListOptions.php @@ -29,7 +29,10 @@ public function __construct( 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, /** The response format ({@code full}, {@code agent}). */ public readonly ?string $responseFormat = null, diff --git a/src/Options/StoreSearchOptions.php b/src/Options/StoreSearchOptions.php index ea9fd7c..1ac024f 100644 --- a/src/Options/StoreSearchOptions.php +++ b/src/Options/StoreSearchOptions.php @@ -30,7 +30,10 @@ public function __construct( 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, /** The response format ({@code full}, {@code agent}). */ public readonly ?string $responseFormat = null, diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index e60860c..004a74f 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 */ diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index ea38f0a..c646063 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -4,6 +4,7 @@ namespace Apify\Client\Resource; +use Apify\Client\Exception\ApifyApiException; use Apify\Client\Internal\HttpClientCore; use Apify\Client\Internal\Json; use Apify\Client\Internal\QueryParams; @@ -14,6 +15,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 +171,27 @@ 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. The stream is not retried. 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): ?KeyValueStoreRecordStream + { + $params = new QueryParams(); + ($options ?? new GetRecordOptions())->appendTo($params); + try { + $response = $this->ctx->streamRawResponse('records/' . ResourceContext::encodePathSegment($key), $params); + } catch (ApifyApiException $e) { + if (HttpClientCore::isNotFound($e)) { + return null; + } + throw $e; + } + $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. diff --git a/src/Resource/StoreCollectionClient.php b/src/Resource/StoreCollectionClient.php index 68031b9..b775ee6 100644 --- a/src/Resource/StoreCollectionClient.php +++ b/src/Resource/StoreCollectionClient.php @@ -67,7 +67,7 @@ public function search(StoreSearchOptions $options, int|float|string|null $timeo { $params = new QueryParams(); $options->appendTo($params); - return StoreSearchResult::fromPage( + 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..1d05739 100644 --- a/src/Resource/TaskClient.php +++ b/src/Resource/TaskClient.php @@ -65,9 +65,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 +75,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); } /** diff --git a/tests/Examples/DocSnippetsTest.php b/tests/Examples/DocSnippetsTest.php index 1082d0d..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); } } 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..e28d313 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,29 @@ 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'); + } + + $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/Integration/ActorRunIntegrationTest.php b/tests/Integration/ActorRunIntegrationTest.php index 52a178a..c7a5bd5 100644 --- a/tests/Integration/ActorRunIntegrationTest.php +++ b/tests/Integration/ActorRunIntegrationTest.php @@ -73,6 +73,18 @@ 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); + $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(); diff --git a/tests/Integration/BuildIntegrationTest.php b/tests/Integration/BuildIntegrationTest.php index de10342..f5bc4a6 100644 --- a/tests/Integration/BuildIntegrationTest.php +++ b/tests/Integration/BuildIntegrationTest.php @@ -55,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/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/Unit/ClientHeadersTest.php b/tests/Unit/ClientHeadersTest.php new file mode 100644 index 0000000..42f4751 --- /dev/null +++ b/tests/Unit/ClientHeadersTest.php @@ -0,0 +1,65 @@ + $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 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/KeyValueStoreStreamRecordTest.php b/tests/Unit/KeyValueStoreStreamRecordTest.php new file mode 100644 index 0000000..7ed0fb1 --- /dev/null +++ b/tests/Unit/KeyValueStoreStreamRecordTest.php @@ -0,0 +1,68 @@ +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 testStreamRecordThrowsOtherErrorsWithoutRetrying(): void + { + $transport = (new MockTransport()) + ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])); + + try { + $this->client($transport)->keyValueStore('s1')->streamRecord('k'); + self::fail('expected ApifyApiException'); + } catch (ApifyApiException $e) { + self::assertSame(500, $e->getStatusCode()); + self::assertSame(1, $transport->callCount()); + } + } +} diff --git a/tests/Unit/MethodTierTest.php b/tests/Unit/MethodTierTest.php index f9313f1..b085087 100644 --- a/tests/Unit/MethodTierTest.php +++ b/tests/Unit/MethodTierTest.php @@ -50,6 +50,8 @@ public static function tierCases(): iterable 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/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/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)); + } +} From d2d8c42240d3012614f4d87967c1e2dfbb867460 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:45:53 +0000 Subject: [PATCH 10/20] fix: retry opening streams, keep a client-wide Authorization header from Actor servers, honor APIFY_API_URL in the docs program streamRecord(), streamItems() and log()->stream() now open the stream through the retrying call path and take timeoutSecs. A client-wide Authorization header is sent as X-Apify-Authorization to an Actor server. The standalone docs program reads APIFY_API_URL. --- CHANGELOG.md | 2 ++ README.md | 2 +- docs/examples.md | 6 +++- docs/misc.md | 2 +- docs/storages.md | 4 +-- src/Internal/HttpClientCore.php | 12 +++---- src/Internal/ResourceContext.php | 30 +++++++--------- src/Resource/DatasetClient.php | 7 ++-- src/Resource/KeyValueStoreClient.php | 13 ++++--- src/Resource/LogClient.php | 9 +++-- tests/Examples/ExamplesTest.php | 3 ++ tests/Unit/ClientHeadersTest.php | 23 +++++++++++++ tests/Unit/DatasetStreamItemsTest.php | 24 ++++++++----- tests/Unit/KeyValueStoreStreamRecordTest.php | 36 ++++++++++++++++---- tests/Unit/MethodTierTest.php | 4 +++ 15 files changed, 123 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3d4f8d..62e003d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ - 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. +- 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()`. diff --git a/README.md b/README.md index c5be683..cb80d6c 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ $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. | -| `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. | +| `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. | diff --git a/docs/examples.md b/docs/examples.md index 4f12045..0a913b4 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -24,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. diff --git a/docs/misc.md b/docs/misc.md index 47ac5a6..123853a 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -40,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. Opening the stream is retried like any request, and a failure while the log is being read is not. ```php $log = $client->log('RUN_OR_BUILD_ID')->get(new LogOptions(raw: true)); diff --git a/docs/storages.md b/docs/storages.md index 69a4450..2faf2d7 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -20,7 +20,7 @@ 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): 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. It takes a trailing `$timeoutSecs`. - `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. 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). @@ -60,7 +60,7 @@ 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): ?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. The stream is not retried. Close it when you stop reading. +- `streamRecord(string $key, ?GetRecordOptions $options = 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. It takes a trailing `$timeoutSecs`. 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. diff --git a/src/Internal/HttpClientCore.php b/src/Internal/HttpClientCore.php index ea64fcf..af9deff 100644 --- a/src/Internal/HttpClientCore.php +++ b/src/Internal/HttpClientCore.php @@ -224,13 +224,6 @@ 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, client-wide headers, content type, and extra headers. * @@ -251,7 +244,10 @@ private function buildRequest( $request = $request->withHeader($authorizationHeader, 'Bearer ' . $this->token); } foreach ($this->headers as $name => $value) { - $request = $request->withHeader($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); diff --git a/src/Internal/ResourceContext.php b/src/Internal/ResourceContext.php index b6f90f7..c24c6c5 100644 --- a/src/Internal/ResourceContext.php +++ b/src/Internal/ResourceContext.php @@ -409,32 +409,28 @@ 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 = null): StreamInterface { - return $this->streamRawResponse($subPath, $params)->getBody(); + return $this->streamRawResponse($subPath, $params, $timeoutSecs)->getBody(); } /** * Like {@see streamRaw()}, but returns the whole response, for its headers. */ - public function streamRawResponse(string $subPath, QueryParams $params): ResponseInterface + public function streamRawResponse(string $subPath, QueryParams $params, ?float $timeoutSecs = null): ResponseInterface { $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', - UrlParts::pathAndQuery($url) - ); - } - return $response; + return $this->http->call( + 'GET', + $url, + timeoutSecs: $this->effectiveTimeout($timeoutSecs), + policy: new RequestPolicy(stream: true) + ); } /** diff --git a/src/Resource/DatasetClient.php b/src/Resource/DatasetClient.php index 004a74f..1f98d25 100644 --- a/src/Resource/DatasetClient.php +++ b/src/Resource/DatasetClient.php @@ -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)); } /** diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index c646063..1be8594 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -173,15 +173,20 @@ public function getRecord(string $key, ?GetRecordOptions $options = null, int|fl /** * Opens a record as a stream, so a large record can be read in chunks, or returns {@code null} if it does not - * exist. The stream is not retried. This is a separate method from {@see getRecord()}, since a PHP method - * cannot change its return type with an option. + * 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): ?KeyValueStoreRecordStream + public function streamRecord(string $key, ?GetRecordOptions $options = null, int|float|string|null $timeoutSecs = null): ?KeyValueStoreRecordStream { $params = new QueryParams(); ($options ?? new GetRecordOptions())->appendTo($params); try { - $response = $this->ctx->streamRawResponse('records/' . ResourceContext::encodePathSegment($key), $params); + $response = $this->ctx->streamRawResponse( + 'records/' . ResourceContext::encodePathSegment($key), + $params, + $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG) + ); } catch (ApifyApiException $e) { if (HttpClientCore::isNotFound($e)) { return null; diff --git a/src/Resource/LogClient.php b/src/Resource/LogClient.php index 171c6e6..93494c6 100644 --- a/src/Resource/LogClient.php +++ b/src/Resource/LogClient.php @@ -52,12 +52,15 @@ 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. 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->streamRaw('', $params, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG)); } } diff --git a/tests/Examples/ExamplesTest.php b/tests/Examples/ExamplesTest.php index e28d313..8520a43 100644 --- a/tests/Examples/ExamplesTest.php +++ b/tests/Examples/ExamplesTest.php @@ -71,6 +71,9 @@ public function testStandaloneProgramRuns(): void 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 { diff --git a/tests/Unit/ClientHeadersTest.php b/tests/Unit/ClientHeadersTest.php index 42f4751..9049678 100644 --- a/tests/Unit/ClientHeadersTest.php +++ b/tests/Unit/ClientHeadersTest.php @@ -55,6 +55,29 @@ public function testHeaderOfASingleCallWinsOverTheClientHeaders(): void 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":{}}'); diff --git a/tests/Unit/DatasetStreamItemsTest.php b/tests/Unit/DatasetStreamItemsTest.php index 440f228..a55670c 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,27 @@ public function testStreamItemsRequestsSameUrlAsDownloadItems(): void self::assertStringContainsString('bom=1', $uri); } - public function testStreamItemsUsesStreamingTransportNotRetrying(): void + public function testStreamItemsRetriesOpeningTheStreamThenThrowsTheError(): void { - // A server error on a streamed request must surface immediately (streaming bypasses retries), - // unlike the buffered downloadItems()/get() calls, which retry 5xx responses. + $body = Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']]); $transport = (new MockTransport()) - ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])); + ->queueResponse(500, $body) + ->queueResponse(200, '[]') + ->queueResponse(500, $body) + ->queueResponse(500, $body) + ->queueResponse(500, $body); + + $stream = $this->client($transport)->dataset('ds1')->streamItems(DownloadItemsFormat::JSON); + self::assertSame('[]', (string) $stream); + self::assertSame(2, $transport->callCount()); + self::assertSame([true, true], $transport->streamed); 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(5, $transport->callCount()); } } } diff --git a/tests/Unit/KeyValueStoreStreamRecordTest.php b/tests/Unit/KeyValueStoreStreamRecordTest.php index 7ed0fb1..89fff85 100644 --- a/tests/Unit/KeyValueStoreStreamRecordTest.php +++ b/tests/Unit/KeyValueStoreStreamRecordTest.php @@ -13,9 +13,9 @@ /** Tests of {@see \Apify\Client\Resource\KeyValueStoreClient::streamRecord()}. */ final class KeyValueStoreStreamRecordTest 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 testStreamRecordReturnsTheBytesAndContentType(): void @@ -52,17 +52,41 @@ public function testStreamRecordOfMissingRecordReturnsNull(): void self::assertNull($this->client($transport)->keyValueStore('s1')->streamRecord('missing')); } - public function testStreamRecordThrowsOtherErrorsWithoutRetrying(): void + public function testStreamRecordRetriesOpeningTheStreamOnAServerError(): void { $transport = (new MockTransport()) - ->queueResponse(500, Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']])); + ->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)->keyValueStore('s1')->streamRecord('k'); + $this->client($transport, 2)->keyValueStore('s1')->streamRecord('k'); self::fail('expected ApifyApiException'); } catch (ApifyApiException $e) { self::assertSame(500, $e->getStatusCode()); - self::assertSame(1, $transport->callCount()); + 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, 7); + + self::assertSame([7.0], $transport->timeouts); + } } diff --git a/tests/Unit/MethodTierTest.php b/tests/Unit/MethodTierTest.php index b085087..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; @@ -45,6 +46,9 @@ 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]; From ec827630a29e5b114c54d05f513b868941d759dc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:47:22 +0000 Subject: [PATCH 11/20] test: use a timeout below the client cap in the streamRecord timeout test --- tests/Unit/KeyValueStoreStreamRecordTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Unit/KeyValueStoreStreamRecordTest.php b/tests/Unit/KeyValueStoreStreamRecordTest.php index 89fff85..d4feea7 100644 --- a/tests/Unit/KeyValueStoreStreamRecordTest.php +++ b/tests/Unit/KeyValueStoreStreamRecordTest.php @@ -85,8 +85,8 @@ public function testStreamRecordThrowsTheErrorOnceTheRetriesRunOut(): void public function testStreamRecordTakesTheTimeoutOfTheCall(): void { $transport = (new MockTransport())->queueResponse(200, 'x'); - $this->client($transport)->keyValueStore('s1')->streamRecord('k', null, 7); + $this->client($transport)->keyValueStore('s1')->streamRecord('k', null, 3); - self::assertSame([7.0], $transport->timeouts); + self::assertSame([3.0], $transport->timeouts); } } From b007bb856afddac941573d23ab3343ac6e9dec04 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:04:42 +0000 Subject: [PATCH 12/20] feat: redirect the run log in call() of an Actor and a task, return null for a missing log stream call() redirects the log of the run by default, to a callable, the standard error stream, or nowhere. run()->redirectLog() is the reusable helper. A cut stream is reopened and resumes after the last message. log()->stream() returns null on a 404 for a client with an ID, and getStreamedLog() takes timeoutSecs. Documents the timeout arguments and the Authorization header rerouting. --- CHANGELOG.md | 3 + README.md | 2 +- docs/actors.md | 2 +- docs/examples.md | 19 +- docs/misc.md | 2 +- docs/runs.md | 4 +- docs/storages.md | 4 +- docs/tasks.md | 2 +- src/ApifyClient.php | 5 +- src/Internal/HttpClientCore.php | 3 +- src/Internal/LogRedirection.php | 41 +++ src/Internal/ResourceContext.php | 21 +- src/Internal/StderrLogSink.php | 50 +++ src/Internal/StreamedLog.php | 278 +++++++++++++++ src/Resource/ActorClient.php | 18 +- src/Resource/LogClient.php | 11 +- src/Resource/RunClient.php | 54 ++- src/Resource/TaskClient.php | 18 +- tests/Examples/LogRedirection.php | 19 +- tests/Integration/ActorRunIntegrationTest.php | 37 +- tests/Integration/TaskIntegrationTest.php | 2 +- tests/Unit/DatasetStreamItemsTest.php | 19 +- tests/Unit/LogClientTest.php | 26 ++ tests/Unit/LogRedirectionTest.php | 328 ++++++++++++++++++ tests/Unit/TimeoutTiersTest.php | 4 +- 25 files changed, 907 insertions(+), 65 deletions(-) create mode 100644 src/Internal/LogRedirection.php create mode 100644 src/Internal/StderrLogSink.php create mode 100644 src/Internal/StreamedLog.php create mode 100644 tests/Unit/LogRedirectionTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 62e003d..5a9245a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ - 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 log of the run to the standard error stream by default, behind `{Actor name} runId:{run ID} -> `, as the reference client does. The new `$log` argument takes a callable that receives each message, or `false` to turn it off. A failure to redirect prints a warning and the call waits without the redirection. A stream that is cut off is reopened and the redirection resumes after the last message. +- Added `run()->redirectLog()`, the redirection that `call()` uses, with a `$since` argument. `run()->getStreamedLog()` takes `$timeoutSecs`. +- **Breaking:** `log()->stream()` returns `null` if the log does not exist, for a client with an ID. A client without an ID still throws on a 404. - 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()`. diff --git a/README.md b/README.md index cb80d6c..ecdab74 100644 --- a/README.md +++ b/README.md @@ -88,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 diff --git a/docs/actors.md b/docs/actors.md index 93182a2..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 diff --git a/docs/examples.md b/docs/examples.md index 0a913b4..43cf708 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -160,15 +160,12 @@ foreach ($client->store()->iterate(new StoreListOptions(), 10) as $item) { ## Run an Actor with log redirection ```php -// Start the run without waiting for it to finish. -$run = $client->actor('apify/hello-world')->start(); - -// 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); -} +// 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 123853a..dbe554d 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -40,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, int|float|string|null $timeoutSecs = null): StreamInterface`: a live stream of the log. Opening the stream is retried like any request, and a failure while the log is being read is not. +- `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/runs.md b/docs/runs.md index f767e34..410519d 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 after the last message. `$timeoutSecs` is the timeout of the requests that fetch the run and its Actor. ```php $run = $client->run('RUN_ID')->waitForFinish(120); diff --git a/docs/storages.md b/docs/storages.md index 2faf2d7..c46b29d 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -20,7 +20,7 @@ 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. Opening the stream is retried like any request, and a failure while the body is being read is not. It takes a trailing `$timeoutSecs`. +- `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. 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). @@ -60,7 +60,7 @@ 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): ?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. It takes a trailing `$timeoutSecs`. Close it when you stop reading. +- `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. diff --git a/docs/tasks.md b/docs/tasks.md index 3b2a821..ef69ab5 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -30,7 +30,7 @@ foreach ($client->tasks()->iterate(new ListOptions(), 50) as $t) { 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/src/ApifyClient.php b/src/ApifyClient.php index 046d22e..8ee3261 100644 --- a/src/ApifyClient.php +++ b/src/ApifyClient.php @@ -106,7 +106,10 @@ final class ApifyClient * @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 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, diff --git a/src/Internal/HttpClientCore.php b/src/Internal/HttpClientCore.php index af9deff..345fd87 100644 --- a/src/Internal/HttpClientCore.php +++ b/src/Internal/HttpClientCore.php @@ -59,7 +59,8 @@ public function __construct( 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. + * 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 */ 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 c24c6c5..6a9b60a 100644 --- a/src/Internal/ResourceContext.php +++ b/src/Internal/ResourceContext.php @@ -414,21 +414,36 @@ public function headExists(string $subPath, QueryParams $params, ?float $timeout * 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, ?float $timeoutSecs = null): StreamInterface + public function streamRaw(string $subPath, QueryParams $params, float $timeoutSecs): StreamInterface { 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 + { + try { + return $this->streamRaw($subPath, $params, $timeoutSecs); + } catch (ApifyApiException $e) { + if (HttpClientCore::isNotFound($e) && $this->swallowsNotFound($subPath)) { + return null; + } + throw $e; + } + } + /** * Like {@see streamRaw()}, but returns the whole response, for its headers. */ - public function streamRawResponse(string $subPath, QueryParams $params, ?float $timeoutSecs = null): ResponseInterface + 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: $this->effectiveTimeout($timeoutSecs), + timeoutSecs: $timeoutSecs, policy: new RequestPolicy(stream: true) ); } 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/StreamedLog.php b/src/Internal/StreamedLog.php new file mode 100644 index 0000000..0d9e1cf --- /dev/null +++ b/src/Internal/StreamedLog.php @@ -0,0 +1,278 @@ +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 before it carried data + * @param float|null $deadline a {@code microtime(true)} value at which to stop, {@code null} for none + * + * @throws ApifyClientException if a reopened stream breaks off again before it reaches the last redirected message + */ + public function redirect(callable $runFinished, ?float $deadline = null): void + { + $emptyRetryMillis = self::EMPTY_STREAM_RETRY_MILLIS; + while (!self::passed($deadline)) { + $stream = $this->logClient->stream(new LogOptions(raw: true)); + if ($stream === null) { + return; + } + $outcome = $this->redirectStream($stream, $deadline); + 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. + * + * @return self::OUTCOME_* + */ + private function redirectStream(StreamInterface $stream, ?float $deadline): string + { + // A chunk may end in the middle of a line. The incomplete rest waits here for the next chunk. + $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) { + return $this->handleBrokenRead($stream, $e); + } + if ($chunk === '') { + usleep(self::EMPTY_READ_PAUSE_MICROS); + continue; + } + $this->receivedData = true; + $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->redirectMessages(substr($text, 0, $lastNewline)); + } + + // Maybe it is incomplete, maybe it is the last message without an end of line. + $this->redirectMessages($remainder); + $stream->close(); + return $outcome; + } + + /** + * Handles a stream that failed while it was read. A stream that failed before it delivered anything is not + * reopened, since the failure is not a cut. Otherwise the stream is reopened, which replays the log, so the + * unfinished line is dropped and the messages redirected so far are skipped. + * + * @return self::OUTCOME_* + * + * @throws RuntimeException if the stream is not to be reopened + */ + private function handleBrokenRead(StreamInterface $stream, RuntimeException $error): string + { + if (!$this->receivedData) { + throw $error; + } + if (!$this->replayCaughtUp()) { + throw new ApifyClientException( + 'Log redirection stopped: the reopened log stream broke off again before it reached the last redirected message.', + 0, + $error + ); + } + $this->replayedUntil = $this->lastRedirectedAt; + $this->replaySkipCount = $this->redirectedAtLastTimestamp; + $stream->close(); + return self::OUTCOME_BROKE_OFF; + } + + /** Whether the current stream got at least as far as the stream before it. */ + private function replayCaughtUp(): bool + { + return $this->replayedUntil === null || $this->replaySkipCount === 0; + } + + /** Whether a message of a reopened stream was redirected before the stream was reopened. */ + private function isReplayed(string $timestamp): bool + { + if ($this->replayedUntil === null) { + return false; + } + if ($timestamp < $this->replayedUntil) { + return true; + } + if ($timestamp === $this->replayedUntil && $this->replaySkipCount > 0) { + $this->replaySkipCount--; + return true; + } + $this->replayedUntil = null; + return false; + } + + private function rememberRedirected(string $timestamp): void + { + if ($timestamp === $this->lastRedirectedAt) { + $this->redirectedAtLastTimestamp++; + } else { + $this->lastRedirectedAt = $timestamp; + $this->redirectedAtLastTimestamp = 1; + } + } + + /** 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->replayedUntil === null) { + ($this->sink)($leading); + } + + for ($i = 0; $i + 1 < count($parts); $i += 2) { + $timestamp = $parts[$i]; + if ($this->isReplayed($timestamp) || ($this->since !== null && $timestamp < $this->since)) { + continue; + } + // The original log level is not available, so every message is redirected as it is. + ($this->sink)(trim($timestamp . $parts[$i + 1])); + $this->rememberRedirected($timestamp); + } + } + + 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/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/LogClient.php b/src/Resource/LogClient.php index 93494c6..21377b3 100644 --- a/src/Resource/LogClient.php +++ b/src/Resource/LogClient.php @@ -53,14 +53,17 @@ public function get(?LogOptions $options = null, int|float|string|null $timeoutS } /** - * Opens a stream of the log, to follow it while the run produces it. Opening the stream is retried like any - * request, but a failure while the log is being read is not. + * 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 + 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, $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG)); + 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..0e08dc0 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 after the last + * redirected message. 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/TaskClient.php b/src/Resource/TaskClient.php index 1d05739..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; @@ -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/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 c7a5bd5..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()); @@ -76,7 +99,7 @@ public function testRunActorAndReadOutputs(): void public function testUpdateRunStatusMessage(): 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()); $updated = $runClient->update(['statusMessage' => 'Updated by the PHP client test', 'isStatusMessageTerminal' => true]); @@ -88,7 +111,7 @@ public function testUpdateRunStatusMessage(): void 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(); @@ -112,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()); @@ -303,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); @@ -316,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/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/Unit/DatasetStreamItemsTest.php b/tests/Unit/DatasetStreamItemsTest.php index a55670c..87dc268 100644 --- a/tests/Unit/DatasetStreamItemsTest.php +++ b/tests/Unit/DatasetStreamItemsTest.php @@ -34,27 +34,30 @@ public function testStreamItemsRequestsSameUrlAsDownloadItems(): void self::assertStringContainsString('bom=1', $uri); } - public function testStreamItemsRetriesOpeningTheStreamThenThrowsTheError(): void + public function testStreamItemsRetriesOpeningTheStreamOnAServerError(): void { - $body = Json::encode(['error' => ['type' => 'internal-error', 'message' => 'boom']]); $transport = (new MockTransport()) - ->queueResponse(500, $body) - ->queueResponse(200, '[]') - ->queueResponse(500, $body) - ->queueResponse(500, $body) - ->queueResponse(500, $body); + ->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, 2)->dataset('ds1')->streamItems(DownloadItemsFormat::JSON); self::fail('expected ApifyApiException'); } catch (ApifyApiException $e) { self::assertSame(500, $e->getStatusCode()); - self::assertSame(5, $transport->callCount()); + self::assertSame(3, $transport->callCount()); } } } 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..34cc760 --- /dev/null +++ b/tests/Unit/LogRedirectionTest.php @@ -0,0 +1,328 @@ + ['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')); + $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('/acts/a1/runs', explode('?', $paths[0])[0]); + self::assertSame('/actor-runs/r1/log?stream=1&raw=1', $paths[1]); + self::assertStringStartsWith('/actor-runs/r1?waitForFinish=', $paths[2]); + self::assertCount(3, $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')); + $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('/acts/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"); + $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], $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"); + $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(2, $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('broke off again'); + $this->client($transport)->run('r1')->redirectLog($sink); + } + + public function testSinceSkipsOlderMessages(): void + { + $transport = (new MockTransport())->queueResponse(200, self::LOG); + $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))); + $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))); + $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 or fails with the given error. */ +final class ScriptedStream implements StreamInterface +{ + /** @param list $chunks */ + public function __construct(private array $chunks, private ?Throwable $thenFail = null) + { + } + + 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->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->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; + } +} 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); } From d39c7ff44b4ef6001b7936cea5e2b51056dd3422 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:06:04 +0000 Subject: [PATCH 13/20] test: fix the Actor path and quote style in the log redirection tests --- tests/Unit/LogRedirectionTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php index 34cc760..f24c4c3 100644 --- a/tests/Unit/LogRedirectionTest.php +++ b/tests/Unit/LogRedirectionTest.php @@ -57,7 +57,7 @@ public function testCallRedirectsTheLogOfTheRunToTheGivenTarget(): void '2024-05-01T10:00:02.000Z bye', ], $sink->messages); $paths = self::paths($transport); - self::assertSame('/acts/a1/runs', explode('?', $paths[0])[0]); + self::assertSame('/actors/a1/runs', explode('?', $paths[0])[0]); self::assertSame('/actor-runs/r1/log?stream=1&raw=1', $paths[1]); self::assertStringStartsWith('/actor-runs/r1?waitForFinish=', $paths[2]); self::assertCount(3, $paths); @@ -104,7 +104,7 @@ public function testTheDefaultTargetNeedsTheRunAndTheActorForThePrefix(): void self::assertSame('SUCCEEDED', $run->getStatus()); $paths = self::paths($transport); self::assertSame('/actor-runs/r1', $paths[1]); - self::assertSame('/acts/a1', $paths[2]); + 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]); @@ -194,7 +194,7 @@ public function testALineWithoutATimestampInALaterChunkIsRedirectedAsItIs(): voi public function testAMessageThatEndsInTheMiddleOfAChunkIsJoinedWithItsRest(): void { - $chunks = ["2024-05-01T10:00:00.000Z fir", "st\n2024-05-01T10:00:01.000Z second"]; + $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))); $sink = new MessageCollector(); From b16d55c7bf8da963642f8c8994dfffd623368c24 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:07:24 +0000 Subject: [PATCH 14/20] fix: narrow the return type of the broken read handler for PHPStan --- src/Internal/StreamedLog.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 0d9e1cf..c197560 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -181,7 +181,7 @@ private function redirectStream(StreamInterface $stream, ?float $deadline): stri * reopened, since the failure is not a cut. Otherwise the stream is reopened, which replays the log, so the * unfinished line is dropped and the messages redirected so far are skipped. * - * @return self::OUTCOME_* + * @return self::OUTCOME_BROKE_OFF * * @throws RuntimeException if the stream is not to be reopened */ From bd233dcfc12ba21117dbc2741ec5260285cf4d96 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:24:44 +0000 Subject: [PATCH 15/20] fix: bound the log redirection by waitSecs, reopen a stream closed early, skip the continuation of a skipped message The log stream opens with the time left until the deadline as its timeout, and a read that fails after the deadline ends the redirection. A stream that ends cleanly while the run has not finished is reopened. The lines that continue a message left out by since are left out too. The default target is tested in a PHP process. --- CHANGELOG.md | 6 +- docs/runs.md | 2 +- src/Internal/ResourceContext.php | 10 +- src/Internal/StreamedLog.php | 49 ++++-- src/Resource/KeyValueStoreClient.php | 19 +-- tests/Unit/LogRedirectionTest.php | 217 +++++++++++++++++++++++++-- 6 files changed, 261 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a9245a..68f3f0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,9 @@ - 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 log of the run to the standard error stream by default, behind `{Actor name} runId:{run ID} -> `, as the reference client does. The new `$log` argument takes a callable that receives each message, or `false` to turn it off. A failure to redirect prints a warning and the call waits without the redirection. A stream that is cut off is reopened and the redirection resumes after the last message. -- Added `run()->redirectLog()`, the redirection that `call()` uses, with a `$since` argument. `run()->getStreamedLog()` takes `$timeoutSecs`. -- **Breaking:** `log()->stream()` returns `null` if the log does not exist, for a client with an ID. A client without an ID still throws on a 404. +- `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()`. diff --git a/docs/runs.md b/docs/runs.md index 410519d..e73216a 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -32,7 +32,7 @@ An Actor's or task's runs are available at `$client->actor($id)->runs()` / `$cli - `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`: `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 after the last message. `$timeoutSecs` is the timeout of the requests that fetch the run and its Actor. +- `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 after the last message. `$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 last message. A stream that fails before it delivered anything throws its error. ```php $run = $client->run('RUN_ID')->waitForFinish(120); diff --git a/src/Internal/ResourceContext.php b/src/Internal/ResourceContext.php index 6a9b60a..ea7338b 100644 --- a/src/Internal/ResourceContext.php +++ b/src/Internal/ResourceContext.php @@ -423,9 +423,17 @@ public function streamRaw(string $subPath, QueryParams $params, float $timeoutSe * 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->streamRaw($subPath, $params, $timeoutSecs); + return $this->streamRawResponse($subPath, $params, $timeoutSecs); } catch (ApifyApiException $e) { if (HttpClientCore::isNotFound($e) && $this->swallowsNotFound($subPath)) { return null; diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index c197560..4362383 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -76,6 +76,9 @@ final class StreamedLog private ?string $replayedUntil = null; private int $replaySkipCount = 0; + /** Whether the last message was left out, so the lines that continue it are left out too. */ + private bool $lastMessageSkipped = false; + /** * @param callable(string): void $sink receives each message * @param DateTimeInterface|null $since redirect only the messages logged at this time or later @@ -100,11 +103,12 @@ public function redirect(callable $runFinished, ?float $deadline = null): void { $emptyRetryMillis = self::EMPTY_STREAM_RETRY_MILLIS; while (!self::passed($deadline)) { - $stream = $this->logClient->stream(new LogOptions(raw: true)); + // 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), $deadline === null ? null : $deadline - microtime(true)); if ($stream === null) { return; } - $outcome = $this->redirectStream($stream, $deadline); + $outcome = $this->redirectStream($stream, $deadline, $runFinished); if ($outcome === self::OUTCOME_DEADLINE) { return; } @@ -135,11 +139,14 @@ private function redirectWholeLog(): void } /** - * Redirects one stream until it ends, breaks off, or the deadline passes. + * 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): string + private function redirectStream(StreamInterface $stream, ?float $deadline, callable $runFinished): string { // A chunk may end in the middle of a line. The incomplete rest waits here for the next chunk. $remainder = ''; @@ -152,7 +159,16 @@ private function redirectStream(StreamInterface $stream, ?float $deadline): stri try { $chunk = $stream->read(self::READ_CHUNK_BYTES); } catch (RuntimeException $e) { - return $this->handleBrokenRead($stream, $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, $e); } if ($chunk === '') { usleep(self::EMPTY_READ_PAUSE_MICROS); @@ -170,6 +186,10 @@ private function redirectStream(StreamInterface $stream, ?float $deadline): stri $this->redirectMessages(substr($text, 0, $lastNewline)); } + if ($outcome === self::OUTCOME_ENDED && $this->receivedData && !$runFinished()) { + return $this->reopenAfterCut($stream, null); + } + // Maybe it is incomplete, maybe it is the last message without an end of line. $this->redirectMessages($remainder); $stream->close(); @@ -177,24 +197,20 @@ private function redirectStream(StreamInterface $stream, ?float $deadline): stri } /** - * Handles a stream that failed while it was read. A stream that failed before it delivered anything is not - * reopened, since the failure is not a cut. Otherwise the stream is reopened, which replays the log, so the - * unfinished line is dropped and the messages redirected so far are skipped. + * Prepares the reopening of a stream that was cut. The reopened stream replays the log, so the unfinished line is + * dropped and the messages redirected so far are skipped. * * @return self::OUTCOME_BROKE_OFF * - * @throws RuntimeException if the stream is not to be reopened + * @throws ApifyClientException if the stream is a reopened one that was cut before it got as far as the one before */ - private function handleBrokenRead(StreamInterface $stream, RuntimeException $error): string + private function reopenAfterCut(StreamInterface $stream, ?RuntimeException $cause): string { - if (!$this->receivedData) { - throw $error; - } if (!$this->replayCaughtUp()) { throw new ApifyClientException( 'Log redirection stopped: the reopened log stream broke off again before it reached the last redirected message.', 0, - $error + $cause ); } $this->replayedUntil = $this->lastRedirectedAt; @@ -245,13 +261,14 @@ private function redirectMessages(string $text): void } // Text before the first timestamp continues a message that an earlier chunk started. $leading = trim((string) array_shift($parts)); - if ($leading !== '' && $this->replayedUntil === null) { + if ($leading !== '' && !$this->lastMessageSkipped) { ($this->sink)($leading); } for ($i = 0; $i + 1 < count($parts); $i += 2) { $timestamp = $parts[$i]; - if ($this->isReplayed($timestamp) || ($this->since !== null && $timestamp < $this->since)) { + $this->lastMessageSkipped = $this->isReplayed($timestamp) || ($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. diff --git a/src/Resource/KeyValueStoreClient.php b/src/Resource/KeyValueStoreClient.php index 1be8594..77faaf5 100644 --- a/src/Resource/KeyValueStoreClient.php +++ b/src/Resource/KeyValueStoreClient.php @@ -4,7 +4,6 @@ namespace Apify\Client\Resource; -use Apify\Client\Exception\ApifyApiException; use Apify\Client\Internal\HttpClientCore; use Apify\Client\Internal\Json; use Apify\Client\Internal\QueryParams; @@ -181,17 +180,13 @@ public function streamRecord(string $key, ?GetRecordOptions $options = null, int { $params = new QueryParams(); ($options ?? new GetRecordOptions())->appendTo($params); - try { - $response = $this->ctx->streamRawResponse( - 'records/' . ResourceContext::encodePathSegment($key), - $params, - $this->ctx->resolveTimeout($timeoutSecs, TimeoutTiers::TIER_LONG) - ); - } catch (ApifyApiException $e) { - if (HttpClientCore::isNotFound($e)) { - return null; - } - throw $e; + $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); diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php index f24c4c3..a2748cb 100644 --- a/tests/Unit/LogRedirectionTest.php +++ b/tests/Unit/LogRedirectionTest.php @@ -45,6 +45,7 @@ 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(); @@ -59,8 +60,10 @@ public function testCallRedirectsTheLogOfTheRunToTheGivenTarget(): void $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]); - self::assertStringStartsWith('/actor-runs/r1?waitForFinish=', $paths[2]); - self::assertCount(3, $paths); + // 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 @@ -68,6 +71,7 @@ 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(); @@ -130,13 +134,14 @@ 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, "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], $transport->streamed); + self::assertSame([true, false, true, false], $transport->streamed); } public function testACutStreamIsReopenedAndResumesAfterTheLastRedirectedMessage(): void @@ -144,7 +149,8 @@ public function testACutStreamIsReopenedAndResumesAfterTheLastRedirectedMessage( $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, $log . "2024-05-01T10:00:02.000Z d\n") + ->queueResponse(200, self::runBody('SUCCEEDED')); $sink = new MessageCollector(); $this->client($transport)->run('r1')->redirectLog($sink); @@ -155,7 +161,7 @@ public function testACutStreamIsReopenedAndResumesAfterTheLastRedirectedMessage( '2024-05-01T10:00:01.000Z c', '2024-05-01T10:00:02.000Z d', ], $sink->messages); - self::assertCount(2, $transport->received); + self::assertCount(3, $transport->received); } public function testAStreamThatBreaksOffAgainBeforeCatchingUpStopsTheRedirection(): void @@ -171,9 +177,112 @@ public function testAStreamThatBreaksOffAgainBeforeCatchingUpStopsTheRedirection $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 SilentStream(100_000))); + $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 SilentStream(1_200_000, new RuntimeException('read timed out')))); + $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 SilentStream(100_000))) + ->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 testSinceSkipsOlderMessages(): void { - $transport = (new MockTransport())->queueResponse(200, self::LOG); + $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')); @@ -184,7 +293,9 @@ public function testSinceSkipsOlderMessages(): void 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))); + $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); @@ -195,7 +306,9 @@ public function testALineWithoutATimestampInALaterChunkIsRedirectedAsItIs(): voi 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))); + $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); @@ -326,3 +439,89 @@ public function getMetadata(?string $key = null) return $key === null ? [] : null; } } + +/** A readable stream that has nothing to deliver: each read waits, then returns nothing or fails. */ +final class SilentStream implements StreamInterface +{ + public function __construct(private int $waitMicros, private ?Throwable $thenFail = null) + { + } + + public function __toString(): string + { + return ''; + } + + public function close(): void + { + } + + public function detach() + { + return null; + } + + public function getSize(): ?int + { + return null; + } + + public function tell(): int + { + return 0; + } + + public function eof(): bool + { + return false; + } + + 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 + { + usleep($this->waitMicros); + if ($this->thenFail !== null) { + throw $this->thenFail; + } + return ''; + } + + public function getContents(): string + { + return ''; + } + + public function getMetadata(?string $key = null) + { + return $key === null ? [] : null; + } +} From 56a99aa23bd95f27c2c0f6a283178c764fd27c98 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:26:10 +0000 Subject: [PATCH 16/20] fix: mark the deadline check as time dependent for PHPStan --- src/Internal/StreamedLog.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 4362383..47dff65 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -277,6 +277,11 @@ private function redirectMessages(string $text): void } } + /** + * 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; From f4603af67175267d19cd9f91ded1b7905a9d6303 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:39:28 +0000 Subject: [PATCH 17/20] fix: skip untimestamped lines of a replayed stream, do not open a stream with too little time left, tidy comments and tests A reopened stream no longer redirects its lines without a timestamp a second time. A log stream is opened only with at least half a second left, and a request that fails after the deadline ends the redirection quietly. --- src/Internal/StreamedLog.php | 36 ++++-- tests/Unit/LogRedirectionTest.php | 178 ++++++++++++++++-------------- 2 files changed, 124 insertions(+), 90 deletions(-) diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 47dff65..398e3b3 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -10,6 +10,7 @@ use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; +use Exception; use Psr\Http\Message\StreamInterface; use RuntimeException; @@ -22,8 +23,9 @@ * The API serves the log of a run that has not logged anything yet as an empty stream that ends at once, so the * stream is reopened until the first bytes arrive. A stream that broke off after it had delivered data is reopened * too. The API cannot continue a log stream from a given point, so the reopened stream replays the log from its start, - * and the messages that were redirected already are skipped. A stream that ends without an error after delivering - * data carried the whole log of a finished run. + * and the messages that were redirected already are skipped. A stream that ends after delivering data while the run + * has not finished was cut as well, whether or not the transport reports an error, so it is reopened. A stream that + * ends after the run has finished carried the whole log. * * @internal */ @@ -53,6 +55,12 @@ final class StreamedLog private const READ_CHUNK_BYTES = 8192; + /** + * The least time left for which a stream is opened. A request with a shorter timeout cannot get its response + * in time, so it fails, and the client retries it. + */ + public const MIN_STREAM_TIMEOUT_SECS = 0.5; + private const MICROS_PER_MILLI = 1000; private const MILLIS_PER_SEC = 1000; @@ -94,17 +102,29 @@ public function __construct(private LogClient $logClient, callable $sink, ?DateT /** * 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 before it carried data + * @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 breaks off again before it reaches the last redirected message + * @throws ApifyClientException if a reopened stream is cut again before it reaches the last redirected message */ public function redirect(callable $runFinished, ?float $deadline = null): void { $emptyRetryMillis = self::EMPTY_STREAM_RETRY_MILLIS; while (!self::passed($deadline)) { - // 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), $deadline === null ? null : $deadline - microtime(true)); + $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; } @@ -208,13 +228,15 @@ private function reopenAfterCut(StreamInterface $stream, ?RuntimeException $caus { if (!$this->replayCaughtUp()) { throw new ApifyClientException( - 'Log redirection stopped: the reopened log stream broke off again before it reached the last redirected message.', + 'Log redirection stopped: the reopened log stream was cut again before it reached the last redirected message.', 0, $cause ); } $this->replayedUntil = $this->lastRedirectedAt; $this->replaySkipCount = $this->redirectedAtLastTimestamp; + // The reopened stream starts with what was redirected already, lines without a timestamp included. + $this->lastMessageSkipped = true; $stream->close(); return self::OUTCOME_BROKE_OFF; } diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php index a2748cb..a40c9cf 100644 --- a/tests/Unit/LogRedirectionTest.php +++ b/tests/Unit/LogRedirectionTest.php @@ -6,12 +6,16 @@ use Apify\Client\ApifyClient; use Apify\Client\Exception\ApifyClientException; +use Apify\Client\Exception\TransportException; +use Apify\Client\Http\HttpClientInterface; use Apify\Client\Internal\Json; use Apify\Client\Internal\StderrLogSink; +use Apify\Client\Internal\StreamedLog; use DateTimeImmutable; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use RuntimeException; use Throwable; @@ -173,7 +177,7 @@ public function testAStreamThatBreaksOffAgainBeforeCatchingUpStopsTheRedirection $sink = new MessageCollector(); $this->expectException(ApifyClientException::class); - $this->expectExceptionMessage('broke off again'); + $this->expectExceptionMessage('was cut again'); $this->client($transport)->run('r1')->redirectLog($sink); } @@ -194,7 +198,7 @@ public function testAStreamThatEndsCleanlyWhileTheRunGoesOnIsReopened(): void public function testWaitSecsBoundsAQuietStream(): void { - $transport = (new MockTransport())->queueRawResponse(new Response(200, [], new SilentStream(100_000))); + $transport = (new MockTransport())->queueRawResponse(new Response(200, [], new ScriptedStream([], null, 100_000, true))); $sink = new MessageCollector(); $start = microtime(true); @@ -210,7 +214,7 @@ public function testWaitSecsBoundsAQuietStream(): void public function testAReadThatFailsAfterTheDeadlineIsNotACut(): void { - $transport = (new MockTransport())->queueRawResponse(new Response(200, [], new SilentStream(1_200_000, new RuntimeException('read timed out')))); + $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); @@ -222,7 +226,7 @@ public function testCallWaitsOnlyTheTimeThatIsLeftAfterTheRedirection(): void { $transport = (new MockTransport()) ->queueResponse(201, self::runBody('READY')) - ->queueRawResponse(new Response(200, [], new SilentStream(100_000))) + ->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()); @@ -280,6 +284,67 @@ public function testSinceAlsoSkipsTheContinuationOfASkippedMessage(): void 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 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')); @@ -349,12 +414,21 @@ public function __invoke(string $message): void } } -/** A readable stream that delivers its chunks one by one, then ends or fails with the given error. */ +/** 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 */ - public function __construct(private array $chunks, private ?Throwable $thenFail = null) - { + /** + * @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 @@ -385,7 +459,7 @@ public function tell(): int public function eof(): bool { - return $this->chunks === [] && $this->thenFail === null; + return !$this->endless && $this->chunks === [] && $this->thenFail === null; } public function isSeekable(): bool @@ -420,6 +494,9 @@ public function isReadable(): bool public function read(int $length): string { + if ($this->waitMicros > 0) { + usleep($this->waitMicros); + } if ($this->chunks !== []) { return (string) array_shift($this->chunks); } @@ -440,88 +517,23 @@ public function getMetadata(?string $key = null) } } -/** A readable stream that has nothing to deliver: each read waits, then returns nothing or fails. */ -final class SilentStream implements StreamInterface +/** 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 int $waitMicros, private ?Throwable $thenFail = null) - { - } - - public function __toString(): string - { - return ''; - } - - public function close(): void - { - } - - public function detach() - { - return null; - } - - public function getSize(): ?int - { - return null; - } - - public function tell(): int - { - return 0; - } - - public function eof(): bool - { - return false; - } - - 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 + public function __construct(private MockTransport $inner) { - 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 + public function send(RequestInterface $request, float $timeoutSecs): ResponseInterface { - return true; + return $this->inner->send($request, $timeoutSecs); } - public function read(int $length): string + public function sendStreaming(RequestInterface $request, float $timeoutSecs): ResponseInterface { - usleep($this->waitMicros); - if ($this->thenFail !== null) { - throw $this->thenFail; + if ($timeoutSecs < StreamedLog::MIN_STREAM_TIMEOUT_SECS) { + throw new TransportException('timed out', null, true); } - return ''; - } - - public function getContents(): string - { - return ''; - } - - public function getMetadata(?string $key = null) - { - return $key === null ? [] : null; + return $this->inner->sendStreaming($request, $timeoutSecs); } } From 1d7968788690e0e62f9bf6e6197a701d6b541a1b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:47:38 +0000 Subject: [PATCH 18/20] fix: redirect a first line that the first stream was cut inside, test the deadline during a replay --- src/Internal/StreamedLog.php | 10 ++++++++-- tests/Unit/LogRedirectionTest.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 398e3b3..5c70fc7 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -87,6 +87,9 @@ final class StreamedLog /** Whether the last message was left out, so the lines that continue it are left out too. */ private bool $lastMessageSkipped = false; + /** Whether anything has reached the sink, so a reopened stream replays it. */ + private bool $redirectedAnything = false; + /** * @param callable(string): void $sink receives each message * @param DateTimeInterface|null $since redirect only the messages logged at this time or later @@ -235,8 +238,9 @@ private function reopenAfterCut(StreamInterface $stream, ?RuntimeException $caus } $this->replayedUntil = $this->lastRedirectedAt; $this->replaySkipCount = $this->redirectedAtLastTimestamp; - // The reopened stream starts with what was redirected already, lines without a timestamp included. - $this->lastMessageSkipped = true; + // The reopened stream starts with what was redirected already, lines without a timestamp included. If + // nothing was, because the cut came in the first line, that text has not been seen yet. + $this->lastMessageSkipped = $this->redirectedAnything; $stream->close(); return self::OUTCOME_BROKE_OFF; } @@ -285,6 +289,7 @@ private function redirectMessages(string $text): void $leading = trim((string) array_shift($parts)); if ($leading !== '' && !$this->lastMessageSkipped) { ($this->sink)($leading); + $this->redirectedAnything = true; } for ($i = 0; $i + 1 < count($parts); $i += 2) { @@ -295,6 +300,7 @@ private function redirectMessages(string $text): void } // The original log level is not available, so every message is redirected as it is. ($this->sink)(trim($timestamp . $parts[$i + 1])); + $this->redirectedAnything = true; $this->rememberRedirected($timestamp); } } diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php index a40c9cf..a848b66 100644 --- a/tests/Unit/LogRedirectionTest.php +++ b/tests/Unit/LogRedirectionTest.php @@ -298,6 +298,36 @@ public function testAnUntimestampedFirstLineIsNotRedirectedAgainByAReopenedStrea 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 testAReopenedStreamThatEndsCleanlyBeforeCatchingUpStopsTheRedirection(): void { $transport = (new MockTransport()) From 844dfb8635bfb3db258c68a87f1d6a1f17944628 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 09:58:11 +0000 Subject: [PATCH 19/20] fix: replay a cut log stream by byte offset so no line is lost or repeated A reopened log stream skips the bytes that were handled already instead of counting messages by timestamp. A cut inside the opening text or a continuation line no longer loses a line. --- src/Internal/StreamedLog.php | 97 +++++++++++-------------------- tests/Unit/LogRedirectionTest.php | 29 +++++++++ 2 files changed, 62 insertions(+), 64 deletions(-) diff --git a/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 5c70fc7..4a0ba9c 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -22,10 +22,10 @@ * * The API serves the log of a run that has not logged anything yet as an empty stream that ends at once, so the * stream is reopened until the first bytes arrive. A stream that broke off after it had delivered data is reopened - * too. The API cannot continue a log stream from a given point, so the reopened stream replays the log from its start, - * and the messages that were redirected already are skipped. A stream that ends after delivering data while the run - * has not finished was cut as well, whether or not the transport reports an error, so it is reopened. A stream that - * ends after the run has finished carried the whole log. + * too. The API cannot continue a log stream from a given point, so the reopened stream replays the log from its + * start. The log only grows, so the bytes that were handled already are skipped, wherever the cut came. A stream that + * ends after delivering data while the run has not finished was cut as well, whether or not the transport reports an + * error, so it is reopened. A stream that ends after the run has finished carried the whole log. * * @internal */ @@ -76,20 +76,15 @@ final class StreamedLog private bool $receivedData = false; - /** The timestamp of the last redirected message, and how many redirected messages carry it. */ - private ?string $lastRedirectedAt = null; - private int $redirectedAtLastTimestamp = 0; - - /** A reopened stream replays the messages before this timestamp, and the first {@see $replaySkipCount} at it. */ - private ?string $replayedUntil = null; - private int $replaySkipCount = 0; + /** + * How many bytes of the log have been handled, which is where the unfinished line, if any, starts. A reopened + * stream skips that many bytes. + */ + private int $handledBytes = 0; /** Whether the last message was left out, so the lines that continue it are left out too. */ private bool $lastMessageSkipped = false; - /** Whether anything has reached the sink, so a reopened stream replays it. */ - private bool $redirectedAnything = false; - /** * @param callable(string): void $sink receives each message * @param DateTimeInterface|null $since redirect only the messages logged at this time or later @@ -108,7 +103,7 @@ public function __construct(private LogClient $logClient, callable $sink, ?DateT * @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 the last redirected message + * @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 { @@ -171,7 +166,10 @@ private function redirectWholeLog(): void */ private function redirectStream(StreamInterface $stream, ?float $deadline, callable $runFinished): string { - // A chunk may end in the middle of a line. The incomplete rest waits here for the next chunk. + // 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()) { @@ -191,13 +189,21 @@ private function redirectStream(StreamInterface $stream, ?float $deadline, calla if (!$this->receivedData) { throw $e; } - return $this->reopenAfterCut($stream, $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"); @@ -206,78 +212,44 @@ private function redirectStream(StreamInterface $stream, ?float $deadline, calla 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, null); + return $this->reopenAfterCut($stream, $toSkip, null); } // Maybe it is incomplete, maybe it is the last message without an end of line. + $this->handledBytes += strlen($remainder); $this->redirectMessages($remainder); $stream->close(); return $outcome; } /** - * Prepares the reopening of a stream that was cut. The reopened stream replays the log, so the unfinished line is - * dropped and the messages redirected so far are skipped. + * 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, ?RuntimeException $cause): string + private function reopenAfterCut(StreamInterface $stream, int $toSkip, ?RuntimeException $cause): string { - if (!$this->replayCaughtUp()) { + if ($toSkip > 0) { throw new ApifyClientException( 'Log redirection stopped: the reopened log stream was cut again before it reached the last redirected message.', 0, $cause ); } - $this->replayedUntil = $this->lastRedirectedAt; - $this->replaySkipCount = $this->redirectedAtLastTimestamp; - // The reopened stream starts with what was redirected already, lines without a timestamp included. If - // nothing was, because the cut came in the first line, that text has not been seen yet. - $this->lastMessageSkipped = $this->redirectedAnything; $stream->close(); return self::OUTCOME_BROKE_OFF; } - /** Whether the current stream got at least as far as the stream before it. */ - private function replayCaughtUp(): bool - { - return $this->replayedUntil === null || $this->replaySkipCount === 0; - } - - /** Whether a message of a reopened stream was redirected before the stream was reopened. */ - private function isReplayed(string $timestamp): bool - { - if ($this->replayedUntil === null) { - return false; - } - if ($timestamp < $this->replayedUntil) { - return true; - } - if ($timestamp === $this->replayedUntil && $this->replaySkipCount > 0) { - $this->replaySkipCount--; - return true; - } - $this->replayedUntil = null; - return false; - } - - private function rememberRedirected(string $timestamp): void - { - if ($timestamp === $this->lastRedirectedAt) { - $this->redirectedAtLastTimestamp++; - } else { - $this->lastRedirectedAt = $timestamp; - $this->redirectedAtLastTimestamp = 1; - } - } - /** Splits complete text into messages and hands each one to the sink. */ private function redirectMessages(string $text): void { @@ -289,19 +261,16 @@ private function redirectMessages(string $text): void $leading = trim((string) array_shift($parts)); if ($leading !== '' && !$this->lastMessageSkipped) { ($this->sink)($leading); - $this->redirectedAnything = true; } for ($i = 0; $i + 1 < count($parts); $i += 2) { $timestamp = $parts[$i]; - $this->lastMessageSkipped = $this->isReplayed($timestamp) || ($this->since !== null && $timestamp < $this->since); + $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])); - $this->redirectedAnything = true; - $this->rememberRedirected($timestamp); } } diff --git a/tests/Unit/LogRedirectionTest.php b/tests/Unit/LogRedirectionTest.php index a848b66..f3105bc 100644 --- a/tests/Unit/LogRedirectionTest.php +++ b/tests/Unit/LogRedirectionTest.php @@ -328,6 +328,35 @@ public function testAReadThatFailsAfterTheDeadlineWhileTheLogIsReplayedIsNotACut 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()) From 1529bab244edb0175c85d809bf2d409b8c275d82 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 10:09:28 +0000 Subject: [PATCH 20/20] docs: describe the resume point of a cut log stream as the cut line --- docs/runs.md | 2 +- src/Internal/StreamedLog.php | 3 +-- src/Resource/RunClient.php | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/runs.md b/docs/runs.md index e73216a..9230711 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -32,7 +32,7 @@ An Actor's or task's runs are available at `$client->actor($id)->runs()` / `$cli - `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`: `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 after the last message. `$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 last message. A stream that fails before it delivered anything throws its error. +- `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/src/Internal/StreamedLog.php b/src/Internal/StreamedLog.php index 4a0ba9c..f04e27a 100644 --- a/src/Internal/StreamedLog.php +++ b/src/Internal/StreamedLog.php @@ -221,7 +221,6 @@ private function redirectStream(StreamInterface $stream, ?float $deadline, calla } // Maybe it is incomplete, maybe it is the last message without an end of line. - $this->handledBytes += strlen($remainder); $this->redirectMessages($remainder); $stream->close(); return $outcome; @@ -241,7 +240,7 @@ private function reopenAfterCut(StreamInterface $stream, int $toSkip, ?RuntimeEx { if ($toSkip > 0) { throw new ApifyClientException( - 'Log redirection stopped: the reopened log stream was cut again before it reached the last redirected message.', + 'Log redirection stopped: the reopened log stream was cut again before it reached the point where the previous stream was cut.', 0, $cause ); diff --git a/src/Resource/RunClient.php b/src/Resource/RunClient.php index 0e08dc0..55b4766 100644 --- a/src/Resource/RunClient.php +++ b/src/Resource/RunClient.php @@ -276,8 +276,8 @@ public function getStreamedLog(int|float|string|null $timeoutSecs = null): Strea * 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 after the last - * redirected message. A message starts with its timestamp, and a line without one is redirected as it is. + * 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} -> "}.