diff --git a/docs/02_concepts/05_logging.mdx b/docs/02_concepts/05_logging.mdx index 1352484eb..3f837d75c 100644 --- a/docs/02_concepts/05_logging.mdx +++ b/docs/02_concepts/05_logging.mdx @@ -45,7 +45,7 @@ An HTTP client you plug in with `ActorClient.call()` 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, `ActorClient.call()` and `TaskClient.call()` 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. diff --git a/docs/04_upgrading/upgrading_to_v3.mdx b/docs/04_upgrading/upgrading_to_v3.mdx index b4b108e4e..af046b6bf 100644 --- a/docs/04_upgrading/upgrading_to_v3.mdx +++ b/docs/04_upgrading/upgrading_to_v3.mdx @@ -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, `TaskClient.call()` now redirects the log of the run it starts to your process while it waits, the way `ActorClient.call()` 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): diff --git a/docs/public-api/apify-client.api.md b/docs/public-api/apify-client.api.md index 7b2a29b99..000b50e99 100644 --- a/docs/public-api/apify-client.api.md +++ b/docs/public-api/apify-client.api.md @@ -4279,6 +4279,7 @@ export interface Task extends Omit, TaskRe // @public export interface TaskCallOptions extends Omit { + log?: Log | null | 'default'; // (undocumented) waitSecs?: number; } diff --git a/src/resource_clients/actor.ts b/src/resource_clients/actor.ts index cac4b5643..d7e9145b0 100644 --- a/src/resource_clients/actor.ts +++ b/src/resource_clients/actor.ts @@ -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'; @@ -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 }); } /** diff --git a/src/resource_clients/task.ts b/src/resource_clients/task.ts index 5a8ded811..e14813755 100644 --- a/src/resource_clients/task.ts +++ b/src/resource_clients/task.ts @@ -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'; @@ -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'; @@ -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, @@ -241,7 +244,8 @@ 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. @@ -249,6 +253,7 @@ export class TaskClient extends ResourceClient { * @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). @@ -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 }); } /** @@ -395,4 +402,10 @@ export type TaskStartOptions = Omit { 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'; } diff --git a/src/wait_for_finish_with_log.ts b/src/wait_for_finish_with_log.ts new file mode 100644 index 000000000..2576ae81f --- /dev/null +++ b/src/wait_for_finish_with_log.ts @@ -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 { + 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(); + }); +} diff --git a/test/abort_signal.test.ts b/test/abort_signal.test.ts index c4a106bed..65fa3aebe 100644 --- a/test/abort_signal.test.ts +++ b/test/abort_signal.test.ts @@ -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 }) => { diff --git a/test/actors.test.ts b/test/actors.test.ts index 82fa92586..09db47869 100644 --- a/test/actors.test.ts +++ b/test/actors.test.ts @@ -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 @@ -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 @@ -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; }); @@ -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(() => {}); diff --git a/test/client_timeouts.test.ts b/test/client_timeouts.test.ts index c3d2afc4c..905955576 100644 --- a/test/client_timeouts.test.ts +++ b/test/client_timeouts.test.ts @@ -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' }, diff --git a/test/mock_server/server.ts b/test/mock_server/server.ts index cd27e9e91..4e2dc7c84 100644 --- a/test/mock_server/server.ts +++ b/test/mock_server/server.ts @@ -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); diff --git a/test/tasks.test.ts b/test/tasks.test.ts index fe8e103bb..c5a7e0a16 100644 --- a/test/tasks.test.ts +++ b/test/tasks.test.ts @@ -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 } }); @@ -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' }); diff --git a/test/wait_for_resources.test.ts b/test/wait_for_resources.test.ts index c1ff5d108..7743ea7de 100644 --- a/test/wait_for_resources.test.ts +++ b/test/wait_for_resources.test.ts @@ -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', }, ];