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
4 changes: 4 additions & 0 deletions .github/workflows/dotnet-integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ on:
- 'src/Apify.Client/Internal/ResponseSchemas.json'
- 'tools/**'
- 'Directory.Build.props'
- 'global.json'
- '.editorconfig'
# The "Test examples" step validates the in-documentation snippets, so doc changes must re-run
# the workflow even though Markdown is not .NET code.
Expand All @@ -37,6 +38,9 @@ jobs:
- name: Set up .NET
uses: actions/setup-dotnet@v4
with:
# global.json pins the SDK that builds and analyzes the code, so a newer SDK on the runner image cannot add
# analyzer rules between runs. The client targets net8.0, so the tests also need the .NET 8 runtime.
global-json-file: global.json
dotnet-version: '8.0.x'

- name: Restore
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/dotnet-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ jobs:
- name: Set up .NET
uses: actions/setup-dotnet@v4
with:
# global.json pins the SDK that builds and analyzes the code, so a newer SDK on the runner image cannot add
# analyzer rules between runs. The client targets net8.0, so the tests also need the .NET 8 runtime.
global-json-file: global.json
dotnet-version: '8.0.x'

- name: Restore
Expand Down
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## 0.10.1

- Updated to the Apify OpenAPI specification `v2-2026-11-18T151559Z`. User responses with the reduced shape that
Apify Proxy reads (`UserProxyInfo`) no longer fail response validation.
- Documented that `RunClient.MetamorphAsync` needs a client created with the run's own `APIFY_TOKEN`, and added an
integration test that metamorphs a run this way.
- Pinned the .NET SDK (11.0.100) in `global.json`, which both workflows use, so that the SDK on the runner image
cannot change between runs. Replaced `Task.WhenAny` with `WaitAsync` in a test helper, which SDK 11 reports as CA2027.
- Documented that `RunClient.ChargeAsync` is called from the run with its `APIFY_TOKEN`, and that
`RunChargeOptions.RequestId` charges a multi-tenant Server Actor request.
- Documented that Apify Console shows an API token only once, and linked "Develop Server Actors" from
`Actor.ActorStandby`.

## 0.10.0

- Added `RequestCompression.Zstd` and `ZstdHttpCompressor` (quality 1 to 19, default 3), which compress request
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ Console.WriteLine($"Items on this page: {items.Items.Count} (of {items.Total} to
```

`new ApifyClient("my-api-token")` takes the token as an explicit argument and does **not** read
`APIFY_TOKEN` automatically. Get your token from the
[Apify Console → Settings → API & Integrations](https://console.apify.com/settings/integrations).
`APIFY_TOKEN` automatically. Create a token in
[Apify Console → Settings → API & Integrations](https://console.apify.com/settings/integrations). Apify Console
shows the token only once, right after you create or rotate it, so copy it and store it somewhere safe.

## Documentation

Expand Down
6 changes: 5 additions & 1 deletion docs/misc.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ await foreach (var item in client.Store().IterateAsync(new StoreListOptions { Se
## Users: `client.Me()` / `client.User(id)`

- `GetAsync()` → `User?`. For `Me()` the raw payload includes private account details
(`ToJsonObject()`); for `User(id)` it returns the public profile.
(`ToJsonObject()`); `User(id)` returns the public profile, plus the private details when the token belongs to
that account or impersonates it (a token with limited permissions never gets them). The API can instead return
the reduced user object that Apify Proxy reads (the specification does not say when). Then `Id` and `Username`
are `null`, and `plan.availableProxyGroups`, `effectivePlatformFeatures`, and `isPaying` are read via
`ToJsonObject()`.
- `MonthlyUsageAsync(string? date = null)` → `JsonObject` (`date` is `YYYY-MM-DD`, and `null` reports the
current month).
- `LimitsAsync()` → `JsonObject` / `UpdateLimitsAsync(object newLimits)`.
Expand Down
9 changes: 6 additions & 3 deletions docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Base class for every JSON-backed model below.
| `CreatedAt` | `string?` | ISO 8601 creation timestamp. |
| `ModifiedAt` | `string?` | ISO 8601 last-modification timestamp. |
| `StandbyUrl` | `string?` | URL of the Actor's server when it is a Server Actor (see [`ActorServerClient`](actors.md#server-actors-clientactoridserver)); `null` otherwise. |
| `ActorStandby` | `JsonObject?` | The Server Actor settings: `isEnabled`, `build`, `memoryMbytes`, `idleTimeoutSecs`, `tenancy` (`SINGLE_TENANT` or `MULTI_TENANT`) and others. |
| `ActorStandby` | `JsonObject?` | The Server Actor settings: `isEnabled`, `build`, `memoryMbytes`, `idleTimeoutSecs`, `tenancy` (`SINGLE_TENANT` or `MULTI_TENANT`), and others; see [Develop Server Actors](https://docs.apify.com/platform/actors/development/programming-interface/server-actors). |
| `TaggedBuilds` | `JsonObject?` | The builds the Actor's tags point to, keyed by tag (e.g. `latest`); each value has `buildId` and `buildNumber`. |

## `ActorRun`
Expand Down Expand Up @@ -341,8 +341,11 @@ The aggregate result of a batch add-requests operation.

## `User`

Returned by `client.Me().GetAsync()` (private account details) and `client.User(id).GetAsync()`
(public profile). Only the always-present fields are typed; read the rest via `ToJsonObject()`.
Returned by `client.Me().GetAsync()` (private account details) and `client.User(id).GetAsync()` (public profile,
plus the private details when the token belongs to that account or impersonates it; a token with limited
permissions never gets them). Only `Id` and `Username` are typed; read the rest via `ToJsonObject()`. The API can
instead return the reduced user object that Apify Proxy reads, with only `plan.availableProxyGroups`,
`effectivePlatformFeatures`, and `isPaying`. Then `Id` and `Username` are `null`.

| Property | Type | Description |
|---|---|---|
Expand Down
6 changes: 3 additions & 3 deletions docs/runs.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ collections, not by task runs).
- `UpdateAsync(object newFields)` → `ActorRun`.
- `DeleteAsync()`.
- `AbortAsync(bool? gracefully = null)` → `ActorRun`.
- `MetamorphAsync(string targetActorId, object? input = null, MetamorphOptions? options = null)` → `ActorRun`.
- `MetamorphAsync(string targetActorId, object? input = null, MetamorphOptions? options = null)` → `ActorRun`. Only the run itself can metamorph: call it with a client created with the run's own `APIFY_TOKEN`; the API rejects any other token.
- `RebootAsync()` → `ActorRun`.
- `ResurrectAsync(RunResurrectOptions? options = null)` → `ActorRun`: resurrects a finished run (status `SUCCEEDED`, `FAILED`, `ABORTED`, or `TIMED-OUT`) and restarts it with the same storages.
- `ChargeAsync(RunChargeOptions options)` → `Task`: record pay-per-event charges (idempotent).
- `ChargeAsync(RunChargeOptions options)` → `Task`: record pay-per-event charges (idempotent). Call it from the run itself, with a client created with the `APIFY_TOKEN` the platform provides to the run at startup.
- `WaitForFinishAsync(int? waitSecs = null)` → `ActorRun`: client-side polling until terminal (`null`
waits indefinitely). A run id that keeps answering 404 for 3 seconds straight (replica lag resolves
faster than that) throws `NotFoundException` instead of polling for the rest of `waitSecs`.
Expand Down Expand Up @@ -80,7 +80,7 @@ await foreach (var item in client.Run(run.Id!).IterateDatasetItemsAsync(new RunI
| `EventName` | `string` | Name of the pay-per-event event to charge for (required, non-empty). |
| `Count` | `int?` | Number of event occurrences to charge (defaults to 1). |
| `IdempotencyKey` | `string?` | Key that deduplicates retried charges; auto-generated when omitted. |
| `RequestId` | `string?` | ID of the Server Actor request being charged (the `X-Actor-Request-ID` header of the incoming request); required for multi-tenant Server Actor runs. Set via object initializer. |
| `RequestId` | `string?` | ID of the Server Actor request being charged (the `X-Actor-Request-ID` header of the incoming request; see [Charge for a request](https://docs.apify.com/platform/actors/monetize/server-actors#charge-for-a-request)); required for multi-tenant Server Actor runs. Runs of single-tenant Server Actors ignore it. Set via object initializer. |

```csharp
using Apify.Client;
Expand Down
6 changes: 6 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "11.0.100",
"rollForward": "latestPatch"
}
}
2 changes: 1 addition & 1 deletion src/Apify.Client/Apify.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<!-- NuGet package metadata (see the publish workflow). -->
<PackageId>Apify.Client</PackageId>
<Version>0.10.0</Version>
<Version>0.10.1</Version>
<Authors>Apify</Authors>
<Company>Apify</Company>
<Product>Apify API client for .NET</Product>
Expand Down
4 changes: 2 additions & 2 deletions src/Apify.Client/ApifyClientVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ public static class ApifyClientVersion
/// The semantic version of this client library (see https://semver.org/). Changes to the public
/// interface other than additive ones are considered breaking changes.
/// </summary>
public const string ClientVersion = "0.10.0";
public const string ClientVersion = "0.10.1";

/// <summary>
/// The version of the Apify OpenAPI specification this client was generated and verified against.
/// Corresponds to the <c>info.version</c> field of the Apify OpenAPI document.
/// </summary>
public const string ApiSpecVersion = "v2-2026-11-09T143926Z";
public const string ApiSpecVersion = "v2-2026-11-18T151559Z";
}
2 changes: 1 addition & 1 deletion src/Apify.Client/Internal/ResponseSchemas.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/Apify.Client/Models/Actor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public Actor(JsonObject data)

/// <summary>
/// The Server Actor settings (<c>actorStandby</c>): <c>isEnabled</c>, <c>build</c>, <c>memoryMbytes</c>,
/// <c>idleTimeoutSecs</c>, <c>tenancy</c> (<c>SINGLE_TENANT</c> or <c>MULTI_TENANT</c>) and others; <c>null</c> when absent.
/// <c>idleTimeoutSecs</c>, <c>tenancy</c> (<c>SINGLE_TENANT</c> or <c>MULTI_TENANT</c>), and others; <c>null</c> when absent.
/// See <see href="https://docs.apify.com/platform/actors/development/programming-interface/server-actors">Develop Server Actors</see>.
/// </summary>
public JsonObject? ActorStandby => Get("actorStandby") as JsonObject;

Expand Down
8 changes: 7 additions & 1 deletion src/Apify.Client/Resources/RunClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ public async Task<ActorRun> AbortAsync(bool? gracefully = null, CancellationToke
}

/// <summary>Transforms the run into a run of another Actor with a new input.</summary>
/// <remarks>
/// Only the run itself can metamorph: use a client created with the run's own API token, which the run gets in the
/// <c>APIFY_TOKEN</c> environment variable. With any other token, the API rejects the request.
/// </remarks>
/// <param name="targetActorId">The Actor to metamorph into.</param>
/// <param name="input">The new input: <c>byte[]</c> is sent as it is, anything else as JSON, <c>null</c> for none.</param>
/// <param name="options">Optional metamorph options.</param>
Expand Down Expand Up @@ -139,7 +143,9 @@ public async Task<ActorRun> ResurrectAsync(RunResurrectOptions? options = null,
/// <summary>Charges for events of a pay-per-event Actor run.</summary>
/// <remarks>
/// The request always carries an idempotency key (generated when not given), so a charge the transport retries is
/// applied once.
/// applied once. Call it from the run itself, with a client created with the <c>APIFY_TOKEN</c> the platform
/// provides to the run at startup. To charge a request to a multi-tenant Server Actor, set
/// <see cref="RunChargeOptions.RequestId"/>.
/// </remarks>
/// <param name="options">The charge event details.</param>
/// <param name="cancellationToken">A token to cancel the request.</param>
Expand Down
6 changes: 5 additions & 1 deletion src/Apify.Client/Resources/UserClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ internal UserClient(HttpClientCore http, string baseUrl, string id)

/// <summary>
/// Fetches the user: private account details for <c>me</c> (via <see cref="ApifyResource.ToJsonObject"/>), the public
/// profile for others. Returns <c>null</c> if the user does not exist.
/// profile for others, plus the private details when the token belongs to that account or impersonates it (a token
/// with limited permissions never gets them). The API can instead return the reduced user object that Apify Proxy
/// reads; the specification does not say when. <see cref="User.Id"/> and <see cref="User.Username"/> are then
/// <c>null</c>, and <c>plan.availableProxyGroups</c>, <c>effectivePlatformFeatures</c>, and <c>isPaying</c> are
/// available via <see cref="ApifyResource.ToJsonObject"/>. Returns <c>null</c> if the user does not exist.
/// </summary>
/// <param name="cancellationToken">A token to cancel the request.</param>
public async Task<User?> GetAsync(CancellationToken cancellationToken = default)
Expand Down
137 changes: 137 additions & 0 deletions tests/Apify.Client.Tests/Integration/ActorRunIntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Apify.Client.Models;
using Apify.Client.Options;
using Xunit;

Expand Down Expand Up @@ -123,4 +127,137 @@ public async Task LastRunAccess()
Assert.NotNull(byOrigin);
Assert.Equal("SUCCEEDED", byOrigin!.Status);
}

/// <summary>Memory of the metamorph test run; the smallest the platform offers keeps the test cheap.</summary>
private const int MetamorphRunMemoryMbytes = 256;

/// <summary>
/// Timeout of the metamorph test run. The test Actor waits for the whole timeout after storing its token, which is
/// longer than <see cref="TokenPollAttempts"/> times <see cref="TokenPollInterval"/>, so the run is still waiting when
/// the test has read the token.
/// </summary>
private const int MetamorphRunTimeoutSecs = 300;

/// <summary>How long to wait for the metamorph test Actor's build and for the run to finish after the metamorph.</summary>
private const int MetamorphWaitSecs = 300;

/// <summary>Polls for the run token the Actor stores at startup, which takes the container a short while to reach.</summary>
private const int TokenPollAttempts = 60;

private static readonly TimeSpan TokenPollInterval = TimeSpan.FromSeconds(2);

/// <summary>
/// A metamorph needs the run's own API token, so the test Actor stores its <c>APIFY_TOKEN</c> in its key-value store and
/// then waits long enough for the test to read it.
/// </summary>
private static object MetamorphSourceActor(string name) => new
{
name,
isPublic = false,
description = "Integration test actor",
versions = new[]
{
new
{
versionNumber = "0.0",
sourceType = "SOURCE_FILES",
buildTag = "latest",
sourceFiles = new object[]
{
new { name = "Dockerfile", format = "TEXT", content = "FROM apify/actor-node:22\nCOPY . ./\nCMD [\"node\", \"main.js\"]\n" },
new
{
name = "main.js",
format = "TEXT",
content = "const { Actor } = require('apify');\n"
+ "Actor.main(async () => {\n"
+ " await Actor.setValue('TOKEN', process.env.APIFY_TOKEN, { contentType: 'text/plain' });\n"
+ $" await new Promise((resolve) => setTimeout(resolve, {MetamorphRunTimeoutSecs * 1000}));\n"
+ "});\n",
},
},
},
},
};

[SkippableFact]
public async Task MetamorphRunWithItsOwnToken()
{
var client = RequireClient();
var created = await client.Actors().CreateAsync(MetamorphSourceActor(UniqueName("metamorph")));
try
{
var build = await client.Actor(created.Id!).BuildAsync("0.0");
var finishedBuild = await client.Build(build.Id!).WaitForFinishAsync(MetamorphWaitSecs);
Assert.Equal("SUCCEEDED", finishedBuild.Status);

var run = await client.Actor(created.Id!).StartAsync(
null,
new ActorStartOptions { MemoryMbytes = MetamorphRunMemoryMbytes, TimeoutSecs = MetamorphRunTimeoutSecs });
try
{
await MetamorphAndVerifyAsync(client, run);
}
finally
{
// Aborting a finished run returns it unchanged. The run is deleted even if the abort fails, since its default
// key-value store holds the run's API token until then.
try
{
await client.Run(run.Id!).AbortAsync();
await client.Run(run.Id!).WaitForFinishAsync(MetamorphWaitSecs);
}
finally
{
await client.Run(run.Id!).DeleteAsync();
}
}
}
finally
{
await client.Actor(created.Id!).DeleteAsync();
}
}

private static async Task MetamorphAndVerifyAsync(ApifyClient client, ActorRun run)
{
var store = client.KeyValueStore(run.DefaultKeyValueStoreId!);

// Poll the Actor's key-value store for the token it stores at startup, and fail early if the run ended without it.
string? runToken = null;
Assert.True(
await PollUntilAsync(
TokenPollAttempts,
TokenPollInterval,
async () =>
{
var record = await store.GetRecordAsync("TOKEN");
if (record is not null)
{
runToken = Encoding.UTF8.GetString(record.Value);
return true;
}

var current = await client.Run(run.Id!).GetAsync();
Assert.Contains(current?.Status, new[] { "READY", "RUNNING" });
return false;
}),
"expected the Actor to store its run token");

// The token is a credential: remove it as soon as it is read.
await store.DeleteRecordAsync("TOKEN");

// Only the run itself can metamorph, so use a client with the run's token.
var runClient = RequireClient(options => options.Token = runToken);
var metamorphed = await runClient.Run(run.Id!).MetamorphAsync("apify/hello-world", new { message = "Hello from metamorph!" });
Assert.Equal(run.Id, metamorphed.Id);

// Hello-world replaces the waiting Actor, so the run finishes on its own.
var finalRun = await client.Run(run.Id!).WaitForFinishAsync(MetamorphWaitSecs);
Assert.Equal("SUCCEEDED", finalRun.Status);
var helloWorldId = await ResolveHelloWorldActorIdAsync(client);
var metamorphs = finalRun.ToJsonObject()["metamorphs"] as JsonArray;
Assert.NotNull(metamorphs);
Assert.Contains(metamorphs!, m => m?["actorId"]?.GetValue<string>() == helloWorldId);
}
}
4 changes: 2 additions & 2 deletions tests/Apify.Client.Tests/Unit/ModelAccessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace Apify.Client.Tests.Unit;

/// <summary>
/// The typed accessors for fields the OpenAPI specification added to the build, run, storage, webhook, schedule
/// and request models (spec v2-2026-11-09T143926Z).
/// The typed accessors for fields the OpenAPI specification added to the build, run, storage, webhook, schedule,
/// and request models.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModelAccessorTests
Expand Down
11 changes: 8 additions & 3 deletions tests/Apify.Client.Tests/Unit/ResponseDecompressionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,14 @@ public async Task WaitForResponseWrittenAsync()
return;
}

var finished = await Task.WhenAny(_serveTask, Task.Delay(WriteTimeout)).ConfigureAwait(false);
Assert.True(finished == _serveTask, "loopback server did not finish writing the response in time");
await _serveTask.ConfigureAwait(false); // rethrows any server-side failure
try
{
await _serveTask.WaitAsync(WriteTimeout).ConfigureAwait(false); // rethrows any server-side failure
}
catch (TimeoutException)
{
Assert.Fail("loopback server did not finish writing the response in time");
}
}

public void Dispose() => _listener.Close();
Expand Down
Loading
Loading