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
2 changes: 1 addition & 1 deletion docs/02_concepts/05_logging.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ An HTTP client you plug in with <ApiLink to="class/ApifyClient#withCustomHttpCli

## Redirecting Actor run logs

In Node.js, <ApiLink to="class/ActorClient#call">`ActorClient.call()`</ApiLink> redirects the log of the run it starts to your process while it waits for the run to finish. The redirected lines carry a prefix with the Actor name and the run ID. The `log` option of `call()` changes where they go:
In Node.js, <ApiLink to="class/ActorClient#call">`ActorClient.call()`</ApiLink> and <ApiLink to="class/TaskClient#call">`TaskClient.call()`</ApiLink> redirect the log of the run they start to your process while they wait for the run to finish. The redirected lines carry a prefix with the Actor name and the run ID. The `log` option of `call()` changes where they go:

- A `Log` instance of `@apify/log` receives the redirected lines.
- `null` turns the redirection off.
Expand Down
11 changes: 11 additions & 0 deletions docs/04_upgrading/upgrading_to_v3.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,17 @@ Dropping the `contentType` sends the body as JSON, so the run's `INPUT` record c

Nothing changes at runtime. `TaskClient.start()` and `call()` keep taking a `Dictionary`: a task's input overrides are merged into the input saved on the task, so they are always an object.

## `TaskClient.call()` redirects the run log

In Node.js, <ApiLink to="class/TaskClient#call">`TaskClient.call()`</ApiLink> now redirects the log of the run it starts to your process while it waits, the way <ApiLink to="class/ActorClient#call">`ActorClient.call()`</ApiLink> has done since v2.20.0. It takes the same `log` option. Pass `null` to keep the run log out of your output:

```diff
- await client.task('my-task').call(); // v2
+ await client.task('my-task').call(undefined, { log: null }); // v3
```

For both methods, a failure to set the redirection up no longer rejects `call()`. The run has already started by then, so `call()` logs a warning and waits for the run without redirecting its log. In v2, `ActorClient.call()` rejected with the error of the failed request.

## Proxies are opt-in

In v2 the client read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables on its own, through the `proxy-agent` package. v3 sends its requests through the `fetch` of the runtime and no longer depends on `proxy-agent`, so in Node.js a proxy applies only when Node.js itself is told to read those variables. Start it with `NODE_USE_ENV_PROXY=1`, which Node.js 22.21 and 24 and newer support (the `--use-env-proxy` flag does the same on 22.21 and on 24.5 and newer):
Expand Down
1 change: 1 addition & 0 deletions docs/public-api/apify-client.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4279,6 +4279,7 @@ export interface Task extends Omit<Schemas['Task'], keyof TaskRePointed>, TaskRe

// @public
export interface TaskCallOptions extends Omit<TaskStartOptions, 'waitForFinish'> {
log?: Log | null | 'default';
// (undocumented)
waitSecs?: number;
}
Expand Down
10 changes: 2 additions & 8 deletions src/resource_clients/actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { Dictionary } from '../utils.js';
import * as schemas from '../schemas.js';
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
import { anyObjectSchema, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
import { waitForFinishWithLog } from '../wait_for_finish_with_log.js';
import { startWaitingForResources } from '../wait_for_resources.js';
import { ActorServerClient } from './actor_server.js';
import { ActorVersionClient } from './actor_version.js';
Expand Down Expand Up @@ -324,14 +325,7 @@ export class ActorClient extends ResourceClient {
// setting it up as a nested route under actor API.
const newRunClient = this.apifyClient.run(id);

const streamedLog = await newRunClient.getStreamedLog({ toLog: log, signal });
streamedLog?.start();
return this.apifyClient
.run(id)
.waitForFinish({ waitSecs, timeoutSecs, signal })
.finally(async () => {
await streamedLog?.stop();
});
return waitForFinishWithLog(newRunClient, { log, waitSecs, timeoutSecs, signal });
}

/**
Expand Down
19 changes: 16 additions & 3 deletions src/resource_clients/task.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { z } from 'zod';

import { ACT_JOB_STATUSES, META_ORIGINS } from '@apify/consts';
import { Log } from '@apify/log';

import type { ApiClientSubResourceOptions } from '../base/api_client.js';
import { ResourceClient } from '../base/resource_client.js';
Expand All @@ -18,6 +19,7 @@ import {
parseResponse,
stringifyWebhooksToBase64,
} from '../utils.js';
import { waitForFinishWithLog } from '../wait_for_finish_with_log.js';
import { startWaitingForResources } from '../wait_for_resources.js';
import type { ActorLastRunOptions, ActorStartOptions, Run } from './actor.js';
import { RunClient } from './run.js';
Expand Down Expand Up @@ -45,6 +47,7 @@ const callOptionsSchema = z.strictObject({
webhooks: z.array(anyObjectSchema).optional(),
maxItems: z.number().min(0).optional(),
maxTotalChargeUsd: z.number().min(0).optional(),
log: z.union([z.null(), z.instanceof(Log), z.literal('default')]).optional(),
restartOnError: z.boolean().optional(),
waitForResources: z.union([z.boolean(), z.number().min(0)]).optional(),
...timeoutOptionsShape,
Expand Down Expand Up @@ -241,14 +244,16 @@ export class TaskClient extends ResourceClient {

/**
* Starts a task and waits for it to finish before returning the Run object.
* It waits indefinitely, unless the `waitSecs` option is provided.
* It waits indefinitely, unless the `waitSecs` option is provided. In Node.js, it redirects the log of the run
* to the console or a custom `Log` instance while it waits.
*
* @param input - Input overrides for the task. If not provided, the task's saved input is used.
* @param options - Run and wait options.
* @param options.build - Tag or number of the Actor build to run.
* @param options.memory - Memory in megabytes allocated for the run.
* @param options.runTimeoutSecs - Timeout for the run in seconds.
* @param options.waitSecs - Maximum time to wait for the run to finish, in seconds. If omitted, waits indefinitely.
* @param options.log - Log instance for streaming run logs. Use `'default'` for console output, `null` to disable logging, or provide a custom Log instance.
* @param options.webhooks - Webhooks to trigger for specific Actor run events.
* @param options.maxItems - Maximum number of dataset items (for pay-per-result Actors).
* @param options.maxTotalChargeUsd - Maximum cost in USD (for pay-per-event Actors).
Expand All @@ -264,14 +269,16 @@ export class TaskClient extends ResourceClient {
parseArgument(input, inputSchema);
const parsed = parseArgument(options, callOptionsSchema, 'TaskCallOptions');

const { waitSecs, timeoutSecs = 'noTimeout', signal, ...startOptions } = parsed;
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = parsed;

const { id } = await this.start(input, { ...startOptions, timeoutSecs, signal });

// Calling root client because we need access to top level API.
// Creating a new instance of RunClient here would only allow
// setting it up as a nested route under task API.
return this.apifyClient.run(id).waitForFinish({ waitSecs, timeoutSecs, signal });
const newRunClient = this.apifyClient.run(id);

return waitForFinishWithLog(newRunClient, { log, waitSecs, timeoutSecs, signal });
}

/**
Expand Down Expand Up @@ -395,4 +402,10 @@ export type TaskStartOptions = Omit<ActorStartOptions, 'contentType' | 'forcePer
*/
export interface TaskCallOptions extends Omit<TaskStartOptions, 'waitForFinish'> {
waitSecs?: number;
/**
* `Log` instance that should be used to redirect Actor run logs to.
* If `undefined` or `'default'` the pre-defined `Log` will be created and used.
* If `null`, no log redirection will occur.
*/
log?: Log | null | 'default';
}
39 changes: 39 additions & 0 deletions src/wait_for_finish_with_log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { Log } from '@apify/log';

import type { Run } from './resource_clients/actor.js';
import type { StreamedLog } from './resource_clients/log.js';
import type { RunClient, RunWaitForFinishOptions } from './resource_clients/run.js';

/**
* Waits for the run to finish and redirects its log to `log` meanwhile, the way `call()` of an Actor or a task does.
* `'default'` or no value redirects to a `Log` prefixed with the Actor name and the run ID, and `null` waits without
* any redirection. A failure to set the redirection up never fails the wait, since the run has already started and
* the caller has to get it: the run is then waited for without the redirection.
* @internal
*/
export async function waitForFinishWithLog(
runClient: RunClient,
options: RunWaitForFinishOptions & { log?: Log | null | 'default' },
): Promise<Run> {
const { log, ...waitOptions } = options;
const { signal } = waitOptions;

let streamedLog: StreamedLog | undefined;
try {
streamedLog = await runClient.getStreamedLog({ toLog: log, signal });
} catch (err) {
// An aborted call rejects with the reason of its signal, which the wait below takes care of.
if (!signal?.aborted) {
const { message, cause } = err as Error;
const causedBy = cause instanceof Error ? ` (${cause.message})` : '';
runClient.httpClient.logger.warning(
`Waiting for run ${runClient.id} without log redirection, which could not be set up: ${message}${causedBy}`,
);
}
}

streamedLog?.start();
return runClient.waitForFinish(waitOptions).finally(async () => {
await streamedLog?.stop();
});
}
2 changes: 1 addition & 1 deletion test/abort_signal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('AbortSignal in resource-client methods', () => {
},
{
name: 'TaskClient',
call: (c: ApifyClient, signal: AbortSignal) => c.task('task-id').call(undefined, { signal }),
call: (c: ApifyClient, signal: AbortSignal) => c.task('task-id').call(undefined, { log: null, signal }),
startPath: 'POST /v2/actor-tasks/task-id/runs',
},
])('call() of $name stops polling the run and rejects with the reason', async ({ call, startPath }) => {
Expand Down
75 changes: 75 additions & 0 deletions test/actors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,10 @@ describe('Run actor with redirected logs', () => {
const statusGenerator = new StatusGenerator();
// Streamed log requests left to answer with an empty body, the way the API answers before a run has logged anything.
let emptyLogStreams = 0;
// Reads of the Actor left to reject, which is what makes setting the log redirection up fail.
let rejectedActorReads = 0;
// Reads of the Actor left to break off, with no response at all.
let brokenActorReads = 0;

beforeAll(async () => {
// Use custom router for the tests
Expand All @@ -1109,6 +1113,21 @@ describe('Run actor with redirected logs', () => {
}
next();
});
router.get('/actors/redirect-actor-id', (req, res, next) => {
if (brokenActorReads > 0) {
brokenActorReads -= 1;
req.socket.destroy();
return;
}
if (rejectedActorReads > 0) {
rejectedActorReads -= 1;
res.status(403).json({
error: { type: 'insufficient-permissions', message: 'Insufficient permissions.' },
});
return;
}
next();
});
// Set up a status generator to simulate run status changes. It will be reset for each test.
router.get('/actor-runs/redirect-run-id', async (_, res) => {
// Delay the response to give the actor time to run and produce expected logs
Expand Down Expand Up @@ -1139,6 +1158,8 @@ describe('Run actor with redirected logs', () => {
// Reset the generator to so that the next test starts fresh
statusGenerator.reset();
emptyLogStreams = 0;
rejectedActorReads = 0;
brokenActorReads = 0;
client = null as unknown as ApifyClient;
});

Expand Down Expand Up @@ -1184,6 +1205,60 @@ describe('Run actor with redirected logs', () => {
});
});

describe('task.call - redirected logs', () => {
test.each(testCases)('logOptions:$logOptions', async ({ expectedPrefix, logOptions }) => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});

await client.task('redirect-task-id').call(undefined, logOptions);

expect(logSpy.mock.calls).toEqual(MOCKED_ACTOR_LOGS_PROCESSED.map((item) => [expectedPrefix + item]));
logSpy.mockRestore();
});

test('logOptions:{ "log": null }', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});

await client.task('redirect-task-id').call(undefined, { log: null });

expect(logSpy.mock.calls).toEqual([]);
logSpy.mockRestore();
});
});

describe('call - log redirection that cannot be set up', () => {
test.each([
{ name: 'actor.call', call: async () => client.actor('redirect-actor-id').call() },
{ name: 'task.call', call: async () => client.task('redirect-task-id').call() },
])('$name waits for the run without redirecting its log', async ({ call }) => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const warningSpy = vi.spyOn(client.httpClient.logger, 'warning').mockImplementation(() => {});
rejectedActorReads = 1;

const run = await call();

expect(run).toMatchObject({ id: 'redirect-run-id', status: 'SUCCEEDED' });
expect(logSpy).not.toHaveBeenCalled();
expect(warningSpy).toHaveBeenCalledExactlyOnceWith(
'Waiting for run redirect-run-id without log redirection, which could not be set up: Insufficient permissions.',
);
logSpy.mockRestore();
warningSpy.mockRestore();
});

test('the warning names the cause of a network failure', async () => {
const warningSpy = vi.spyOn(client.httpClient.logger, 'warning').mockImplementation(() => {});
brokenActorReads = 1;

const run = await client.task('redirect-task-id').call();

expect(run).toMatchObject({ id: 'redirect-run-id', status: 'SUCCEEDED' });
expect(warningSpy).toHaveBeenCalledExactlyOnceWith(
expect.stringMatching(/^Waiting for run redirect-run-id without log redirection, .+: \S/),
);
warningSpy.mockRestore();
});
});

describe('run.getStreamedLog - empty log stream', () => {
test('reopens the log stream when the first one is empty', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
Expand Down
2 changes: 1 addition & 1 deletion test/client_timeouts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ const TIMEOUT_CASES: TimeoutCase[] = [
{ client: 'TaskClient', method: 'unpublish', tier: 'short' },
{ client: 'TaskClient', method: 'delete', tier: 'short' },
{ client: 'TaskClient', method: 'start', tier: 'medium', args: [undefined] },
{ client: 'TaskClient', method: 'call', tier: 'noTimeout', args: [undefined] },
{ client: 'TaskClient', method: 'call', tier: 'noTimeout', args: [undefined], options: { log: null } },
{ client: 'TaskClient', method: 'getInput', tier: 'short' },
{ client: 'TaskClient', method: 'updateInput', tier: 'short', args: [{ x: 1 }] },
{ client: 'TaskCollectionClient', method: 'list', tier: 'medium' },
Expand Down
3 changes: 3 additions & 0 deletions test/mock_server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ export function createDefaultApp(v2Router = express.Router()) {
v2Router.post('/actors/redirect-actor-id/runs', async (_, res) => {
res.json({ data: { ...fixtures.run, id: 'redirect-run-id', actId: 'redirect-actor-id' } });
});
v2Router.post('/actor-tasks/redirect-task-id/runs', async (_, res) => {
res.json({ data: { ...fixtures.run, id: 'redirect-run-id', actId: 'redirect-actor-id' } });
});
v2Router.use('/actors', actors);
v2Router.use('/actor-builds', builds);
v2Router.use('/actor-runs/redirect-run-id/log', streamLogChunks);
Expand Down
2 changes: 2 additions & 0 deletions test/tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ describe('Task methods', () => {
runTimeoutSecs,
build,
waitSecs,
log: null,
});
expect(res).toMatchObject({ id: runId, actId, status: 'SUCCEEDED' });
validateRequest({ query: { waitForFinish: waitSecs }, params: { runId } });
Expand Down Expand Up @@ -333,6 +334,7 @@ describe('Task methods', () => {
mockServer.setResponse({ body });
const res = await client.task(taskId).call(undefined, {
waitSecs,
log: null,
maxItems,
});
expect(res).toMatchObject({ id: runId, actId, status: 'SUCCEEDED' });
Expand Down
2 changes: 1 addition & 1 deletion test/wait_for_resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const STARTERS: { name: string; start: Starter; startPath: string }[] = [
},
{
name: 'TaskClient.call()',
start: async (c, options) => c.task('task-id').call(undefined, options),
start: async (c, options) => c.task('task-id').call(undefined, { log: null, ...options }),
startPath: 'POST /v2/actor-tasks/task-id/runs',
},
];
Expand Down
Loading