Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 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.
- Documented that `RunClient::metamorph()` and `RunClient::charge()` need the run's own token.
- Documented that Apify Console shows an API token only once, and that a schedule's `uiState` can be `null`.
- Added a `metamorph()` integration test and a unit test for a user fetched with a proxy password.

## 0.14.0

- Synced with Apify OpenAPI spec `v2-2026-11-09T143926Z`: `zstd` is a documented `Content-Encoding`.
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ echo 'Item count: ' . $items->getCount() . PHP_EOL;
```

The client does not read `APIFY_TOKEN`. Pass it yourself, for example `new ApifyClient(getenv('APIFY_TOKEN'))`.
You can find your token in [Apify Console → Settings → API & Integrations](https://console.apify.com/settings/integrations).
You can create a token in [Apify Console → Settings → API & Integrations](https://console.apify.com/settings/integrations).
Apify Console shows a token only once, right after you create or rotate it, so store it somewhere safe.

## Configuration

Expand Down
2 changes: 1 addition & 1 deletion docs/misc.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ foreach ($client->store()->iterate(new StoreListOptions(search: 'scraper'), 50)

## Users — `$client->me()` / `$client->user($id)`

- `get(): ?User`: for `me()`, the private account details are in `toArray()`.
- `get(): ?User`: the private account details, such as the plan and email, are in `toArray()` for `me()` and for a user ID fetched with a token of that account. A token with limited permissions never gets them, and `me()` omits `plan`, `email` and `profile` when called from an Actor run. With a proxy password as the token, the API returns only `plan.availableProxyGroups`, `effectivePlatformFeatures` and `isPaying`, so `getId()` and `getUsername()` are `null`.
- `monthlyUsage(?string $date = null): array`: the monthly usage of the cycle that contains `$date` (`YYYY-MM-DD`), by default the current month.
- `limits(): array`, `updateLimits(mixed $newLimits): void`: the account limits. These three methods work for `me()` and for any user ID the token may access.

Expand Down
4 changes: 3 additions & 1 deletion docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ kept as received.
| `getCronExpression(): ?string` | The cron expression that triggers the schedule. |
| `isEnabled(): ?bool` | Whether the schedule is enabled. |

The `uiState` field in `toArray()` is `null` after an API update changes the cron expression or timezone.

### `Webhook`
| Getter | Description |
|---|---|
Expand All @@ -116,7 +118,7 @@ kept as received.
| `getId(): ?string` | The user ID. |
| `getUsername(): ?string` | The username. |

Private account details (plan, email, etc.) returned by `me()->get()` are available via `toArray()`.
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.
Expand Down
4 changes: 2 additions & 2 deletions docs/runs.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ An Actor's or task's runs are available at `$client->actor($id)->runs()` / `$cli
- `update(mixed $newFields): ActorRun`
- `delete(): void`
- `abort(?bool $gracefully = null): ActorRun`: with `$gracefully` `true`, the run can finish its current request first. `false` and `null` (the default) abort at once.
- `metamorph(string $targetActorId, mixed $input = null, ?MetamorphOptions $options = null): ActorRun`: `$input` is as for `ActorClient::start()`.
- `metamorph(string $targetActorId, mixed $input = null, ?MetamorphOptions $options = null): ActorRun`: `$input` is as for `ActorClient::start()`. Only the run itself can metamorph: call it from the Actor run, with the token the run received in `APIFY_TOKEN`. Any other token is rejected.
- `reboot(): ActorRun`
- `resurrect(?RunResurrectOptions $options = null): ActorRun`
- `charge(RunChargeOptions $options): void`: for pay-per-event Actors.
- `charge(RunChargeOptions $options): void`: for pay-per-event Actors. Call it from the Actor run itself, with the token the run received in `APIFY_TOKEN`. For a multi-tenant Server Actor, set `requestId` to the request's `X-Actor-Request-ID` header value.
- `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).
Expand Down
5 changes: 4 additions & 1 deletion src/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
namespace Apify\Client\Model;

/**
* A user account. The private details of {@code me}, such as email, plan, and proxy settings, are in {@see toArray()}.
* A user account. The private details, such as email, plan, and proxy settings, are in {@see toArray()}. The API returns
* them for {@code me} and for the user of the token, but not for other users or for a token with limited permissions.
* For a request authenticated with a proxy password, the API returns only the fields Apify Proxy reads
* ({@code plan.availableProxyGroups}, {@code effectivePlatformFeatures} and {@code isPaying}), without an ID or a username.
*/
final class User extends ApifyResource
{
Expand Down
9 changes: 7 additions & 2 deletions src/Resource/RunClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ public function abort(?bool $gracefully = null, int|float|string|null $timeoutSe
}

/**
* Transforms the run into a run of another Actor with a new input.
* Transforms the run into a run of another Actor with a new input. Only the run itself can metamorph: the client
* must use the run's own API token, which the run gets in the {@code APIFY_TOKEN} environment variable. With any
* other token, the API rejects the request.
*
* @param string $targetActorId the Actor to metamorph into
* @param mixed $input the new input: a JSON-serializable value, a string sent as it is (set a
Expand Down Expand Up @@ -156,7 +158,10 @@ public function resurrect(?RunResurrectOptions $options = null, int|float|string
/**
* Charges for events of a pay-per-event Actor run.
*
* The request always carries an idempotency key, so a retried charge is applied once.
* Call it from the Actor run itself, with a client that uses the token the run received in its
* {@code APIFY_TOKEN} environment variable. The request always carries an idempotency key, so a retried
* charge is applied once. To charge a request to a multi-tenant Server Actor, set
* {@see RunChargeOptions::$requestId} to the request's {@code X-Actor-Request-ID} header value.
*/
public function charge(RunChargeOptions $options, int|float|string|null $timeoutSecs = null): void
{
Expand Down
8 changes: 6 additions & 2 deletions src/Resource/UserClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ public function __construct(private HttpClientCore $http, string $baseUrl, strin
}

/**
* Fetches the user: the private account details for {@code me}, the public profile for others. Returns
* {@code null} if the user does not exist.
* Fetches the user: the public profile, plus the private account details for {@code me} and for a user ID
* fetched with a token of that account. A token with limited permissions never gets the private details, and
* {@code me} omits {@code plan}, {@code email} and {@code profile} when called from an Actor run. Returns
* {@code null} if the user does not exist. With a proxy password as the token, the API returns only
* {@code plan.availableProxyGroups}, {@code effectivePlatformFeatures} and {@code isPaying}, so
* {@see User::getId()} and {@see User::getUsername()} are {@code null}; read the fields from {@see User::toArray()}.
*/
public function get(int|float|string|null $timeoutSecs = null): ?User
{
Expand Down
4 changes: 2 additions & 2 deletions src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.0';
public const CLIENT_VERSION = '0.14.1';

/**
* 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-09T143926Z';
public const API_SPEC_VERSION = 'v2-2026-11-18T151559Z';

private function __construct()
{
Expand Down
81 changes: 81 additions & 0 deletions tests/Integration/ActorRunIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Apify\Client\ApifyClient;
use Apify\Client\Internal\UrlNormalizer;
use Apify\Client\Options\ActorStartOptions;
use Apify\Client\Options\DatasetListItemsOptions;
use Apify\Client\Options\LastRunOptions;
use Apify\Client\Options\ListOptions;
Expand All @@ -15,6 +16,21 @@

final class ActorRunIntegrationTest extends IntegrationTestCase
{
/** Memory of the metamorph Actor run, enough for a script that makes one request. */
private const METAMORPH_RUN_MEMORY_MBYTES = 256;
/** Timeout of the metamorph run. It must exceed {@see METAMORPH_ACTOR_WAIT_SECS} plus the hello-world run. */
private const METAMORPH_RUN_TIMEOUT_SECS = 300;
/** How long the metamorph Actor waits after storing its token. */
private const METAMORPH_ACTOR_WAIT_SECS = 240;
/** How long the test polls for the stored token. It must stay below {@see METAMORPH_ACTOR_WAIT_SECS}, or the run could end first. */
private const METAMORPH_TOKEN_POLL_BUDGET_SECS = 120;
/** Seconds between two reads of the stored token. */
private const METAMORPH_TOKEN_POLL_SECS = 2;
/** How long hello-world, which replaces the waiting Actor, gets to finish the run after the metamorph. */
private const METAMORPH_HELLO_WORLD_WAIT_SECS = 300;
/** How long the cleanup waits for an aborted run to finish. */
private const METAMORPH_ABORT_WAIT_SECS = 60;

public function testListRuns(): void
{
$client = $this->requireClient();
Expand Down Expand Up @@ -136,6 +152,71 @@ public function testIterateDatasetItemsReadsItemsWhileTheRunIsStillRunning(): vo
}
}

public function testMetamorphWithTheRunsOwnTokenTransformsTheRunKeepingItsId(): void
{
$client = $this->requireClient();
// An Actor that stores its run token under `TOKEN` in its key-value store, then waits.
$waitSecs = self::METAMORPH_ACTOR_WAIT_SECS;
$script = <<<JS
const base = (process.env.APIFY_API_PUBLIC_BASE_URL || 'https://api.apify.com').replace(/\/$/, '');
const url = `\${base}/v2/key-value-stores/\${process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID}/records/TOKEN?token=\${process.env.APIFY_TOKEN}`;
(async () => {
const response = await fetch(url, {
method: 'PUT',
headers: { 'content-type': 'text/plain' },
body: process.env.APIFY_TOKEN,
});
if (!response.ok) throw new Error(`storing the token failed: \${response.status}`);
await new Promise((resolve) => setTimeout(resolve, {$waitSecs} * 1000));
})();
JS;
$actorId = $this->createBuiltActor($client, 'metamorph', $script);
try {
$run = $client->actor($actorId)->start(null, new ActorStartOptions(
memoryMbytes: self::METAMORPH_RUN_MEMORY_MBYTES,
timeoutSecs: self::METAMORPH_RUN_TIMEOUT_SECS,
));
$runId = (string) $run->getId();
$runClient = $client->run($runId);
try {
$store = $client->keyValueStore((string) $run->getDefaultKeyValueStoreId());
$runToken = null;
$maxAttempts = intdiv(self::METAMORPH_TOKEN_POLL_BUDGET_SECS, self::METAMORPH_TOKEN_POLL_SECS);
for ($attempt = 1; $attempt <= $maxAttempts && $runToken === null; $attempt++) {
$runToken = $store->getRecord('TOKEN')?->getValue();
if ($runToken === null) {
self::assertContains($runClient->get()?->getStatus(), ['READY', 'RUNNING'], 'The run ended without storing its token.');
sleep(self::METAMORPH_TOKEN_POLL_SECS);
}
}
self::assertNotEmpty($runToken, 'The run did not store its token in time.');
// The token must not stay in storage.
$store->deleteRecord('TOKEN');

$metamorphed = $this->requireClient(token: $runToken)->run($runId)
->metamorph('apify/hello-world', ['message' => 'Hello from metamorph!']);
self::assertSame($runId, $metamorphed->getId());

// Hello-world replaces the waiting Actor, so the run finishes on its own.
$finished = $runClient->waitForFinish(self::METAMORPH_HELLO_WORLD_WAIT_SECS);
self::assertSame('SUCCEEDED', $finished->getStatus());
$helloWorldId = $client->actor('apify/hello-world')->get()?->getId();
self::assertNotNull($helloWorldId);
$metamorphs = $finished->get('metamorphs');
self::assertIsArray($metamorphs);
self::assertCount(1, $metamorphs);
self::assertSame($helloWorldId, $metamorphs[0]['actorId'] ?? null);
} finally {
// Aborting a finished run returns it unchanged.
$runClient->abort();
$runClient->waitForFinish(self::METAMORPH_ABORT_WAIT_SECS);
$runClient->delete();
}
} finally {
$client->actor($actorId)->delete();
}
}

/**
* Creates an Actor with the script as {@code main.js}, waits for its build, and returns its ID. The caller deletes
* the Actor.
Expand Down
12 changes: 8 additions & 4 deletions tests/Integration/IntegrationTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,22 @@ protected static function resolveBaseUrl(?string $apiUrl): string
private const LISTING_MAX_ATTEMPTS = 30;
private const LISTING_RETRY_DELAY_SECS = 3;

/** Returns a configured client, or skips the test if {@code APIFY_TOKEN} is unset. */
/**
* Returns a configured client, or skips the test if {@code APIFY_TOKEN} is unset. The client uses
* {@code $token} instead of {@code APIFY_TOKEN} if given, for example the token of an Actor run.
*/
protected function requireClient(
string|HttpCompressorInterface|null $compression = null,
?HttpClientInterface $httpClient = null,
?string $token = null,
): ApifyClient {
$token = getenv('APIFY_TOKEN');
if ($token === false || $token === '') {
$envToken = getenv('APIFY_TOKEN');
if ($envToken === false || $envToken === '') {
self::markTestSkipped('skipping: APIFY_TOKEN is not set');
}
$apiUrl = getenv('APIFY_API_URL');
return new ApifyClient(
token: $token,
token: $token ?? $envToken,
baseUrl: self::resolveBaseUrl($apiUrl === false ? null : $apiUrl),
httpClient: $httpClient,
compression: $compression,
Expand Down
19 changes: 19 additions & 0 deletions tests/Unit/SpecSyncTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,25 @@ public function testScheduleWithANullUiStateIsReadAsIs(): void
self::assertArrayHasKey('uiState', $schedule->toArray());
}

public function testUserFetchedWithAProxyPasswordHasNoIdOrUsername(): void
{
// The API returns only the fields Apify Proxy reads when the caller authenticates with a proxy password.
$proxyInfo = [
'plan' => ['availableProxyGroups' => ['GOOGLE_SERP' => 200]],
'effectivePlatformFeatures' => [],
'isPaying' => true,
];
$transport = (new MockTransport())->queueResponse(200, Json::encode(['data' => $proxyInfo]));

$user = $this->client($transport)->me()->get();

self::assertNotNull($user);
self::assertNull($user->getId());
self::assertNull($user->getUsername());
self::assertSame(200, $user->toArray()['plan']['availableProxyGroups']['GOOGLE_SERP']);
self::assertTrue($user->get('isPaying'));
}

public function testPendingStoredRequestWithANullHandledAtIsReadAsIs(): void
{
$transport = (new MockTransport())->queueResponse(200, Json::encode(['data' => [
Expand Down
Loading