Skip to content

Commit 5fb376f

Browse files
JuanGalileametalwarrior665claude
authored
feat: target standby builds directly with X-Actor-Build (#233)
clanked it out from the phone when i heard about the adhoc deployments thing. seems reasonable but reading diffs from phone is hard. feel free to roast me if its sloppy xd Standby tests now send requests directly to the Actor's standby URL and use `X-Actor-Build` to select the build from `ACTOR_BUILDS`, falling back to the configured standby build. This removes temporary task creation and cleanup while preserving the `callStandby({ input, path, headers })` API. Uses the platform support introduced in apify/actor-standby-controller#461. Task-based run-link annotations are removed because direct Actor requests can share standby runs. The library documentation and unit tests cover the new behavior, including build numbers and labels, defaults, header handling, and request failures. Validation: build, type-check, lint, formatting, and the full local test suite passed (486 tests passed; 2 existing skips). Live Apify tests were not run because the sandbox token is not configured. --------- Co-authored-by: Lukáš Křivka <lukaskrivka@gmail.com> Co-authored-by: Claude <noreply@anthropic.com>
1 parent c681879 commit 5fb376f

5 files changed

Lines changed: 304 additions & 129 deletions

File tree

‎docs/lib.md‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -136,27 +136,30 @@ testActor(actorId, 'validate existing run', async ({ expect, run }) => {
136136

137137
## `testStandbyActor(actorId, testName, fn, options?)`
138138

139-
Same as `testActor`, for Actors in standby mode. It creates a temporary task with the build from `ACTOR_BUILDS` (or
140-
the Actor's standby build) and deletes it after the test. Instead of `run`, `fn` gets `callStandby`, which sends a
141-
`POST` request with `input` as the JSON body to the task's standby URL, plus `path`, and returns
142-
`{ data, status, headers }`, where `data` is the parsed JSON response. It gets `apifyClient` too.
143-
144-
Only the Actor's owner, or an account with write access to it, can start a standby Actor on a build other than its
145-
default one. The tests run with the owner's token by default; if you point `testTokenEnvVar` at another account, give
146-
it write access to the Actor.
139+
Same as `testActor`, for Actors in standby mode. Instead of `run`, `fn` gets `callStandby`, which sends a
140+
`POST` request with `input` as the JSON body directly to the Actor's standby URL, plus `path`. It sends
141+
`Content-Type: application/json` unless `headers` set another type. When `ACTOR_BUILDS` lists a build for the Actor,
142+
as on a PR, the request selects it with the `X-Actor-Build` header. Otherwise, as in the scheduled platform tests, it
143+
sends no header and the platform serves the Actor's configured standby build. No temporary tasks are created.
144+
It returns `{ data, body, status, headers }`, where `body` is the raw response text and `data` is `body` parsed as
145+
JSON, or `undefined` when the response isn't JSON, e.g. an HTML error page. Pass `body` as the message of the status
146+
assertion to see what came back when it fails. `fn` gets `apifyClient` too.
147+
148+
Only the Actor's owner, or an account with write access to it, can select a build with `X-Actor-Build`. The tests run
149+
with the owner's token by default; if you point `testTokenEnvVar` at another account, give it write access to the
150+
Actor, or its standby tests can only run on the default build.
147151

148152
```ts
149153
import { describe, testStandbyActor } from 'apify-test-tools';
150154

151155
describe('standby tests', () => {
152156
testStandbyActor(actorId, 'standby request', async ({ expect, callStandby }) => {
153-
const { data, status } = await callStandby({
157+
const { data, body, status } = await callStandby({
154158
input: { query: 'test' },
155159
path: '/search',
156-
headers: { 'Content-Type': 'application/json' },
157160
});
158161

159-
expect(status).toBe(200);
162+
expect(status, body).toBe(200);
160163
expect(data.results).toBeNonEmptyArray();
161164
});
162165
});

‎lib/lib.ts‎

Lines changed: 47 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Actor, ActorRun, ActorRunListItem, ActorStandby, Task } from 'apify-client';
1+
import type { Actor, ActorRun, ActorRunListItem } from 'apify-client';
22
import { ApifyClient } from 'apify-client';
33
import type { SuiteFactory, TestContext, TestFunction } from 'vitest';
44
import { describe as vitestDescribe, ExpectStatic, test as vitestTest } from 'vitest';
@@ -120,10 +120,8 @@ export const testActor = <T>(
120120
};
121121

122122
/**
123-
* This wrapper creates a new task with specific `build` of the standby actor and provides
124-
* `callStandby` function, which calls the task's `standbyUrl`.
125-
*
126-
* Using task is just current shortcoming of standby feature but ideally we would use Actor directly
123+
* Tests a standby Actor directly. A build listed in `ACTOR_BUILDS` is targeted with the X-Actor-Build header, otherwise
124+
* the platform serves the Actor's configured standby build.
127125
*
128126
* @param actorId - The actor's raw platform ID or its full name (`owner/name`, e.g. `"apify/web-scraper"`).
129127
*/
@@ -134,27 +132,14 @@ export const testStandbyActor = <I = any, O = any>(
134132
fn: TestFunction<{ callStandby: ReturnType<typeof createStartStandbyFn<I, O>>; apifyClient: ApifyClient }>,
135133
testOptions?: ActorTestOptions,
136134
) => {
137-
defineActorTest(actorId, testName, testOptions, async (context, name) => {
135+
defineActorTest(actorId, testName, testOptions, async (context) => {
138136
const apifyClient = getApifyClient(actorId);
139-
const standbyTask = await createStandbyTask(apifyClient, actorId, config.get(actorId)?.buildNumber);
140-
141-
// NOTE: we wrap `fn` in try/finally so cleanup (deleting the task) always runs afterwards
142-
try {
143-
await fn({
144-
...context,
145-
apifyClient,
146-
callStandby: createStartStandbyFn(apifyClient, standbyTask, context, name),
147-
});
148-
} finally {
149-
const { taskId } = standbyTask;
150-
// we want to delete the task at the end of the test
151-
await apifyClient
152-
.task(taskId)
153-
.delete()
154-
.catch((error) => {
155-
console.error(`Failed to delete standby task "${taskId}": ${error}`);
156-
});
157-
}
137+
const standbyActor = await getStandbyActor(apifyClient, actorId, config.get(actorId)?.buildNumber);
138+
await fn({
139+
...context,
140+
callStandby: createStartStandbyFn<I, O>({ ...standbyActor, apifyClient }),
141+
apifyClient,
142+
});
158143
});
159144
};
160145

@@ -177,124 +162,77 @@ export const testTestActor = <T>(
177162
export const it = testActor;
178163

179164
/**
180-
* Creates a function that accepts input for a standby actor and sends a request containing the input
181-
* to the task's standby url.
165+
* Sends JSON input directly to the Actor's standby URL, as `application/json` unless `headers` set another type.
166+
* Returns the raw response `body` too. `data` is the body parsed as JSON, or `undefined` when it isn't JSON (e.g. an
167+
* HTML error page), so a test can still assert the status and show what came back.
182168
*/
183-
const createStartStandbyFn = <I, O>(
184-
apifyClient: ApifyClient,
185-
standbyTask: StandbyTask,
186-
{ annotate }: TestContext,
187-
testName: string,
188-
) => {
189-
const { standbyUrl, taskId } = standbyTask;
190-
const annotatedRuns = new Set<string>();
191-
192-
// We annotate all the runs of the task, though it will be only one run
193-
// for most of the tests. To avoid annotating the same run multiple times
194-
// (in case the test calls the standby more than once), we use `annotatedRuns`
195-
// set to keep track of which runs have already been annotated.
196-
const annotateStandbyRuns = async () => {
197-
const runs = (await apifyClient.task(taskId).runs().list()).items;
198-
for (const run of runs) {
199-
if (!annotatedRuns.has(run.id)) {
200-
const runLink = generateRunLink(run);
201-
await annotate(`${testName} - ${runLink}`, 'run_link');
202-
}
203-
annotatedRuns.add(run.id);
204-
}
205-
};
206-
169+
const createStartStandbyFn = <I, O>({
170+
standbyUrl,
171+
build,
172+
apifyClient,
173+
}: StandbyActor & { apifyClient: ApifyClient }) => {
207174
return async ({
208175
input,
209176
path = '',
210177
headers = {},
211178
}: Pick<RunOptions<I>, 'input'> & { path?: string; headers?: Record<string, string> }) => {
179+
const requestHeaders = new Headers(headers);
180+
if (!requestHeaders.has('Content-Type')) {
181+
requestHeaders.set('Content-Type', 'application/json');
182+
}
183+
requestHeaders.set('Authorization', `Bearer ${apifyClient.token}`);
184+
if (build !== undefined) {
185+
requestHeaders.set('X-Actor-Build', build);
186+
}
212187
const response = await fetch(standbyUrl + path, {
213-
headers: {
214-
...headers,
215-
Authorization: `Bearer ${apifyClient.token}`,
216-
},
188+
headers: requestHeaders,
217189
method: 'POST',
218190
body: JSON.stringify(input),
219191
});
220192

221-
await annotateStandbyRuns();
222-
223-
const data = (await response.json()) as O;
193+
const body = await response.text();
194+
let data: O;
195+
try {
196+
data = JSON.parse(body) as O;
197+
} catch {
198+
data = undefined as O;
199+
}
224200
return {
225201
data,
202+
body,
226203
status: response.status,
227204
headers: response.headers,
228205
};
229206
};
230207
};
231208

232-
interface StandbyTask {
209+
interface StandbyActor {
233210
standbyUrl: string;
234-
taskId: string;
211+
build?: string;
235212
}
236213

237214
/**
238-
* Creates a task with specific `build` - either `buildNumber` or default.
239-
*
240-
* @throws if actor doesn't exist or it doesn't support standby mode.
215+
* Resolves the Actor's standby URL, and the build from `ACTOR_BUILDS` to target with `X-Actor-Build`. Without one, the
216+
* tests run on the Actor's default build, so no header is sent and the platform serves its configured standby build.
217+
* That keeps default-build runs working for testers without write access to the Actor.
241218
*/
242-
const createStandbyTask = async (
219+
const getStandbyActor = async (
243220
apifyClient: ApifyClient,
244221
actorId: string,
245222
buildNumber?: string,
246-
): Promise<StandbyTask> => {
247-
const actor = apifyClient.actor(actorId);
248-
249-
const actorInfo = (await actor.get()) as Actor & { standbyUrl?: string };
223+
): Promise<StandbyActor> => {
224+
const actorInfo = (await apifyClient.actor(actorId).get()) as (Actor & { standbyUrl?: string }) | undefined;
250225
if (!actorInfo) {
251226
throw new Error(`Actor "${actorId}" not found`);
252227
}
253-
254228
if (!actorInfo.standbyUrl) {
255229
throw new Error(`Actor "${actorId}" doesn't support standby mode`);
256230
}
257231

258-
if (!actorInfo.actorStandby) {
259-
throw new Error(`Actor "${actorId} doesn't contain actorStandby options`);
260-
}
261-
const { isEnabled, ...defaultActorStandby } = actorInfo.actorStandby;
262-
delete defaultActorStandby.disableStandbyFieldsOverride;
263-
264-
const build = buildNumber ?? defaultActorStandby.build;
265-
266-
const actorStandbyOptions: ActorStandby = {
267-
...defaultActorStandby,
268-
build,
232+
return {
233+
standbyUrl: actorInfo.standbyUrl,
234+
build: buildNumber,
269235
};
270-
271-
try {
272-
const title = `Test task - ${build}`.slice(0, 62);
273-
const randomValueLength = 15;
274-
// we try to create unique task name containing only `a-z0-9-` characters and at most 63 characters long
275-
const randomValue = Math.random().toString(10).slice(2).padEnd(randomValueLength, '0');
276-
const name = `test-${randomValue.slice(0, randomValueLength)}`;
277-
const newTask = (await apifyClient.tasks().create({
278-
actId: actorId,
279-
actorStandby: actorStandbyOptions,
280-
description: `Task for testing standby version ${build} of actor "${actorId}"`,
281-
title,
282-
name,
283-
})) as Task & { standbyUrl?: string };
284-
285-
const { id, standbyUrl } = newTask;
286-
287-
if (!standbyUrl) {
288-
throw new Error(`Task "${id} doesn't contain standbyUrl property`);
289-
}
290-
291-
return {
292-
standbyUrl,
293-
taskId: id,
294-
};
295-
} catch (error) {
296-
throw new Error(`Failed to create task: ${error}`);
297-
}
298236
};
299237

300238
const createStartRunFn = <T>(apifyClient: ApifyClient, actorId: string, testContext: TestContext) => {
@@ -350,4 +288,4 @@ const generateRunLink = (run: ActorRun | ActorRunListItem): string => {
350288

351289
/** Used for unit testing */
352290
// eslint-disable-next-line no-underscore-dangle
353-
export const _private = { createStartRunFn } as const;
291+
export const _private = { createStartRunFn, createStartStandbyFn, getStandbyActor } as const;

‎lib/types.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import type { ActorCallOptions } from 'apify-client';
22
import type { Assertion, TestOptions } from 'vitest';
33

44
export type ActorBuild = {
5-
buildId: string;
5+
/** Absent when testing the Actor's default build */
6+
buildId?: string;
67
actorRawId: string;
7-
buildNumber: string;
8+
/** Absent when testing the Actor's default build */
9+
buildNumber?: string;
810
actorFullName: string;
911
/** The env var holding the token the Actor's tests run with */
1012
testTokenEnvVar?: string;

0 commit comments

Comments
 (0)