apify 4.0.0-rc.0 → 4.0.0-rc.1

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.js CHANGED
@@ -1,26 +1,37 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
2
  import { readFile, stat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
4
+ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
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, INTEGER_ENV_VARS, } from '@apify/consts';
8
+ import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_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';
12
+ import { timeoutPromise } from '@apify/utilities';
12
13
  import { parseArgument } from '@apify/validations';
13
14
  import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
14
15
  import { ApifyStorageBackend } from './apify_storage_backend.js';
15
16
  import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
16
17
  import { ChargingStorageBackend } from './charging_storage_backend.js';
18
+ import { ChildRunTracker } from './child_run_tracker.js';
17
19
  import { Configuration } from './configuration.js';
18
20
  import { ActorInputError } from './errors.js';
21
+ import { fixGoogleSheetsUrls } from './google_sheets.js';
19
22
  import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
20
23
  import { PlatformEventManager } from './platform_event_manager.js';
21
24
  import { ProxyConfiguration } from './proxy_configuration.js';
22
25
  import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
23
- import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, printOutdatedSdkWarning, snakeCaseToCamelCase, } from './utils.js';
26
+ import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, snakeCaseToCamelCase, } from './utils.js';
27
+ // `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
28
+ const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
29
+ // Still listed in `@apify/consts`, but not read by the SDK.
30
+ const IGNORED_ENV_VARS = [
31
+ APIFY_ENV_VARS.DISABLE_OUTDATED_WARNING,
32
+ APIFY_ENV_VARS.SDK_LATEST_VERSION,
33
+ APIFY_ENV_VARS.LOCAL_STORAGE_DIR,
34
+ ];
24
35
  /**
25
36
  * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
26
37
  * JSON input reports where it came from.
@@ -52,6 +63,7 @@ export const EXIT_CODES = {
52
63
  export class Actor {
53
64
  /** @internal */
54
65
  static #instance;
66
+ #childRunTracker;
55
67
  /**
56
68
  * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
57
69
  * @internal
@@ -93,10 +105,16 @@ export class Actor {
93
105
  */
94
106
  #statusMessageForwarder;
95
107
  #chargingManager;
108
+ #runPromise;
109
+ #actorPromise;
110
+ /** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
111
+ #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
96
112
  /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
97
113
  #requestQueueAccess = 'single';
98
114
  /** Lazily built by the `#storageBackend` getter. */
99
115
  #cachedStorageBackend;
116
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
117
+ #pendingListeners = [];
100
118
  constructor(options = {}) {
101
119
  const { configuration, ...configOptions } = options;
102
120
  if (configuration) {
@@ -120,8 +138,11 @@ export class Actor {
120
138
  this.configuration = new Configuration(configOptions);
121
139
  }
122
140
  this.apifyClient = this.newClient();
123
- this.eventManager = new PlatformEventManager(this.configuration);
124
- this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
141
+ this.eventManager = new PlatformEventManager(this.configuration, {
142
+ [ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
143
+ });
144
+ this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
145
+ this.#childRunTracker = new ChildRunTracker();
125
146
  }
126
147
  /**
127
148
  * Runs the main user function that performs the job of the Actor
@@ -196,9 +217,7 @@ export class Actor {
196
217
  }
197
218
  catch (err) {
198
219
  log.exception(err, err.message);
199
- await this.exit({
200
- exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
201
- });
220
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
202
221
  }
203
222
  return ret;
204
223
  })();
@@ -221,7 +240,6 @@ export class Actor {
221
240
  this.initialized = true;
222
241
  checkCrawleeVersion();
223
242
  log.info('System info', getSystemInfo());
224
- printOutdatedSdkWarning();
225
243
  // Register this Actor's config as the global one so crawlee storages and
226
244
  // the event manager resolve the same instance (`availableMemoryRatio` /
227
245
  // `disableBrowserSandbox` at-home defaults now live in `Configuration`).
@@ -236,9 +254,6 @@ export class Actor {
236
254
  else if (options.storage) {
237
255
  this.installStorageBackend(options.storage);
238
256
  }
239
- // Init the event manager the config uses
240
- await serviceLocator.getEventManager().init();
241
- log.debug(`Events initialized`);
242
257
  // Register handlers for aborting and migrating events for automatic graceful shutdown.
243
258
  // - aborting: calls Actor.exit() to terminate the run gracefully
244
259
  // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
@@ -265,16 +280,39 @@ export class Actor {
265
280
  // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
266
281
  this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
267
282
  this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
283
+ // Attach listeners queued before init(), then connect to the platform events only after all handlers
284
+ // are registered, so that an event sent right after the connection opens (e.g. an already pending
285
+ // `aborting`) is not missed.
286
+ const events = serviceLocator.getEventManager();
287
+ if (this.#pendingListeners.length > 0) {
288
+ for (const [event, listener] of this.#pendingListeners) {
289
+ events.on(event, listener);
290
+ }
291
+ log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
292
+ this.#pendingListeners = [];
293
+ }
294
+ await events.init();
295
+ log.debug(`Events initialized`);
268
296
  await purgeDefaultStorages({
269
297
  configuration: this.configuration,
270
298
  onlyPurgeOnce: true,
271
299
  });
272
300
  log.debug(`Default storages purged`);
301
+ await this.#childRunTracker.load();
302
+ this.#runPromise = undefined;
303
+ this.#actorPromise = undefined;
304
+ if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
305
+ // Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
306
+ void this.getCurrentRun().catch(() => { });
307
+ void this.#getCurrentActor().catch(() => { });
308
+ }
273
309
  await this.#chargingManager.init();
274
310
  log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
275
311
  // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
276
312
  // registered with crawlee directly; the storages the Actor installs itself are wrapped.
277
- if (this.#chargingManager.isPayPerEvent && !this.#chargesDefaultDatasetItems()) {
313
+ if (this.#chargingManager.isPayPerEvent &&
314
+ !this.#chargingManager.isMultiTenant &&
315
+ !this.#chargesDefaultDatasetItems()) {
278
316
  log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
279
317
  'storage - the platform only counts items it stores itself.');
280
318
  }
@@ -362,18 +400,29 @@ export class Actor {
362
400
  * @ignore
363
401
  */
364
402
  async fail(messageOrOptions, options = {}) {
365
- return this.exit(messageOrOptions, { exitCode: 1, ...options });
403
+ const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
404
+ return this.exit(messageOrOptions, { ...options, exitCode });
366
405
  }
367
406
  /**
368
407
  * @ignore
369
408
  */
370
409
  on(event, listener) {
410
+ // Before init() the service locator must stay untouched, otherwise it
411
+ // creates a default Configuration that init() then conflicts with.
412
+ if (!this.initialized) {
413
+ this.#pendingListeners.push([event, listener]);
414
+ return;
415
+ }
371
416
  serviceLocator.getEventManager().on(event, listener);
372
417
  }
373
418
  /**
374
419
  * @ignore
375
420
  */
376
421
  off(event, listener) {
422
+ if (!this.initialized) {
423
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
424
+ return;
425
+ }
377
426
  serviceLocator.getEventManager().off(event, listener);
378
427
  }
379
428
  /**
@@ -401,9 +450,26 @@ export class Actor {
401
450
  */
402
451
  async call(actorId, input, options = {}) {
403
452
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
404
- const { token, timeout: _timeout, ...rest } = options;
453
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
405
454
  const client = token ? this.newClient({ token }) : this.apifyClient;
406
- return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
455
+ if (abortWithParent && !runName)
456
+ throw new Error('`abortWithParent` requires `runName`.');
457
+ if (!runName)
458
+ return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
459
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
460
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
461
+ const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
462
+ // The earlier part of a resumed run's log was already redirected before the migration.
463
+ const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
464
+ streamedLog?.start();
465
+ try {
466
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
467
+ await this.#childRunTracker.update(runName, finishedRun);
468
+ return finishedRun;
469
+ }
470
+ finally {
471
+ await streamedLog?.stop();
472
+ }
407
473
  }
408
474
  /**
409
475
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -430,9 +496,15 @@ export class Actor {
430
496
  */
431
497
  async start(actorId, input, options = {}) {
432
498
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
433
- const { token, timeout: _timeout, ...rest } = options;
499
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
434
500
  const client = token ? this.newClient({ token }) : this.apifyClient;
435
- return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
501
+ if (abortWithParent && !runName)
502
+ throw new Error('`abortWithParent` requires `runName`.');
503
+ if (!runName)
504
+ return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
505
+ const startOptions = { ...rest, runTimeoutSecs };
506
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
507
+ return run;
436
508
  }
437
509
  /**
438
510
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -452,12 +524,35 @@ export class Actor {
452
524
  async abort(runId, options = {}) {
453
525
  const { token, statusMessage, ...rest } = options;
454
526
  const client = token ? this.newClient({ token }) : this.apifyClient;
527
+ const runClient = client.run(runId);
455
528
  if (statusMessage) {
456
- await this.setStatusMessage(statusMessage, {
457
- isStatusMessageTerminal: true,
458
- });
529
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
459
530
  }
460
- return client.run(runId).abort(rest);
531
+ return runClient.abort(rest);
532
+ }
533
+ /**
534
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
535
+ *
536
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
537
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
538
+ *
539
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
540
+ *
541
+ * For more information about Actors, read the
542
+ * [documentation](https://docs.apify.com/actor).
543
+ *
544
+ * **Example usage:**
545
+ *
546
+ * ```js
547
+ * const run = await Actor.resurrect(runId);
548
+ * ```
549
+ * @ignore
550
+ */
551
+ async resurrect(runId, options = {}) {
552
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
553
+ const { token, timeout: _timeout, ...rest } = options;
554
+ const client = token ? this.newClient({ token }) : this.apifyClient;
555
+ return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
461
556
  }
462
557
  /**
463
558
  * Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -487,9 +582,69 @@ export class Actor {
487
582
  */
488
583
  async callTask(taskId, input, options = {}) {
489
584
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
490
- const { token, timeout: _timeout, ...rest } = options;
585
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
491
586
  const client = token ? this.newClient({ token }) : this.apifyClient;
492
- return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
587
+ if (abortWithParent && !runName)
588
+ throw new Error('`abortWithParent` requires `runName`.');
589
+ if (!runName)
590
+ return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
591
+ const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
592
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
593
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
594
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
595
+ await this.#childRunTracker.update(runName, finishedRun);
596
+ return finishedRun;
597
+ }
598
+ /**
599
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
600
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
601
+ *
602
+ * ```js
603
+ * await Actor.childRuns['my-child'].waitForFinish();
604
+ * ```
605
+ *
606
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
607
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
608
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
609
+ */
610
+ get childRuns() {
611
+ this.ensureActorInit('childRuns');
612
+ return this.#childRunTracker.getRunClients(this.apifyClient);
613
+ }
614
+ /**
615
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
616
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
617
+ *
618
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
619
+ *
620
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
621
+ *
622
+ * **Example usage:**
623
+ *
624
+ * ```js
625
+ * const run = await Actor.startTask('bob/some-task');
626
+ * ```
627
+ *
628
+ * @param taskId
629
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
630
+ * @param [input]
631
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
632
+ * JSON and its content type set to `application/json; charset=utf-8`.
633
+ * Provided input will be merged with Actor task input.
634
+ * @param [options]
635
+ * @ignore
636
+ */
637
+ async startTask(taskId, input, options = {}) {
638
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
639
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
640
+ const client = token ? this.newClient({ token }) : this.apifyClient;
641
+ if (abortWithParent && !runName)
642
+ throw new Error('`abortWithParent` requires `runName`.');
643
+ if (!runName)
644
+ return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
645
+ const startOptions = { ...rest, runTimeoutSecs };
646
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
647
+ return run;
493
648
  }
494
649
  /**
495
650
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -533,23 +688,36 @@ export class Actor {
533
688
  return;
534
689
  }
535
690
  this.#isRebooting = true;
691
+ const { timeoutSecs = 30, customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
692
+ const callListeners = (event, data) => serviceLocator
693
+ .getEventManager()
694
+ .listeners(event)
695
+ .map(async (listener) => {
696
+ try {
697
+ await listener(data);
698
+ }
699
+ catch (err) {
700
+ log.exception(err, 'A pre-reboot event listener failed');
701
+ }
702
+ });
536
703
  // Waiting for all the listeners to finish, as `.reboot()` kills the container.
537
- await Promise.all([
704
+ // Not using `addTimeoutToPromise`, its timeout would also cancel the enclosing one (e.g. a request handler).
705
+ await timeoutPromise(Promise.all([
538
706
  // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
539
- ...serviceLocator
540
- .getEventManager()
541
- .listeners(EventType.PERSIST_STATE)
542
- .map(async (x) => x({})),
707
+ ...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
543
708
  // `migrating` to pause Apify crawlers
544
- ...serviceLocator
545
- .getEventManager()
546
- .listeners(EventType.MIGRATING)
547
- .map(async (x) => x({})),
548
- ]);
709
+ ...callListeners(EventType.MIGRATING, {}),
710
+ ]), timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
549
711
  const runId = this.configuration.actorRunId;
550
- await this.apifyClient.run(runId).reboot();
712
+ try {
713
+ await this.apifyClient.run(runId).reboot();
714
+ }
715
+ catch (err) {
716
+ // Reset the flag so that a failed reboot can be retried.
717
+ this.#isRebooting = false;
718
+ throw err;
719
+ }
551
720
  // Wait some time for container to be stopped.
552
- const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
553
721
  await sleep(customAfterSleepMillis);
554
722
  }
555
723
  /**
@@ -598,7 +766,8 @@ export class Actor {
598
766
  /**
599
767
  * Sets the status message for the current Actor run.
600
768
  *
601
- * @returns The return value is the Run object.
769
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
770
+ * or when the update failed or timed out (a warning is logged in that case).
602
771
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
603
772
  * @ignore
604
773
  */
@@ -626,17 +795,18 @@ export class Actor {
626
795
  }
627
796
  /**
628
797
  * Propagates a status message to the current run, without logging it locally.
798
+ * Resolves `undefined` when there is no run to update, or when the update failed or timed out.
629
799
  */
630
800
  async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
631
801
  const runId = this.configuration.actorRunId;
632
- if (runId) {
633
- // just to be sure, this should be fast
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
- }
802
+ if (!runId) {
803
+ return undefined;
638
804
  }
639
- return {};
805
+ // just to be sure, this should be fast
806
+ return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
807
+ log.warning(e.message);
808
+ return undefined;
809
+ });
640
810
  }
641
811
  /**
642
812
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -664,6 +834,7 @@ export class Actor {
664
834
  * @param item Object or array of objects containing data to be stored in the default dataset.
665
835
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
666
836
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
837
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
667
838
  * @ignore
668
839
  */
669
840
  async pushData(item, eventName) {
@@ -671,6 +842,9 @@ export class Actor {
671
842
  if (eventName?.startsWith('apify-')) {
672
843
  throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
673
844
  }
845
+ if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
846
+ 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.');
847
+ }
674
848
  if (eventName !== undefined) {
675
849
  rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
676
850
  'so a rolled-back request would be billed for items that were never stored.');
@@ -742,38 +916,10 @@ export class Actor {
742
916
  : undefined,
743
917
  });
744
918
  }
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) {
919
+ async getValue(key, defaultValue) {
774
920
  this.ensureActorInit('getValue');
775
921
  const store = await this.openKeyValueStore();
776
- return store.getValue(key);
922
+ return store.getValue(key, defaultValue);
777
923
  }
778
924
  /**
779
925
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -818,11 +964,15 @@ export class Actor {
818
964
  * A record stored as `application/octet-stream` — which is what a local input file without an
819
965
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
820
966
  *
821
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
822
- * `<inputKey>.json` file in the current working directory instead.
967
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
968
+ * working directory. A storage backend that doesn't read the default key-value store's directory under
969
+ * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
970
+ *
971
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
972
+ * replaced with the links of their CSV exports.
823
973
  *
824
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
825
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
974
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
975
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
826
976
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
827
977
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
828
978
  *
@@ -842,16 +992,24 @@ export class Actor {
842
992
  */
843
993
  async getInput() {
844
994
  this.ensureActorInit('getInput');
845
- const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase } = this.configuration;
995
+ const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
996
+ // Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
997
+ const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
846
998
  const store = await this.openKeyValueStore();
847
999
  const record = await store.getRecord(inputKey);
848
- const rawInput = record
1000
+ // Not a conflict check: under the file-system backend the record *is* the store directory's file.
1001
+ const storeInput = record
849
1002
  ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
850
- : await this.readInputFromWorkingDirectory(inputKey);
1003
+ : await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
1004
+ const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
1005
+ if (storeInput != null && cwdInput != null) {
1006
+ 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.`);
1007
+ }
1008
+ const rawInput = storeInput ?? cwdInput;
851
1009
  if (rawInput == null) {
852
1010
  const locations = [`the "${inputKey}" record of the default key-value store`];
853
1011
  if (!this.configuration.isAtHome) {
854
- locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working directory`);
1012
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
855
1013
  }
856
1014
  throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
857
1015
  }
@@ -871,19 +1029,19 @@ export class Actor {
871
1029
  }
872
1030
  }
873
1031
  if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
874
- input = await this.inferDefaultsFromInputSchema(input);
1032
+ input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
875
1033
  }
876
1034
  return input;
877
1035
  }
878
1036
  /**
879
- * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the working directory, for local runs
1037
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
880
1038
  * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
881
1039
  * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
882
1040
  * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
883
1041
  *
884
1042
  * @returns `undefined` when running on the platform or when neither file exists.
885
1043
  */
886
- async readInputFromWorkingDirectory(inputKey) {
1044
+ async readInputFromDirectory(inputKey, directory, label) {
887
1045
  if (this.configuration.isAtHome) {
888
1046
  return undefined;
889
1047
  }
@@ -893,20 +1051,20 @@ export class Actor {
893
1051
  ];
894
1052
  const found = [];
895
1053
  for (const candidate of candidates) {
896
- const path = join(process.cwd(), candidate.filename);
1054
+ const path = join(directory, candidate.filename);
897
1055
  const stats = await stat(path).catch(() => null);
898
1056
  if (stats?.isFile()) {
899
1057
  found.push({ ...candidate, path });
900
1058
  }
901
1059
  }
902
1060
  if (found.length > 1) {
903
- throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the working directory: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
1061
+ throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
904
1062
  }
905
1063
  if (found.length === 0) {
906
1064
  return undefined;
907
1065
  }
908
1066
  const [file] = found;
909
- return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the working directory`);
1067
+ return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
910
1068
  }
911
1069
  /**
912
1070
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -1031,6 +1189,10 @@ export class Actor {
1031
1189
  * rather than batching via `count` — this gives finer control over budget consumption
1032
1190
  * and avoids situations where more work is requested than the budget allows.
1033
1191
  *
1192
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1193
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1194
+ * be globally unique (e.g. derived from `requestId`).
1195
+ *
1034
1196
  * @param options The name of the event to charge for and the number of events to be charged.
1035
1197
  * @ignore
1036
1198
  */
@@ -1046,6 +1208,40 @@ export class Actor {
1046
1208
  this.ensureActorInit('getChargingManager');
1047
1209
  return this.#chargingManager;
1048
1210
  }
1211
+ /**
1212
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1213
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1214
+ * Resolves to `undefined` when not running on the Apify platform.
1215
+ */
1216
+ async getCurrentRun() {
1217
+ const runId = this.configuration.actorRunId;
1218
+ if (!runId) {
1219
+ return undefined;
1220
+ }
1221
+ this.#runPromise ??= this.apifyClient
1222
+ .run(runId)
1223
+ .get()
1224
+ .catch((err) => {
1225
+ this.#runPromise = undefined;
1226
+ throw err;
1227
+ });
1228
+ return this.#runPromise;
1229
+ }
1230
+ /** Cached for the lifetime of the Actor; only the charging manager needs it. */
1231
+ async #getCurrentActor() {
1232
+ const { actorId } = this.configuration;
1233
+ if (!actorId) {
1234
+ return undefined;
1235
+ }
1236
+ this.#actorPromise ??= this.apifyClient
1237
+ .actor(actorId)
1238
+ .get()
1239
+ .catch((err) => {
1240
+ this.#actorPromise = undefined;
1241
+ throw err;
1242
+ });
1243
+ return this.#actorPromise;
1244
+ }
1049
1245
  /**
1050
1246
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
1051
1247
  */
@@ -1078,17 +1274,22 @@ export class Actor {
1078
1274
  ...APIFY_ENV_VARS,
1079
1275
  ...this.getModifiedActorEnvVars(),
1080
1276
  })) {
1277
+ if (IGNORED_ENV_VARS.includes(fullName))
1278
+ continue;
1081
1279
  const camelCaseName = snakeCaseToCamelCase(shortName);
1082
1280
  let value = env[fullName];
1083
- // Parse dates and integers.
1084
- if (value && fullName.endsWith('_AT')) {
1281
+ // Parse booleans, dates and integers.
1282
+ if (BOOLEAN_ENV_VARS.includes(fullName)) {
1283
+ value = !!value && coerceBoolean.parse(value);
1284
+ }
1285
+ else if (value && fullName.endsWith('_AT')) {
1085
1286
  const unix = Date.parse(value);
1086
1287
  value = unix > 0 ? new Date(unix) : undefined;
1087
1288
  }
1088
1289
  else if (INTEGER_ENV_VARS.includes(fullName)) {
1089
1290
  value = parseInt(value, 10);
1090
1291
  }
1091
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1292
+ Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
1092
1293
  }
1093
1294
  return envVars;
1094
1295
  }
@@ -1131,7 +1332,7 @@ export class Actor {
1131
1332
  async useState(name, defaultValue = {}, options) {
1132
1333
  this.ensureActorInit('useState');
1133
1334
  const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
1134
- configuration: options?.configuration || Configuration.getGlobalConfiguration(),
1335
+ configuration: options?.configuration ?? this.configuration,
1135
1336
  });
1136
1337
  return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
1137
1338
  }
@@ -1313,6 +1514,31 @@ export class Actor {
1313
1514
  static async callTask(taskId, input, options = {}) {
1314
1515
  return Actor.getDefaultInstance().callTask(taskId, input, options);
1315
1516
  }
1517
+ /**
1518
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1519
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
1520
+ *
1521
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1522
+ *
1523
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
1524
+ *
1525
+ * **Example usage:**
1526
+ *
1527
+ * ```js
1528
+ * const run = await Actor.startTask('bob/some-task');
1529
+ * ```
1530
+ *
1531
+ * @param taskId
1532
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
1533
+ * @param [input]
1534
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
1535
+ * JSON and its content type set to `application/json; charset=utf-8`.
1536
+ * Provided input will be merged with Actor task input.
1537
+ * @param [options]
1538
+ */
1539
+ static async startTask(taskId, input, options = {}) {
1540
+ return Actor.getDefaultInstance().startTask(taskId, input, options);
1541
+ }
1316
1542
  /**
1317
1543
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1318
1544
  * unlike `Actor.call`, this method just starts the run without waiting for finish.
@@ -1338,6 +1564,21 @@ export class Actor {
1338
1564
  static async start(actorId, input, options = {}) {
1339
1565
  return Actor.getDefaultInstance().start(actorId, input, options);
1340
1566
  }
1567
+ /**
1568
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1569
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
1570
+ *
1571
+ * ```js
1572
+ * await Actor.childRuns['my-child'].waitForFinish();
1573
+ * ```
1574
+ *
1575
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
1576
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1577
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1578
+ */
1579
+ static get childRuns() {
1580
+ return Actor.getDefaultInstance().childRuns;
1581
+ }
1341
1582
  /**
1342
1583
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1343
1584
  *
@@ -1355,6 +1596,26 @@ export class Actor {
1355
1596
  static async abort(runId, options = {}) {
1356
1597
  return Actor.getDefaultInstance().abort(runId, options);
1357
1598
  }
1599
+ /**
1600
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1601
+ *
1602
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
1603
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
1604
+ *
1605
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1606
+ *
1607
+ * For more information about Actors, read the
1608
+ * [documentation](https://docs.apify.com/actor).
1609
+ *
1610
+ * **Example usage:**
1611
+ *
1612
+ * ```js
1613
+ * const run = await Actor.resurrect(runId);
1614
+ * ```
1615
+ */
1616
+ static async resurrect(runId, options = {}) {
1617
+ return Actor.getDefaultInstance().resurrect(runId, options);
1618
+ }
1358
1619
  /**
1359
1620
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
1360
1621
  * the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
@@ -1399,7 +1660,8 @@ export class Actor {
1399
1660
  * @param [options]
1400
1661
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1401
1662
  * This is required for the last status message of the run. Default value is `false`.
1402
- * @returns The return value is the Run object. When run locally, this method returns empty object (`{}`).
1663
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1664
+ * or when the update failed or timed out (a warning is logged in that case).
1403
1665
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1404
1666
  */
1405
1667
  static async setStatusMessage(statusMessage, options) {
@@ -1428,6 +1690,7 @@ export class Actor {
1428
1690
  * @param item Object or array of objects containing data to be stored in the default dataset.
1429
1691
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1430
1692
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1693
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1431
1694
  */
1432
1695
  static async pushData(item, eventName) {
1433
1696
  if (eventName === undefined) {
@@ -1454,35 +1717,8 @@ export class Actor {
1454
1717
  static async openDataset(datasetIdOrName, options = {}) {
1455
1718
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1456
1719
  }
1457
- /**
1458
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
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);
1720
+ static async getValue(key, defaultValue) {
1721
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1486
1722
  }
1487
1723
  /**
1488
1724
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1528,11 +1764,14 @@ export class Actor {
1528
1764
  * A record stored as `application/octet-stream` — which is what a local input file without an
1529
1765
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1530
1766
  *
1531
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
1532
- * `<inputKey>.json` file in the current working directory instead.
1767
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1768
+ * working directory.
1533
1769
  *
1534
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
1535
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
1770
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
1771
+ * replaced with the links of their CSV exports.
1772
+ *
1773
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1774
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1536
1775
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1537
1776
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1538
1777
  * ```js
@@ -1652,6 +1891,10 @@ export class Actor {
1652
1891
  * rather than batching via `count` — this gives finer control over budget consumption
1653
1892
  * and avoids situations where more work is requested than the budget allows.
1654
1893
  *
1894
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1895
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1896
+ * be globally unique (e.g. derived from `requestId`).
1897
+ *
1655
1898
  * @param options The name of the event to charge for and the number of events to be charged.
1656
1899
  */
1657
1900
  static async charge(options) {
@@ -1689,6 +1932,14 @@ export class Actor {
1689
1932
  static isAtHome() {
1690
1933
  return Actor.getDefaultInstance().isAtHome();
1691
1934
  }
1935
+ /**
1936
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1937
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1938
+ * Resolves to `undefined` when not running on the Apify platform.
1939
+ */
1940
+ static async getCurrentRun() {
1941
+ return Actor.getDefaultInstance().getCurrentRun();
1942
+ }
1692
1943
  /** Default {@link ApifyClient} instance. */
1693
1944
  static get apifyClient() {
1694
1945
  return Actor.getDefaultInstance().apifyClient;