-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathrun.ts
More file actions
569 lines (524 loc) · 20.1 KB
/
Copy pathrun.ts
File metadata and controls
569 lines (524 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import type { AxiosRequestConfig } from 'axios';
import { z } from 'zod';
import type { RUN_GENERAL_ACCESS } from '@apify/consts';
import { LEVELS, Log } from '@apify/log';
import type { ApiClientOptionsWithOptionalResourcePath } from '../base/api_client.js';
import { ResourceClient } from '../base/resource_client.js';
import type { ApifyResponse } from '../http_client.js';
import * as schemas from '../schemas.js';
import { anyObjectSchema, isNode, parseArgument, parseResponse } from '../utils.js';
import type { ActorInput, ActorRun } from './actor.js';
import { DatasetClient } from './dataset.js';
import { KeyValueStoreClient } from './key_value_store.js';
import { LogClient, LoggerActorRedirect, StreamedLog } from './log.js';
import { RequestQueueClient } from './request_queue.js';
const RUN_CHARGE_IDEMPOTENCY_HEADER = 'idempotency-key';
const getOptionsSchema = z.strictObject({ waitForFinish: z.number().optional() });
const abortOptionsSchema = z.strictObject({ gracefully: z.boolean().optional() });
const targetActorIdSchema = z.string();
const metamorphOptionsSchema = z.strictObject({
contentType: z.string().optional(),
build: z.string().optional(),
});
const resurrectOptionsSchema = z.strictObject({
build: z.string().optional(),
memory: z.number().optional(),
timeout: z.number().optional(),
maxItems: z.number().optional(),
maxTotalChargeUsd: z.number().optional(),
restartOnError: z.boolean().optional(),
});
const chargeOptionsSchema = z.strictObject({
eventName: z.string(),
count: z.number().default(1),
idempotencyKey: z.string().optional(),
});
const waitForFinishOptionsSchema = z.strictObject({ waitSecs: z.number().optional() });
/**
* Client for managing a specific Actor run.
*
* Provides methods to get run details, abort, metamorph, resurrect, wait for completion,
* and access the run's dataset, key-value store, request queue, and logs.
*
* @example
* ```javascript
* const client = new ApifyClient({ token: 'my-token' });
* const runClient = client.run('my-run-id');
*
* // Get run details
* const run = await runClient.get();
*
* // Wait for the run to finish
* const finishedRun = await runClient.waitForFinish();
*
* // Access the run's dataset
* const { items } = await runClient.dataset().listItems();
* ```
*
* @see https://docs.apify.com/platform/actors/running/runs-and-builds
*/
export class RunClient extends ResourceClient {
/**
* @hidden
*/
constructor(options: ApiClientOptionsWithOptionalResourcePath) {
super({
...options,
resourcePath: options.resourcePath || 'actor-runs',
});
}
/**
* Gets the Actor run object from the Apify API.
*
* @param options - Get options
* @param options.waitForFinish - Maximum time to wait (in seconds, max 60s) for the run to finish on the API side before returning. Default is 0 (returns immediately).
* @returns The ActorRun object, or `undefined` if it does not exist
* @see https://docs.apify.com/api/v2/actor-run-get
*
* @example
* ```javascript
* // Get run status immediately
* const run = await client.run('run-id').get();
* console.log(`Status: ${run.status}`);
*
* // Wait up to 60 seconds for run to finish
* const run = await client.run('run-id').get({ waitForFinish: 60 });
* ```
*/
async get(options: RunGetOptions = {}): Promise<ActorRun | undefined> {
const parsed = parseArgument(options, getOptionsSchema, 'RunGetOptions');
return this._get(schemas.Run(), parsed);
}
/**
* Aborts the Actor run.
*
* @param options - Abort options
* @param options.gracefully - If `true`, the Actor run will abort gracefully - it can send status messages and perform cleanup. Default is `false` (immediate abort).
* @returns The updated ActorRun object with `ABORTING` or `ABORTED` status
* @see https://docs.apify.com/api/v2/actor-run-abort-post
*
* @example
* ```javascript
* // Abort immediately
* await client.run('run-id').abort();
*
* // Abort gracefully (allows cleanup)
* await client.run('run-id').abort({ gracefully: true });
* ```
*/
async abort(options: RunAbortOptions = {}): Promise<ActorRun> {
const parsed = parseArgument(options, abortOptionsSchema, 'RunAbortOptions');
const response = await this.httpClient.call({
url: this._url('abort'),
method: 'POST',
params: this._params(parsed),
});
return parseResponse(response, schemas.Run());
}
/**
* Deletes the Actor run.
*
* @see https://docs.apify.com/api/v2/actor-run-delete
* @since Added in 2.8.1
*/
async delete(): Promise<void> {
return this._delete();
}
/**
* Transforms the Actor run into a run of another Actor (metamorph).
*
* This operation preserves the run ID, storages (dataset, key-value store, request queue),
* and resource allocation. The run effectively becomes a run of the target Actor with new input.
* This is useful for chaining Actor executions or implementing complex workflows.
*
* @param targetActorId - ID or username/name of the target Actor
* @param input - Input for the target Actor, serialized to JSON. Omit it to metamorph without input.
* @param options - Metamorph options
* @param options.build - Tag or number of the target Actor's build to run. Default is the target Actor's default build.
* @returns The metamorphed ActorRun object (same ID, but now running the target Actor)
* @see https://docs.apify.com/api/v2/actor-run-metamorph-post
*
* @example
* ```javascript
* // Transform current run into another Actor
* const metamorphedRun = await client.run('original-run-id').metamorph(
* 'target-actor-id',
* { url: 'https://example.com' }
* );
* console.log(`Run ${metamorphedRun.id} is now running ${metamorphedRun.actId}`);
* ```
*/
async metamorph(targetActorId: string, input?: ActorInput, options: RunMetamorphOptions = {}): Promise<ActorRun> {
parseArgument(targetActorId, targetActorIdSchema);
const parsed = parseArgument(options, metamorphOptionsSchema, 'RunMetamorphOptions');
const safeTargetActorId = this._toSafeId(targetActorId);
const params = {
targetActorId: safeTargetActorId,
build: parsed.build,
};
const request: AxiosRequestConfig = {
url: this._url('metamorph'),
method: 'POST',
data: input,
params: this._params(params),
// Apify internal property. Tells the request serialization interceptor
// to stringify functions to JSON, instead of omitting them.
// TODO: remove this ts-expect-error once we have defined custom Apify axios configs
// @ts-expect-error Custom Apify property
stringifyFunctions: true,
};
if (parsed.contentType) {
request.headers = {
'content-type': parsed.contentType,
};
}
const response = await this.httpClient.call(request);
return parseResponse(response, schemas.Run());
}
/**
* Reboots the Actor run.
*
* Rebooting restarts the Actor's Docker container while preserving the run ID and storages.
* This can be useful to recover from certain errors or to force the Actor to restart
* with a fresh environment.
*
* @returns The updated ActorRun object
* @see https://docs.apify.com/api/v2/actor-run-reboot-post
*
* @example
* ```javascript
* const run = await client.run('run-id').reboot();
* ```
* @since Added in 2.8.0
*/
async reboot(): Promise<ActorRun> {
const request: AxiosRequestConfig = {
url: this._url('reboot'),
method: 'POST',
};
const response = await this.httpClient.call(request);
return parseResponse(response, schemas.Run());
}
/**
* Updates the Actor run with specified fields.
*
* @param newFields - Fields to update
* @param newFields.statusMessage - Custom status message to display (e.g., "Processing page 10/100")
* @param newFields.isStatusMessageTerminal - If `true`, the status message is final and won't be overwritten. Default is `false`.
* @param newFields.generalAccess - General resource access level ('FOLLOW_USER_SETTING', 'ANYONE_WITH_ID_CAN_READ' or 'RESTRICTED')
* @returns The updated ActorRun object
*
* @example
* ```javascript
* // Set a status message
* await client.run('run-id').update({
* statusMessage: 'Processing items: 50/100'
* });
* ```
* @since Added in 2.6.0
*/
async update(newFields: RunUpdateOptions): Promise<ActorRun> {
parseArgument(newFields, anyObjectSchema);
return this._update(schemas.Run(), newFields);
}
/**
* Resurrects a finished Actor run, starting it again with the same settings.
*
* This creates a new run with the same configuration as the original run. The original
* run's storages (dataset, key-value store, request queue) are preserved and reused.
*
* @param options - Resurrection options (override original run settings)
* @param options.build - Tag or number of the build to use. If not provided, uses the original run's build.
* @param options.memory - Memory in megabytes. If not provided, uses the original run's memory.
* @param options.timeout - Timeout in seconds. If not provided, uses the original run's timeout.
* @param options.maxItems - Maximum number of dataset items (pay-per-result Actors).
* @param options.maxTotalChargeUsd - Maximum cost in USD (pay-per-event Actors).
* @param options.restartOnError - Whether to restart on error.
* @returns The new (resurrected) ActorRun object
* @see https://docs.apify.com/api/v2/post-resurrect-run
*
* @example
* ```javascript
* // Resurrect a failed run with more memory
* const newRun = await client.run('failed-run-id').resurrect({ memory: 2048 });
* console.log(`New run started: ${newRun.id}`);
* ```
*/
async resurrect(options: RunResurrectOptions = {}): Promise<ActorRun> {
const parsed = parseArgument(options, resurrectOptionsSchema, 'RunResurrectOptions');
const response = await this.httpClient.call({
url: this._url('resurrect'),
method: 'POST',
params: this._params(parsed),
});
return parseResponse(response, schemas.Run());
}
/**
* Charges the Actor run for a specific event.
*
* @param options - Charge options including event name and count.
* @param options.eventName - **Required.** Name of the event to charge for.
* @param options.count - Number of times to charge the event. Default is 1.
* @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
* @returns Empty response object.
* @see https://docs.apify.com/api/v2/post-charge-run
* @since Added in 2.11.0
*/
async charge(options: RunChargeOptions): Promise<ApifyResponse<Record<string, never>>> {
const {
eventName,
count,
idempotencyKey: providedIdempotencyKey,
} = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
/** To avoid duplicates during the same milisecond, doesn't need to by crypto-secure. */
const randomSuffix = (Math.random() + 1).toString(36).slice(3, 8);
const idempotencyKey = providedIdempotencyKey ?? `${this.id}-${eventName}-${Date.now()}-${randomSuffix}`;
const request: AxiosRequestConfig = {
url: this._url('charge'),
method: 'POST',
data: {
eventName,
count,
},
headers: {
[RUN_CHARGE_IDEMPOTENCY_HEADER]: idempotencyKey,
},
};
const response = await this.httpClient.call(request);
return response;
}
/**
* Waits for the Actor run to finish and returns the finished Run object.
*
* The promise resolves when the run reaches a terminal state (`SUCCEEDED`, `FAILED`, `ABORTED`, or `TIMED-OUT`).
* If `waitSecs` is provided and the timeout is reached, the promise resolves with the unfinished
* Run object (status will be `RUNNING` or `READY`). The promise is NOT rejected based on run status.
*
* Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
* by polling the run status. It uses the `waitForFinish` parameter internally (max 60s per call)
* and continuously polls until the run finishes or the timeout is reached.
*
* @param options - Wait options
* @param options.waitSecs - Maximum time to wait for the run to finish, in seconds. If the limit is reached, the returned promise resolves to a run object that will have status `READY` or `RUNNING`. If omitted, waits indefinitely.
* @returns The ActorRun object (finished or still running if timeout was reached)
*
* @example
* ```javascript
* // Wait indefinitely for run to finish
* const run = await client.run('run-id').waitForFinish();
* console.log(`Run finished with status: ${run.status}`);
*
* // Wait up to 5 minutes
* const run = await client.run('run-id').waitForFinish({ waitSecs: 300 });
* if (run.status === 'SUCCEEDED') {
* console.log('Run succeeded!');
* }
* ```
*/
async waitForFinish(options: RunWaitForFinishOptions = {}): Promise<ActorRun> {
const parsed = parseArgument(options, waitForFinishOptionsSchema, 'RunWaitForFinishOptions');
return this._waitForFinish(schemas.Run(), parsed);
}
/**
* Returns a client for the default dataset of this Actor run.
*
* A 404 from this client throws an `ApifyApiError`, since the run itself may be what is missing.
*
* @returns A client for accessing the run's default dataset
* @see https://docs.apify.com/api/v2/actor-run-get
*
* @example
* ```javascript
* // Access run's dataset
* const { items } = await client.run('run-id').dataset().listItems();
* ```
*/
dataset(): DatasetClient {
return new DatasetClient(
this._subResourceOptions({
resourcePath: 'dataset',
}),
);
}
/**
* Returns a client for the default key-value store of this Actor run.
*
* `get()` and `delete()` throw an `ApifyApiError` on a 404, since the run itself may be what is missing. Record
* lookups such as `getRecord()` read a 404 as a missing record.
*
* @returns A client for accessing the run's default key-value store
* @see https://docs.apify.com/api/v2/actor-run-get
*
* @example
* ```javascript
* // Access run's key-value store
* const output = await client.run('run-id').keyValueStore().getRecord('OUTPUT');
* ```
*/
keyValueStore(): KeyValueStoreClient {
return new KeyValueStoreClient(
this._subResourceOptions({
resourcePath: 'key-value-store',
}),
);
}
/**
* Returns a client for the default Request queue of this Actor run.
*
* `get()` and `delete()` throw an `ApifyApiError` on a 404, since the run itself may be what is missing.
* `getRequest()` reads a 404 as a missing request.
*
* @returns A client for accessing the run's default Request queue
* @see https://docs.apify.com/api/v2/actor-run-get
*
* @example
* ```javascript
* // Access run's Request queue
* const { items } = await client.run('run-id').requestQueue().listHead();
* ```
*/
requestQueue(): RequestQueueClient {
return new RequestQueueClient(
this._subResourceOptions({
resourcePath: 'request-queue',
}),
);
}
/**
* Returns a client for accessing the log of this Actor run.
*
* A 404 from this client throws an `ApifyApiError`, since the run itself may be what is missing.
*
* @returns A client for accessing the run's log
* @see https://docs.apify.com/api/v2/actor-run-get
*
* @example
* ```javascript
* // Get run log
* const log = await client.run('run-id').log().get();
* console.log(log);
* ```
*/
log(): LogClient {
return new LogClient(
this._subResourceOptions({
resourcePath: 'log',
}),
);
}
/**
* Get StreamedLog for convenient streaming of the run log and their redirection.
* @since Added in 2.20.0
*/
async getStreamedLog(options: GetStreamedLogOptions = {}): Promise<StreamedLog | undefined> {
const { fromStart = true } = options;
let { toLog } = options;
if (toLog === null || !isNode()) {
// Explicitly no logging or not in Node.js
return undefined;
}
if (toLog === undefined || toLog === 'default') {
// Create default StreamedLog
// Get actor name and run id
const runData = await this.get();
const runId = runData?.id ?? '';
const actorId = runData?.actId ?? '';
// `apifyClient.actor()` rejects an empty ID, which is what a run that could not be read leaves here.
const actorData = actorId ? await this.apifyClient.actor(actorId).get() : undefined;
const actorName = actorData?.name ?? '';
const name = [actorName, `runId:${runId}`].filter(Boolean).join(' ');
toLog = new Log({ level: LEVELS.DEBUG, prefix: `${name} -> `, logger: new LoggerActorRedirect() });
}
return new StreamedLog({ logClient: this.log(), toLog, fromStart });
}
}
/**
* Options for getting a streamed log.
* @since Added in 2.20.0
*/
export interface GetStreamedLogOptions {
toLog?: Log | null | 'default';
fromStart?: boolean;
}
/**
* Options for getting a Run.
*/
export interface RunGetOptions {
waitForFinish?: number;
}
/**
* Options for aborting a Run.
*/
export interface RunAbortOptions {
gracefully?: boolean;
}
/**
* Options for metamorphing a Run into another Actor.
*/
export interface RunMetamorphOptions {
/**
* Content type of the request body, which becomes the content type of the run's `INPUT` record.
* Without it, an input is serialized to JSON and sent as `application/json`. Pairing an object
* with `application/x-www-form-urlencoded` form-encodes it instead.
*/
contentType?: string;
build?: string;
}
/**
* Options for updating a Run.
* @since Added in 2.6.0
*/
export interface RunUpdateOptions {
statusMessage?: string;
/**
* @since Added in 2.6.3
*/
isStatusMessageTerminal?: boolean;
/**
* @since Added in 2.12.2
*/
generalAccess?: RUN_GENERAL_ACCESS | null;
}
/**
* Options for resurrecting a finished Run.
*/
export interface RunResurrectOptions {
build?: string;
memory?: number;
timeout?: number;
/**
* @since Added in 2.12.1
*/
maxItems?: number;
/**
* @since Added in 2.12.1
*/
maxTotalChargeUsd?: number;
/**
* @since Added in 2.19.0
*/
restartOnError?: boolean;
}
/**
* Options for charging events in a pay-per-event Actor run.
* @since Added in 2.11.0
*/
export interface RunChargeOptions {
/** Name of the event to charge. Must be defined in the Actor's pricing info else the API will throw. */
eventName: string;
/** Defaults to 1 */
count?: number;
/** Defaults to runId-eventName-timestamp */
idempotencyKey?: string;
}
/**
* Options for waiting for a Run to finish.
*/
export interface RunWaitForFinishOptions {
/**
* Maximum time to wait for the run to finish, in seconds.
* If the limit is reached, the returned promise is resolved to a run object that will have
* status `READY` or `RUNNING`. If `waitSecs` omitted, the function waits indefinitely.
*/
waitSecs?: number;
}