apify 4.0.0-rc.0 → 4.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actor.d.ts +249 -164
- package/dist/actor.js +361 -179
- package/dist/apify_key_value_store_backend.js +1 -0
- package/dist/apify_request_queue_backend.d.ts +1 -1
- package/dist/apify_request_queue_backend.js +1 -1
- package/dist/apify_request_queue_shared_backend.d.ts +2 -2
- package/dist/apify_request_queue_shared_backend.js +4 -4
- package/dist/apify_storage_backend.js +7 -14
- package/dist/charging.d.ts +27 -6
- package/dist/charging.js +168 -62
- package/dist/charging_storage_backend.js +6 -2
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +20 -2
- package/dist/configuration.js +39 -2
- package/dist/errors.d.ts +2 -2
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/platform_event_manager.d.ts +22 -6
- package/dist/platform_event_manager.js +206 -36
- package/dist/proxy_configuration.js +6 -2
- package/dist/utils.d.ts +5 -3
- package/dist/utils.js +14 -13
- package/package.json +33 -35
package/dist/actor.js
CHANGED
|
@@ -5,7 +5,7 @@ import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultSt
|
|
|
5
5
|
import { sleep } from '@crawlee/utils';
|
|
6
6
|
import { ApifyClient } from 'apify-client';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS,
|
|
8
|
+
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, META_ORIGINS } from '@apify/consts';
|
|
9
9
|
import { decryptInputSecrets } from '@apify/input_secrets';
|
|
10
10
|
import log from '@apify/log';
|
|
11
11
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
@@ -14,13 +14,15 @@ import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backe
|
|
|
14
14
|
import { ApifyStorageBackend } from './apify_storage_backend.js';
|
|
15
15
|
import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
|
|
16
16
|
import { ChargingStorageBackend } from './charging_storage_backend.js';
|
|
17
|
+
import { ChildRunTracker } from './child_run_tracker.js';
|
|
17
18
|
import { Configuration } from './configuration.js';
|
|
18
19
|
import { ActorInputError } from './errors.js';
|
|
20
|
+
import { fixGoogleSheetsUrls } from './google_sheets.js';
|
|
19
21
|
import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
|
|
20
22
|
import { PlatformEventManager } from './platform_event_manager.js';
|
|
21
23
|
import { ProxyConfiguration } from './proxy_configuration.js';
|
|
22
24
|
import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
|
|
23
|
-
import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue,
|
|
25
|
+
import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, } from './utils.js';
|
|
24
26
|
/**
|
|
25
27
|
* {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
|
|
26
28
|
* JSON input reports where it came from.
|
|
@@ -52,6 +54,7 @@ export const EXIT_CODES = {
|
|
|
52
54
|
export class Actor {
|
|
53
55
|
/** @internal */
|
|
54
56
|
static #instance;
|
|
57
|
+
#childRunTracker;
|
|
55
58
|
/**
|
|
56
59
|
* Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
|
|
57
60
|
* @internal
|
|
@@ -93,10 +96,16 @@ export class Actor {
|
|
|
93
96
|
*/
|
|
94
97
|
#statusMessageForwarder;
|
|
95
98
|
#chargingManager;
|
|
99
|
+
#runPromise;
|
|
100
|
+
#actorPromise;
|
|
101
|
+
/** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
|
|
102
|
+
#abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
|
|
96
103
|
/** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
|
|
97
104
|
#requestQueueAccess = 'single';
|
|
98
105
|
/** Lazily built by the `#storageBackend` getter. */
|
|
99
106
|
#cachedStorageBackend;
|
|
107
|
+
/** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
|
|
108
|
+
#pendingListeners = [];
|
|
100
109
|
constructor(options = {}) {
|
|
101
110
|
const { configuration, ...configOptions } = options;
|
|
102
111
|
if (configuration) {
|
|
@@ -120,8 +129,11 @@ export class Actor {
|
|
|
120
129
|
this.configuration = new Configuration(configOptions);
|
|
121
130
|
}
|
|
122
131
|
this.apifyClient = this.newClient();
|
|
123
|
-
this.eventManager = new PlatformEventManager(this.configuration
|
|
124
|
-
|
|
132
|
+
this.eventManager = new PlatformEventManager(this.configuration, {
|
|
133
|
+
[ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
|
|
134
|
+
});
|
|
135
|
+
this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
|
|
136
|
+
this.#childRunTracker = new ChildRunTracker();
|
|
125
137
|
}
|
|
126
138
|
/**
|
|
127
139
|
* Runs the main user function that performs the job of the Actor
|
|
@@ -196,9 +208,7 @@ export class Actor {
|
|
|
196
208
|
}
|
|
197
209
|
catch (err) {
|
|
198
210
|
log.exception(err, err.message);
|
|
199
|
-
await this.exit({
|
|
200
|
-
exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
|
|
201
|
-
});
|
|
211
|
+
await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
|
|
202
212
|
}
|
|
203
213
|
return ret;
|
|
204
214
|
})();
|
|
@@ -221,7 +231,6 @@ export class Actor {
|
|
|
221
231
|
this.initialized = true;
|
|
222
232
|
checkCrawleeVersion();
|
|
223
233
|
log.info('System info', getSystemInfo());
|
|
224
|
-
printOutdatedSdkWarning();
|
|
225
234
|
// Register this Actor's config as the global one so crawlee storages and
|
|
226
235
|
// the event manager resolve the same instance (`availableMemoryRatio` /
|
|
227
236
|
// `disableBrowserSandbox` at-home defaults now live in `Configuration`).
|
|
@@ -236,9 +245,6 @@ export class Actor {
|
|
|
236
245
|
else if (options.storage) {
|
|
237
246
|
this.installStorageBackend(options.storage);
|
|
238
247
|
}
|
|
239
|
-
// Init the event manager the config uses
|
|
240
|
-
await serviceLocator.getEventManager().init();
|
|
241
|
-
log.debug(`Events initialized`);
|
|
242
248
|
// Register handlers for aborting and migrating events for automatic graceful shutdown.
|
|
243
249
|
// - aborting: calls Actor.exit() to terminate the run gracefully
|
|
244
250
|
// - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
|
|
@@ -265,16 +271,39 @@ export class Actor {
|
|
|
265
271
|
// Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
|
|
266
272
|
this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
|
|
267
273
|
this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
|
|
274
|
+
// Attach listeners queued before init(), then connect to the platform events only after all handlers
|
|
275
|
+
// are registered, so that an event sent right after the connection opens (e.g. an already pending
|
|
276
|
+
// `aborting`) is not missed.
|
|
277
|
+
const events = serviceLocator.getEventManager();
|
|
278
|
+
if (this.#pendingListeners.length > 0) {
|
|
279
|
+
for (const [event, listener] of this.#pendingListeners) {
|
|
280
|
+
events.on(event, listener);
|
|
281
|
+
}
|
|
282
|
+
log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
|
|
283
|
+
this.#pendingListeners = [];
|
|
284
|
+
}
|
|
285
|
+
await events.init();
|
|
286
|
+
log.debug(`Events initialized`);
|
|
268
287
|
await purgeDefaultStorages({
|
|
269
288
|
configuration: this.configuration,
|
|
270
289
|
onlyPurgeOnce: true,
|
|
271
290
|
});
|
|
272
291
|
log.debug(`Default storages purged`);
|
|
292
|
+
await this.#childRunTracker.load();
|
|
293
|
+
this.#runPromise = undefined;
|
|
294
|
+
this.#actorPromise = undefined;
|
|
295
|
+
if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
|
|
296
|
+
// Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
|
|
297
|
+
void this.getCurrentRun().catch(() => { });
|
|
298
|
+
void this.#getCurrentActor().catch(() => { });
|
|
299
|
+
}
|
|
273
300
|
await this.#chargingManager.init();
|
|
274
301
|
log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
|
|
275
302
|
// Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
|
|
276
303
|
// registered with crawlee directly; the storages the Actor installs itself are wrapped.
|
|
277
|
-
if (this.#chargingManager.isPayPerEvent &&
|
|
304
|
+
if (this.#chargingManager.isPayPerEvent &&
|
|
305
|
+
!this.#chargingManager.isMultiTenant &&
|
|
306
|
+
!this.#chargesDefaultDatasetItems()) {
|
|
278
307
|
log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
|
|
279
308
|
'storage - the platform only counts items it stores itself.');
|
|
280
309
|
}
|
|
@@ -362,18 +391,29 @@ export class Actor {
|
|
|
362
391
|
* @ignore
|
|
363
392
|
*/
|
|
364
393
|
async fail(messageOrOptions, options = {}) {
|
|
365
|
-
|
|
394
|
+
const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
|
|
395
|
+
return this.exit(messageOrOptions, { ...options, exitCode });
|
|
366
396
|
}
|
|
367
397
|
/**
|
|
368
398
|
* @ignore
|
|
369
399
|
*/
|
|
370
400
|
on(event, listener) {
|
|
401
|
+
// Before init() the service locator must stay untouched, otherwise it
|
|
402
|
+
// creates a default Configuration that init() then conflicts with.
|
|
403
|
+
if (!this.initialized) {
|
|
404
|
+
this.#pendingListeners.push([event, listener]);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
371
407
|
serviceLocator.getEventManager().on(event, listener);
|
|
372
408
|
}
|
|
373
409
|
/**
|
|
374
410
|
* @ignore
|
|
375
411
|
*/
|
|
376
412
|
off(event, listener) {
|
|
413
|
+
if (!this.initialized) {
|
|
414
|
+
this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
377
417
|
serviceLocator.getEventManager().off(event, listener);
|
|
378
418
|
}
|
|
379
419
|
/**
|
|
@@ -401,9 +441,26 @@ export class Actor {
|
|
|
401
441
|
*/
|
|
402
442
|
async call(actorId, input, options = {}) {
|
|
403
443
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
404
|
-
const { token, timeout: _timeout, ...rest } = options;
|
|
444
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
405
445
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
406
|
-
|
|
446
|
+
if (abortWithParent && !runName)
|
|
447
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
448
|
+
if (!runName)
|
|
449
|
+
return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
|
|
450
|
+
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
451
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
452
|
+
const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
453
|
+
// The earlier part of a resumed run's log was already redirected before the migration.
|
|
454
|
+
const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
|
|
455
|
+
streamedLog?.start();
|
|
456
|
+
try {
|
|
457
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
458
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
459
|
+
return finishedRun;
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
await streamedLog?.stop();
|
|
463
|
+
}
|
|
407
464
|
}
|
|
408
465
|
/**
|
|
409
466
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
@@ -430,9 +487,15 @@ export class Actor {
|
|
|
430
487
|
*/
|
|
431
488
|
async start(actorId, input, options = {}) {
|
|
432
489
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
433
|
-
const { token, timeout: _timeout, ...rest } = options;
|
|
490
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
434
491
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
435
|
-
|
|
492
|
+
if (abortWithParent && !runName)
|
|
493
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
494
|
+
if (!runName)
|
|
495
|
+
return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
|
|
496
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
497
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
498
|
+
return run;
|
|
436
499
|
}
|
|
437
500
|
/**
|
|
438
501
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -452,12 +515,35 @@ export class Actor {
|
|
|
452
515
|
async abort(runId, options = {}) {
|
|
453
516
|
const { token, statusMessage, ...rest } = options;
|
|
454
517
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
518
|
+
const runClient = client.run(runId);
|
|
455
519
|
if (statusMessage) {
|
|
456
|
-
await
|
|
457
|
-
isStatusMessageTerminal: true,
|
|
458
|
-
});
|
|
520
|
+
await runClient.update({ statusMessage, isStatusMessageTerminal: true });
|
|
459
521
|
}
|
|
460
|
-
return
|
|
522
|
+
return runClient.abort(rest);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
526
|
+
*
|
|
527
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
528
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
529
|
+
*
|
|
530
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
531
|
+
*
|
|
532
|
+
* For more information about Actors, read the
|
|
533
|
+
* [documentation](https://docs.apify.com/actor).
|
|
534
|
+
*
|
|
535
|
+
* **Example usage:**
|
|
536
|
+
*
|
|
537
|
+
* ```js
|
|
538
|
+
* const run = await Actor.resurrect(runId);
|
|
539
|
+
* ```
|
|
540
|
+
* @ignore
|
|
541
|
+
*/
|
|
542
|
+
async resurrect(runId, options = {}) {
|
|
543
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
544
|
+
const { token, timeout: _timeout, ...rest } = options;
|
|
545
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
546
|
+
return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
|
|
461
547
|
}
|
|
462
548
|
/**
|
|
463
549
|
* Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -487,9 +573,69 @@ export class Actor {
|
|
|
487
573
|
*/
|
|
488
574
|
async callTask(taskId, input, options = {}) {
|
|
489
575
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
490
|
-
const { token, timeout: _timeout, ...rest } = options;
|
|
576
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
577
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
578
|
+
if (abortWithParent && !runName)
|
|
579
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
580
|
+
if (!runName)
|
|
581
|
+
return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
|
|
582
|
+
const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
583
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
584
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
585
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
586
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
587
|
+
return finishedRun;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
591
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
592
|
+
*
|
|
593
|
+
* ```js
|
|
594
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
595
|
+
* ```
|
|
596
|
+
*
|
|
597
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
598
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
599
|
+
* under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
|
|
600
|
+
*/
|
|
601
|
+
get childRuns() {
|
|
602
|
+
this.ensureActorInit('childRuns');
|
|
603
|
+
return this.#childRunTracker.getRunClients(this.apifyClient);
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
607
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
608
|
+
*
|
|
609
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
610
|
+
*
|
|
611
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
612
|
+
*
|
|
613
|
+
* **Example usage:**
|
|
614
|
+
*
|
|
615
|
+
* ```js
|
|
616
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
617
|
+
* ```
|
|
618
|
+
*
|
|
619
|
+
* @param taskId
|
|
620
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
621
|
+
* @param [input]
|
|
622
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
623
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
624
|
+
* Provided input will be merged with Actor task input.
|
|
625
|
+
* @param [options]
|
|
626
|
+
* @ignore
|
|
627
|
+
*/
|
|
628
|
+
async startTask(taskId, input, options = {}) {
|
|
629
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
630
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
491
631
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
492
|
-
|
|
632
|
+
if (abortWithParent && !runName)
|
|
633
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
634
|
+
if (!runName)
|
|
635
|
+
return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
|
|
636
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
637
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
638
|
+
return run;
|
|
493
639
|
}
|
|
494
640
|
/**
|
|
495
641
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
@@ -533,23 +679,37 @@ export class Actor {
|
|
|
533
679
|
return;
|
|
534
680
|
}
|
|
535
681
|
this.#isRebooting = true;
|
|
682
|
+
const { timeoutSecs = 30, customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
|
|
683
|
+
const callListeners = (event, data) => serviceLocator
|
|
684
|
+
.getEventManager()
|
|
685
|
+
.listeners(event)
|
|
686
|
+
.map(async (listener) => {
|
|
687
|
+
try {
|
|
688
|
+
await listener(data);
|
|
689
|
+
}
|
|
690
|
+
catch (err) {
|
|
691
|
+
log.exception(err, 'A pre-reboot event listener failed');
|
|
692
|
+
}
|
|
693
|
+
});
|
|
536
694
|
// Waiting for all the listeners to finish, as `.reboot()` kills the container.
|
|
537
|
-
await
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
.
|
|
541
|
-
|
|
542
|
-
.
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
.getEventManager()
|
|
546
|
-
.listeners(EventType.MIGRATING)
|
|
547
|
-
.map(async (x) => x({})),
|
|
548
|
-
]);
|
|
695
|
+
await addTimeoutToPromise(async () => {
|
|
696
|
+
await Promise.all([
|
|
697
|
+
// `persistState` for individual RequestLists, RequestQueue... instances to be persisted
|
|
698
|
+
...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
|
|
699
|
+
// `migrating` to pause Apify crawlers
|
|
700
|
+
...callListeners(EventType.MIGRATING, {}),
|
|
701
|
+
]);
|
|
702
|
+
}, timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
|
|
549
703
|
const runId = this.configuration.actorRunId;
|
|
550
|
-
|
|
704
|
+
try {
|
|
705
|
+
await this.apifyClient.run(runId).reboot();
|
|
706
|
+
}
|
|
707
|
+
catch (err) {
|
|
708
|
+
// Reset the flag so that a failed reboot can be retried.
|
|
709
|
+
this.#isRebooting = false;
|
|
710
|
+
throw err;
|
|
711
|
+
}
|
|
551
712
|
// Wait some time for container to be stopped.
|
|
552
|
-
const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
|
|
553
713
|
await sleep(customAfterSleepMillis);
|
|
554
714
|
}
|
|
555
715
|
/**
|
|
@@ -598,7 +758,8 @@ export class Actor {
|
|
|
598
758
|
/**
|
|
599
759
|
* Sets the status message for the current Actor run.
|
|
600
760
|
*
|
|
601
|
-
* @returns The
|
|
761
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
762
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
602
763
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
603
764
|
* @ignore
|
|
604
765
|
*/
|
|
@@ -626,17 +787,18 @@ export class Actor {
|
|
|
626
787
|
}
|
|
627
788
|
/**
|
|
628
789
|
* Propagates a status message to the current run, without logging it locally.
|
|
790
|
+
* Resolves `undefined` when there is no run to update, or when the update failed or timed out.
|
|
629
791
|
*/
|
|
630
792
|
async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
|
|
631
793
|
const runId = this.configuration.actorRunId;
|
|
632
|
-
if (runId) {
|
|
633
|
-
|
|
634
|
-
const run = await addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => log.warning(e.message));
|
|
635
|
-
if (run) {
|
|
636
|
-
return run;
|
|
637
|
-
}
|
|
794
|
+
if (!runId) {
|
|
795
|
+
return undefined;
|
|
638
796
|
}
|
|
639
|
-
|
|
797
|
+
// just to be sure, this should be fast
|
|
798
|
+
return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
|
|
799
|
+
log.warning(e.message);
|
|
800
|
+
return undefined;
|
|
801
|
+
});
|
|
640
802
|
}
|
|
641
803
|
/**
|
|
642
804
|
* Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
|
|
@@ -664,6 +826,7 @@ export class Actor {
|
|
|
664
826
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
665
827
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
666
828
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
829
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
667
830
|
* @ignore
|
|
668
831
|
*/
|
|
669
832
|
async pushData(item, eventName) {
|
|
@@ -671,6 +834,9 @@ export class Actor {
|
|
|
671
834
|
if (eventName?.startsWith('apify-')) {
|
|
672
835
|
throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
|
|
673
836
|
}
|
|
837
|
+
if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
|
|
838
|
+
throw new Error('Charging for pushed items is not supported in a multi-tenant Server Actor run - use Actor.charge() with the `requestId` of the incoming request instead.');
|
|
839
|
+
}
|
|
674
840
|
if (eventName !== undefined) {
|
|
675
841
|
rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
|
|
676
842
|
'so a rolled-back request would be billed for items that were never stored.');
|
|
@@ -742,38 +908,10 @@ export class Actor {
|
|
|
742
908
|
: undefined,
|
|
743
909
|
});
|
|
744
910
|
}
|
|
745
|
-
|
|
746
|
-
* Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
|
|
747
|
-
*
|
|
748
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
749
|
-
* For example, calling the following code:
|
|
750
|
-
* ```js
|
|
751
|
-
* const value = await Actor.getValue('my-key');
|
|
752
|
-
* ```
|
|
753
|
-
*
|
|
754
|
-
* is equivalent to:
|
|
755
|
-
* ```js
|
|
756
|
-
* const store = await Actor.openKeyValueStore();
|
|
757
|
-
* const value = await store.getValue('my-key');
|
|
758
|
-
* ```
|
|
759
|
-
*
|
|
760
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
761
|
-
*
|
|
762
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
763
|
-
* and {@link KeyValueStore.getValue}.
|
|
764
|
-
*
|
|
765
|
-
* @param key Unique record key.
|
|
766
|
-
* @returns
|
|
767
|
-
* Returns a promise that resolves to an object, string
|
|
768
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
769
|
-
* on the MIME content type of the record, or `null`
|
|
770
|
-
* if the record is missing.
|
|
771
|
-
* @ignore
|
|
772
|
-
*/
|
|
773
|
-
async getValue(key) {
|
|
911
|
+
async getValue(key, defaultValue) {
|
|
774
912
|
this.ensureActorInit('getValue');
|
|
775
913
|
const store = await this.openKeyValueStore();
|
|
776
|
-
return store.getValue(key);
|
|
914
|
+
return store.getValue(key, defaultValue);
|
|
777
915
|
}
|
|
778
916
|
/**
|
|
779
917
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -818,11 +956,15 @@ export class Actor {
|
|
|
818
956
|
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
819
957
|
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
820
958
|
*
|
|
821
|
-
* When running locally
|
|
822
|
-
*
|
|
959
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
960
|
+
* working directory. A storage backend that doesn't read the default key-value store's directory under
|
|
961
|
+
* the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
|
|
962
|
+
*
|
|
963
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
964
|
+
* replaced with the links of their CSV exports.
|
|
823
965
|
*
|
|
824
|
-
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when
|
|
825
|
-
*
|
|
966
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
967
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
826
968
|
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
827
969
|
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
|
|
828
970
|
*
|
|
@@ -842,16 +984,24 @@ export class Actor {
|
|
|
842
984
|
*/
|
|
843
985
|
async getInput() {
|
|
844
986
|
this.ensureActorInit('getInput');
|
|
845
|
-
const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase } = this.configuration;
|
|
987
|
+
const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
|
|
988
|
+
// Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
|
|
989
|
+
const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
|
|
846
990
|
const store = await this.openKeyValueStore();
|
|
847
991
|
const record = await store.getRecord(inputKey);
|
|
848
|
-
|
|
992
|
+
// Not a conflict check: under the file-system backend the record *is* the store directory's file.
|
|
993
|
+
const storeInput = record
|
|
849
994
|
? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
|
|
850
|
-
: await this.
|
|
995
|
+
: await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
|
|
996
|
+
const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
|
|
997
|
+
if (storeInput != null && cwdInput != null) {
|
|
998
|
+
throw new ActorInputError('MULTIPLE_FILES', `Found the input both in the default key-value store and in a "${inputKey}" or "${inputKey}.json" file in the working directory. Keep only one of them.`);
|
|
999
|
+
}
|
|
1000
|
+
const rawInput = storeInput ?? cwdInput;
|
|
851
1001
|
if (rawInput == null) {
|
|
852
1002
|
const locations = [`the "${inputKey}" record of the default key-value store`];
|
|
853
1003
|
if (!this.configuration.isAtHome) {
|
|
854
|
-
locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working directory`);
|
|
1004
|
+
locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
|
|
855
1005
|
}
|
|
856
1006
|
throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
|
|
857
1007
|
}
|
|
@@ -871,19 +1021,19 @@ export class Actor {
|
|
|
871
1021
|
}
|
|
872
1022
|
}
|
|
873
1023
|
if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
|
|
874
|
-
input = await this.inferDefaultsFromInputSchema(input);
|
|
1024
|
+
input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
|
|
875
1025
|
}
|
|
876
1026
|
return input;
|
|
877
1027
|
}
|
|
878
1028
|
/**
|
|
879
|
-
* Reads the input from a `<inputKey>` or `<inputKey>.json` file in the
|
|
1029
|
+
* Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
|
|
880
1030
|
* whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
|
|
881
1031
|
* such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
|
|
882
1032
|
* {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
|
|
883
1033
|
*
|
|
884
1034
|
* @returns `undefined` when running on the platform or when neither file exists.
|
|
885
1035
|
*/
|
|
886
|
-
async
|
|
1036
|
+
async readInputFromDirectory(inputKey, directory, label) {
|
|
887
1037
|
if (this.configuration.isAtHome) {
|
|
888
1038
|
return undefined;
|
|
889
1039
|
}
|
|
@@ -893,20 +1043,20 @@ export class Actor {
|
|
|
893
1043
|
];
|
|
894
1044
|
const found = [];
|
|
895
1045
|
for (const candidate of candidates) {
|
|
896
|
-
const path = join(
|
|
1046
|
+
const path = join(directory, candidate.filename);
|
|
897
1047
|
const stats = await stat(path).catch(() => null);
|
|
898
1048
|
if (stats?.isFile()) {
|
|
899
1049
|
found.push({ ...candidate, path });
|
|
900
1050
|
}
|
|
901
1051
|
}
|
|
902
1052
|
if (found.length > 1) {
|
|
903
|
-
throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the
|
|
1053
|
+
throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
|
|
904
1054
|
}
|
|
905
1055
|
if (found.length === 0) {
|
|
906
1056
|
return undefined;
|
|
907
1057
|
}
|
|
908
1058
|
const [file] = found;
|
|
909
|
-
return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the
|
|
1059
|
+
return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
|
|
910
1060
|
}
|
|
911
1061
|
/**
|
|
912
1062
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
@@ -1031,6 +1181,10 @@ export class Actor {
|
|
|
1031
1181
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1032
1182
|
* and avoids situations where more work is requested than the budget allows.
|
|
1033
1183
|
*
|
|
1184
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1185
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1186
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1187
|
+
*
|
|
1034
1188
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1035
1189
|
* @ignore
|
|
1036
1190
|
*/
|
|
@@ -1047,50 +1201,38 @@ export class Actor {
|
|
|
1047
1201
|
return this.#chargingManager;
|
|
1048
1202
|
}
|
|
1049
1203
|
/**
|
|
1050
|
-
*
|
|
1204
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1205
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1206
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1051
1207
|
*/
|
|
1052
|
-
|
|
1053
|
-
const
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1208
|
+
async getCurrentRun() {
|
|
1209
|
+
const runId = this.configuration.actorRunId;
|
|
1210
|
+
if (!runId) {
|
|
1211
|
+
return undefined;
|
|
1212
|
+
}
|
|
1213
|
+
this.#runPromise ??= this.apifyClient
|
|
1214
|
+
.run(runId)
|
|
1215
|
+
.get()
|
|
1216
|
+
.catch((err) => {
|
|
1217
|
+
this.#runPromise = undefined;
|
|
1218
|
+
throw err;
|
|
1062
1219
|
});
|
|
1063
|
-
return
|
|
1220
|
+
return this.#runPromise;
|
|
1064
1221
|
}
|
|
1065
|
-
/**
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
* If some variables are not defined or are invalid, the corresponding value in the resulting object will be null.
|
|
1071
|
-
* @ignore
|
|
1072
|
-
*/
|
|
1073
|
-
getEnv() {
|
|
1074
|
-
// NOTE: Don't throw if env vars are invalid to simplify local development and debugging of Actors
|
|
1075
|
-
const env = process.env || {};
|
|
1076
|
-
const envVars = {};
|
|
1077
|
-
for (const [shortName, fullName] of Object.entries({
|
|
1078
|
-
...APIFY_ENV_VARS,
|
|
1079
|
-
...this.getModifiedActorEnvVars(),
|
|
1080
|
-
})) {
|
|
1081
|
-
const camelCaseName = snakeCaseToCamelCase(shortName);
|
|
1082
|
-
let value = env[fullName];
|
|
1083
|
-
// Parse dates and integers.
|
|
1084
|
-
if (value && fullName.endsWith('_AT')) {
|
|
1085
|
-
const unix = Date.parse(value);
|
|
1086
|
-
value = unix > 0 ? new Date(unix) : undefined;
|
|
1087
|
-
}
|
|
1088
|
-
else if (INTEGER_ENV_VARS.includes(fullName)) {
|
|
1089
|
-
value = parseInt(value, 10);
|
|
1090
|
-
}
|
|
1091
|
-
Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
|
|
1222
|
+
/** Cached for the lifetime of the Actor; only the charging manager needs it. */
|
|
1223
|
+
async #getCurrentActor() {
|
|
1224
|
+
const { actorId } = this.configuration;
|
|
1225
|
+
if (!actorId) {
|
|
1226
|
+
return undefined;
|
|
1092
1227
|
}
|
|
1093
|
-
|
|
1228
|
+
this.#actorPromise ??= this.apifyClient
|
|
1229
|
+
.actor(actorId)
|
|
1230
|
+
.get()
|
|
1231
|
+
.catch((err) => {
|
|
1232
|
+
this.#actorPromise = undefined;
|
|
1233
|
+
throw err;
|
|
1234
|
+
});
|
|
1235
|
+
return this.#actorPromise;
|
|
1094
1236
|
}
|
|
1095
1237
|
/**
|
|
1096
1238
|
* Returns a new instance of the Apify API client. The `ApifyClient` class is provided
|
|
@@ -1124,14 +1266,14 @@ export class Actor {
|
|
|
1124
1266
|
*
|
|
1125
1267
|
* Values can be modified by simply using the assignment operator.
|
|
1126
1268
|
*
|
|
1127
|
-
* @param name The
|
|
1269
|
+
* @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
|
|
1128
1270
|
* @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
|
|
1129
1271
|
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
|
|
1130
1272
|
*/
|
|
1131
1273
|
async useState(name, defaultValue = {}, options) {
|
|
1132
1274
|
this.ensureActorInit('useState');
|
|
1133
1275
|
const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
|
|
1134
|
-
configuration: options?.configuration
|
|
1276
|
+
configuration: options?.configuration ?? this.configuration,
|
|
1135
1277
|
});
|
|
1136
1278
|
return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
|
|
1137
1279
|
}
|
|
@@ -1140,7 +1282,7 @@ export class Actor {
|
|
|
1140
1282
|
*
|
|
1141
1283
|
* Values can be modified by simply using the assignment operator.
|
|
1142
1284
|
*
|
|
1143
|
-
* @param name The
|
|
1285
|
+
* @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
|
|
1144
1286
|
* @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
|
|
1145
1287
|
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
|
|
1146
1288
|
*/
|
|
@@ -1313,6 +1455,31 @@ export class Actor {
|
|
|
1313
1455
|
static async callTask(taskId, input, options = {}) {
|
|
1314
1456
|
return Actor.getDefaultInstance().callTask(taskId, input, options);
|
|
1315
1457
|
}
|
|
1458
|
+
/**
|
|
1459
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1460
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
1461
|
+
*
|
|
1462
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1463
|
+
*
|
|
1464
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
1465
|
+
*
|
|
1466
|
+
* **Example usage:**
|
|
1467
|
+
*
|
|
1468
|
+
* ```js
|
|
1469
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
1470
|
+
* ```
|
|
1471
|
+
*
|
|
1472
|
+
* @param taskId
|
|
1473
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
1474
|
+
* @param [input]
|
|
1475
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
1476
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
1477
|
+
* Provided input will be merged with Actor task input.
|
|
1478
|
+
* @param [options]
|
|
1479
|
+
*/
|
|
1480
|
+
static async startTask(taskId, input, options = {}) {
|
|
1481
|
+
return Actor.getDefaultInstance().startTask(taskId, input, options);
|
|
1482
|
+
}
|
|
1316
1483
|
/**
|
|
1317
1484
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1318
1485
|
* unlike `Actor.call`, this method just starts the run without waiting for finish.
|
|
@@ -1338,6 +1505,21 @@ export class Actor {
|
|
|
1338
1505
|
static async start(actorId, input, options = {}) {
|
|
1339
1506
|
return Actor.getDefaultInstance().start(actorId, input, options);
|
|
1340
1507
|
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
1510
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
1511
|
+
*
|
|
1512
|
+
* ```js
|
|
1513
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
1514
|
+
* ```
|
|
1515
|
+
*
|
|
1516
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
1517
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
1518
|
+
* under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
|
|
1519
|
+
*/
|
|
1520
|
+
static get childRuns() {
|
|
1521
|
+
return Actor.getDefaultInstance().childRuns;
|
|
1522
|
+
}
|
|
1341
1523
|
/**
|
|
1342
1524
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1343
1525
|
*
|
|
@@ -1355,6 +1537,26 @@ export class Actor {
|
|
|
1355
1537
|
static async abort(runId, options = {}) {
|
|
1356
1538
|
return Actor.getDefaultInstance().abort(runId, options);
|
|
1357
1539
|
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1542
|
+
*
|
|
1543
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
1544
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
1545
|
+
*
|
|
1546
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1547
|
+
*
|
|
1548
|
+
* For more information about Actors, read the
|
|
1549
|
+
* [documentation](https://docs.apify.com/actor).
|
|
1550
|
+
*
|
|
1551
|
+
* **Example usage:**
|
|
1552
|
+
*
|
|
1553
|
+
* ```js
|
|
1554
|
+
* const run = await Actor.resurrect(runId);
|
|
1555
|
+
* ```
|
|
1556
|
+
*/
|
|
1557
|
+
static async resurrect(runId, options = {}) {
|
|
1558
|
+
return Actor.getDefaultInstance().resurrect(runId, options);
|
|
1559
|
+
}
|
|
1358
1560
|
/**
|
|
1359
1561
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
1360
1562
|
* the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
|
|
@@ -1399,7 +1601,8 @@ export class Actor {
|
|
|
1399
1601
|
* @param [options]
|
|
1400
1602
|
* @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
|
|
1401
1603
|
* This is required for the last status message of the run. Default value is `false`.
|
|
1402
|
-
* @returns The
|
|
1604
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
1605
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
1403
1606
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
1404
1607
|
*/
|
|
1405
1608
|
static async setStatusMessage(statusMessage, options) {
|
|
@@ -1428,6 +1631,7 @@ export class Actor {
|
|
|
1428
1631
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
1429
1632
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
1430
1633
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
1634
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
1431
1635
|
*/
|
|
1432
1636
|
static async pushData(item, eventName) {
|
|
1433
1637
|
if (eventName === undefined) {
|
|
@@ -1454,35 +1658,8 @@ export class Actor {
|
|
|
1454
1658
|
static async openDataset(datasetIdOrName, options = {}) {
|
|
1455
1659
|
return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
|
|
1456
1660
|
}
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
*
|
|
1460
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
1461
|
-
* For example, calling the following code:
|
|
1462
|
-
* ```js
|
|
1463
|
-
* const value = await Actor.getValue('my-key');
|
|
1464
|
-
* ```
|
|
1465
|
-
*
|
|
1466
|
-
* is equivalent to:
|
|
1467
|
-
* ```js
|
|
1468
|
-
* const store = await Actor.openKeyValueStore();
|
|
1469
|
-
* const value = await store.getValue('my-key');
|
|
1470
|
-
* ```
|
|
1471
|
-
*
|
|
1472
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
1473
|
-
*
|
|
1474
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
1475
|
-
* and {@link KeyValueStore.getValue}.
|
|
1476
|
-
*
|
|
1477
|
-
* @param key Unique record key.
|
|
1478
|
-
* @returns
|
|
1479
|
-
* Returns a promise that resolves to an object, string
|
|
1480
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
1481
|
-
* on the MIME content type of the record, or `null`
|
|
1482
|
-
* if the record is missing.
|
|
1483
|
-
*/
|
|
1484
|
-
static async getValue(key) {
|
|
1485
|
-
return Actor.getDefaultInstance().getValue(key);
|
|
1661
|
+
static async getValue(key, defaultValue) {
|
|
1662
|
+
return Actor.getDefaultInstance().getValue(key, defaultValue);
|
|
1486
1663
|
}
|
|
1487
1664
|
/**
|
|
1488
1665
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -1528,11 +1705,14 @@ export class Actor {
|
|
|
1528
1705
|
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
1529
1706
|
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
1530
1707
|
*
|
|
1531
|
-
* When running locally
|
|
1532
|
-
*
|
|
1708
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
1709
|
+
* working directory.
|
|
1710
|
+
*
|
|
1711
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
1712
|
+
* replaced with the links of their CSV exports.
|
|
1533
1713
|
*
|
|
1534
|
-
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when
|
|
1535
|
-
*
|
|
1714
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
1715
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
1536
1716
|
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
1537
1717
|
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
|
|
1538
1718
|
* ```js
|
|
@@ -1652,6 +1832,10 @@ export class Actor {
|
|
|
1652
1832
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1653
1833
|
* and avoids situations where more work is requested than the budget allows.
|
|
1654
1834
|
*
|
|
1835
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1836
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1837
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1838
|
+
*
|
|
1655
1839
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1656
1840
|
*/
|
|
1657
1841
|
static async charge(options) {
|
|
@@ -1663,16 +1847,6 @@ export class Actor {
|
|
|
1663
1847
|
static getChargingManager() {
|
|
1664
1848
|
return Actor.getDefaultInstance().getChargingManager();
|
|
1665
1849
|
}
|
|
1666
|
-
/**
|
|
1667
|
-
* Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
|
|
1668
|
-
*
|
|
1669
|
-
* For the list of the Apify environment variables, see
|
|
1670
|
-
* [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
|
|
1671
|
-
* If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.
|
|
1672
|
-
*/
|
|
1673
|
-
static getEnv() {
|
|
1674
|
-
return Actor.getDefaultInstance().getEnv();
|
|
1675
|
-
}
|
|
1676
1850
|
/**
|
|
1677
1851
|
* Returns a new instance of the Apify API client. The `ApifyClient` class is provided
|
|
1678
1852
|
* by the [apify-client](https://www.npmjs.com/package/apify-client)
|
|
@@ -1689,6 +1863,14 @@ export class Actor {
|
|
|
1689
1863
|
static isAtHome() {
|
|
1690
1864
|
return Actor.getDefaultInstance().isAtHome();
|
|
1691
1865
|
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1868
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1869
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1870
|
+
*/
|
|
1871
|
+
static async getCurrentRun() {
|
|
1872
|
+
return Actor.getDefaultInstance().getCurrentRun();
|
|
1873
|
+
}
|
|
1692
1874
|
/** Default {@link ApifyClient} instance. */
|
|
1693
1875
|
static get apifyClient() {
|
|
1694
1876
|
return Actor.getDefaultInstance().apifyClient;
|
|
@@ -1792,10 +1974,10 @@ export class Actor {
|
|
|
1792
1974
|
* Returns `undefined` if not on the Apify platform or the current run was started without a timeout.
|
|
1793
1975
|
*/
|
|
1794
1976
|
getRemainingTimeSecs() {
|
|
1795
|
-
const
|
|
1977
|
+
const { timeoutAt } = this.configuration;
|
|
1796
1978
|
const MINIMUM_API_TIMEOUT_SECS = 1;
|
|
1797
|
-
if (this.isAtHome() &&
|
|
1798
|
-
return Math.max(Math.ceil((
|
|
1979
|
+
if (this.isAtHome() && timeoutAt !== undefined) {
|
|
1980
|
+
return Math.max(Math.ceil((timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
|
|
1799
1981
|
}
|
|
1800
1982
|
log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
|
|
1801
1983
|
'timeout for the Actor run is set.');
|