apify 4.0.0-beta.15 → 4.0.0-beta.151

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.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +416 -281
  3. package/dist/actor.js +743 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +88 -0
  11. package/dist/apify_request_queue_backend.js +123 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +201 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +265 -0
  16. package/dist/apify_storage_backend.d.ts +95 -0
  17. package/dist/apify_storage_backend.js +219 -0
  18. package/dist/charging.d.ts +77 -47
  19. package/dist/charging.js +348 -226
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +110 -0
  23. package/dist/child_run_tracker.js +333 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +66 -12
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +32 -21
  38. package/dist/proxy_configuration.js +137 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
package/dist/actor.js CHANGED
@@ -1,21 +1,40 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
- import { Dataset, purgeDefaultStorages, RequestQueue, serviceLocator } from '@crawlee/core';
3
- import { sleep, snakeCaseToCamelCase } from '@crawlee/utils';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
5
+ import { sleep } from '@crawlee/utils';
4
6
  import { ApifyClient } from 'apify-client';
5
- import ow from 'ow';
6
- import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, } from '@apify/consts';
7
+ import { z } from 'zod';
8
+ import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, META_ORIGINS } from '@apify/consts';
7
9
  import { decryptInputSecrets } from '@apify/input_secrets';
8
10
  import log from '@apify/log';
9
11
  import { addTimeoutToPromise } from '@apify/timeout';
10
- import { ApifyStorageClient, pushDataChargingContext, USES_PUSH_DATA_INTERCEPTION, } from './apify_storage_client.js';
11
- import { ChargingManager, pushDataAndCharge } from './charging.js';
12
+ import { parseArgument } from '@apify/validations';
13
+ import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
14
+ import { ApifyStorageBackend } from './apify_storage_backend.js';
15
+ import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
16
+ import { ChargingStorageBackend } from './charging_storage_backend.js';
17
+ import { ChildRunTracker } from './child_run_tracker.js';
12
18
  import { Configuration } from './configuration.js';
19
+ import { ActorInputError } from './errors.js';
20
+ import { fixGoogleSheetsUrls } from './google_sheets.js';
13
21
  import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
14
- import { KeyValueStore } from './key_value_store.js';
15
22
  import { PlatformEventManager } from './platform_event_manager.js';
16
23
  import { ProxyConfiguration } from './proxy_configuration.js';
17
- import { openStorage } from './storage.js';
18
- import { checkCrawleeVersion, getSystemInfo, printOutdatedSdkWarning } from './utils.js';
24
+ import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
25
+ import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, } from './utils.js';
26
+ /**
27
+ * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
28
+ * JSON input reports where it came from.
29
+ */
30
+ function parseInput(value, contentType, source) {
31
+ try {
32
+ return parseInputValue(value, contentType);
33
+ }
34
+ catch (cause) {
35
+ throw new ActorInputError('PARSE_FAILED', `The input in ${source} is not valid JSON.`, { cause });
36
+ }
37
+ }
19
38
  /**
20
39
  * Exit codes for the Actor process.
21
40
  * The error codes must be in the range 1-128, to avoid collision with signal exits
@@ -34,12 +53,13 @@ export const EXIT_CODES = {
34
53
  */
35
54
  export class Actor {
36
55
  /** @internal */
37
- static _instance;
56
+ static #instance;
57
+ #childRunTracker;
38
58
  /**
39
59
  * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
40
60
  * @internal
41
61
  */
42
- config;
62
+ configuration;
43
63
  /**
44
64
  * Default {@link ApifyClient} instance.
45
65
  * @internal
@@ -58,26 +78,34 @@ export class Actor {
58
78
  * Set if the Actor called a method that requires the instance to be initialized, but did not do so.
59
79
  * A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
60
80
  */
61
- warnedAboutMissingInitCall = false;
81
+ #warnedAboutMissingInitCall = false;
62
82
  /**
63
83
  * Set if the Actor is currently rebooting.
64
84
  */
65
- isRebooting = false;
85
+ #isRebooting = false;
66
86
  /**
67
87
  * Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
68
88
  */
69
- isExiting = false;
89
+ #isExiting = false;
70
90
  /**
71
91
  * References to graceful shutdown handlers so they can be removed during cleanup.
72
92
  */
73
- gracefulShutdownHandlers = {};
74
- chargingManager;
75
- /**
76
- * Tracks which aliased storages have been purged during this session,
77
- * so we only purge them once (on first open) when running locally.
78
- * @internal
79
- */
80
- purgedStorageAliases = new Set();
93
+ #gracefulShutdownHandlers = {};
94
+ /**
95
+ * Reference to the crawlee status message forwarder, so it can be removed during cleanup.
96
+ */
97
+ #statusMessageForwarder;
98
+ #chargingManager;
99
+ #runPromise;
100
+ #actorPromise;
101
+ /** Aborts the child runs started with `abortWithParent` on the `aborting` event, or in `Actor.exit()`. */
102
+ #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent();
103
+ /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
104
+ #requestQueueAccess = 'single';
105
+ /** Lazily built by the `#storageBackend` getter. */
106
+ #cachedStorageBackend;
107
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
108
+ #pendingListeners = [];
81
109
  constructor(options = {}) {
82
110
  const { configuration, ...configOptions } = options;
83
111
  if (configuration) {
@@ -91,18 +119,21 @@ export class Actor {
91
119
  throw new Error('Actor `configuration` must be an Apify SDK Configuration (imported from `apify`), ' +
92
120
  'not a crawlee Configuration, otherwise APIFY_*/ACTOR_* environment variables are not resolved.');
93
121
  }
94
- this.config = configuration;
122
+ this.configuration = configuration;
95
123
  }
96
124
  else if (Object.keys(configOptions).length === 0) {
97
125
  // use default configuration object if nothing overridden (it fallbacks to env vars)
98
- this.config = Configuration.getGlobalConfig();
126
+ this.configuration = Configuration.getGlobalConfiguration();
99
127
  }
100
128
  else {
101
- this.config = new Configuration(configOptions);
129
+ this.configuration = new Configuration(configOptions);
102
130
  }
103
131
  this.apifyClient = this.newClient();
104
- this.eventManager = new PlatformEventManager(this.config);
105
- this.chargingManager = new ChargingManager(this.config, this.apifyClient);
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(this.apifyClient);
106
137
  }
107
138
  /**
108
139
  * Runs the main user function that performs the job of the Actor
@@ -139,24 +170,22 @@ export class Actor {
139
170
  *
140
171
  * If the user function returns a promise, it is considered asynchronous:
141
172
  * ```js
142
- * import { gotScraping } from 'got-scraping';
143
- *
144
173
  * await Actor.main(() => {
145
174
  * // My asynchronous function that returns a promise
146
- * return gotScraping('http://www.example.com').then((html) => {
147
- * console.log(html);
148
- * });
175
+ * return fetch('http://www.example.com')
176
+ * .then((response) => response.text())
177
+ * .then((html) => {
178
+ * console.log(html);
179
+ * });
149
180
  * });
150
181
  * ```
151
182
  *
152
183
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
153
184
  *
154
185
  * ```js
155
- * import { gotScraping } from 'got-scraping';
156
- *
157
186
  * await Actor.main(async () => {
158
187
  * // My asynchronous function
159
- * const html = await request('http://www.example.com');
188
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
160
189
  * console.log(html);
161
190
  * });
162
191
  * ```
@@ -179,9 +208,7 @@ export class Actor {
179
208
  }
180
209
  catch (err) {
181
210
  log.exception(err, err.message);
182
- await this.exit({
183
- exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
184
- });
211
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
185
212
  }
186
213
  return ret;
187
214
  })();
@@ -195,71 +222,103 @@ export class Actor {
195
222
  return;
196
223
  }
197
224
  // If the warning about forgotten init call was emitted, we will not continue the init procedure.
198
- if (this.warnedAboutMissingInitCall) {
225
+ if (this.#warnedAboutMissingInitCall) {
199
226
  throw new Error([
200
227
  'Actor.init() was called after a method that would access a storage client was used.',
201
228
  'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
202
229
  ].join('\n'));
203
230
  }
231
+ this.#childRunTracker.configure(options);
204
232
  this.initialized = true;
205
233
  checkCrawleeVersion();
206
234
  log.info('System info', getSystemInfo());
207
- printOutdatedSdkWarning();
208
235
  // Register this Actor's config as the global one so crawlee storages and
209
236
  // the event manager resolve the same instance (`availableMemoryRatio` /
210
237
  // `disableBrowserSandbox` at-home defaults now live in `Configuration`).
211
- serviceLocator.setConfiguration(this.config);
238
+ serviceLocator.setConfiguration(this.configuration);
239
+ this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
212
240
  if (this.isAtHome()) {
213
- serviceLocator.setStorageClient(new ApifyStorageClient(this.apifyClient, this.config, () => this.chargingManager));
214
241
  serviceLocator.setEventManager(this.eventManager);
215
242
  }
243
+ if (!serviceLocator.getServicesIfSet().storageBackend) {
244
+ this.installStorageBackend(options.storage ?? this.#storageBackend);
245
+ }
216
246
  else if (options.storage) {
217
- serviceLocator.setStorageClient(options.storage);
247
+ this.installStorageBackend(options.storage);
218
248
  }
219
- // Init the event manager the config uses
220
- await serviceLocator.getEventManager().init();
221
- log.debug(`Events initialized`);
222
249
  // Register handlers for aborting and migrating events for automatic graceful shutdown.
223
250
  // - aborting: calls Actor.exit() to terminate the run gracefully
224
251
  // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
225
252
  // Using setTimeout to avoid deadlock with waitForAllListenersToComplete() in exit()/reboot()
226
253
  if (options.gracefulShutdown !== false) {
227
254
  const delay = options.gracefulShutdownDelayMillis ?? 0;
228
- this.gracefulShutdownHandlers.aborting = () => {
255
+ this.#gracefulShutdownHandlers.aborting = () => {
229
256
  setTimeout(() => {
230
257
  this.exit().catch((err) => {
231
258
  log.exception(err, 'Failed to exit gracefully');
232
259
  });
233
260
  }, delay);
234
261
  };
235
- this.on(ACTOR_EVENT_NAMES.ABORTING, this.gracefulShutdownHandlers.aborting);
236
- this.gracefulShutdownHandlers.migrating = () => {
262
+ this.on(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
263
+ this.#gracefulShutdownHandlers.migrating = () => {
237
264
  setTimeout(() => {
238
265
  this.reboot().catch((err) => {
239
266
  log.exception(err, 'Failed to reboot on migration');
240
267
  });
241
268
  }, delay);
242
269
  };
243
- this.on(ACTOR_EVENT_NAMES.MIGRATING, this.gracefulShutdownHandlers.migrating);
270
+ this.on(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
244
271
  }
272
+ // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
273
+ this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
274
+ this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
275
+ // Attach listeners queued before init(), then connect to the platform events only after all handlers
276
+ // are registered, so that an event sent right after the connection opens (e.g. an already pending
277
+ // `aborting`) is not missed.
278
+ const events = serviceLocator.getEventManager();
279
+ if (this.#pendingListeners.length > 0) {
280
+ for (const [event, listener] of this.#pendingListeners) {
281
+ events.on(event, listener);
282
+ }
283
+ log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
284
+ this.#pendingListeners = [];
285
+ }
286
+ await events.init();
287
+ log.debug(`Events initialized`);
245
288
  await purgeDefaultStorages({
246
- config: this.config,
289
+ configuration: this.configuration,
247
290
  onlyPurgeOnce: true,
248
291
  });
249
292
  log.debug(`Default storages purged`);
250
- await this.chargingManager.init();
251
- log.debug(`ChargingManager initialized`, this.chargingManager.getPricingInfo());
293
+ await this.#childRunTracker.load();
294
+ this.#runPromise = undefined;
295
+ this.#actorPromise = undefined;
296
+ if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
297
+ // Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
298
+ void this.getCurrentRun().catch(() => { });
299
+ void this.#getCurrentActor().catch(() => { });
300
+ }
301
+ await this.#chargingManager.init();
302
+ log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
303
+ // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
304
+ // registered with crawlee directly; the storages the Actor installs itself are wrapped.
305
+ if (this.#chargingManager.isPayPerEvent &&
306
+ !this.#chargingManager.isMultiTenant &&
307
+ !this.#chargesDefaultDatasetItems()) {
308
+ log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
309
+ 'storage - the platform only counts items it stores itself.');
310
+ }
252
311
  }
253
312
  /**
254
313
  * @ignore
255
314
  */
256
315
  async exit(messageOrOptions, options = {}) {
257
316
  // Prevent double-exit from graceful shutdown handlers
258
- if (this.isExiting) {
317
+ if (this.#isExiting) {
259
318
  log.debug('Actor.exit() called while already exiting, skipping');
260
319
  return;
261
320
  }
262
- this.isExiting = true;
321
+ this.#isExiting = true;
263
322
  options =
264
323
  typeof messageOrOptions === 'string'
265
324
  ? { ...options, statusMessage: messageOrOptions }
@@ -267,21 +326,24 @@ export class Actor {
267
326
  options.exit ??= true;
268
327
  options.exitCode ??= EXIT_CODES.SUCCESS;
269
328
  options.timeoutSecs ??= 30;
270
- this._ensureActorInit('exit');
271
- const client = serviceLocator.getStorageClient();
329
+ this.ensureActorInit('exit');
330
+ const client = serviceLocator.getStorageBackend();
272
331
  const events = serviceLocator.getEventManager();
273
332
  // Remove graceful shutdown handlers to prevent them from interfering with exit
274
- if (this.gracefulShutdownHandlers.aborting) {
275
- this.off(ACTOR_EVENT_NAMES.ABORTING, this.gracefulShutdownHandlers.aborting);
333
+ if (this.#gracefulShutdownHandlers.aborting) {
334
+ this.off(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
276
335
  }
277
- if (this.gracefulShutdownHandlers.migrating) {
278
- this.off(ACTOR_EVENT_NAMES.MIGRATING, this.gracefulShutdownHandlers.migrating);
336
+ if (this.#gracefulShutdownHandlers.migrating) {
337
+ this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
279
338
  }
339
+ await this.#abortChildRunsWithParent();
340
+ // Writes the charged event counts one last time, so that a resurrected run continues from them.
341
+ await this.#chargingManager.teardown();
280
342
  // Close the event manager and emit the final PERSIST_STATE event
281
343
  await events.close();
282
344
  log.debug(`Events closed`);
283
345
  // Emit the exit event
284
- events.emit("exit" /* EventType.EXIT */, options);
346
+ events.emit(EventType.EXIT, options);
285
347
  // Wait for all event listeners to be processed
286
348
  log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
287
349
  if (options.exit) {
@@ -293,6 +355,11 @@ export class Actor {
293
355
  }
294
356
  await addTimeoutToPromise(async () => {
295
357
  await events.waitForAllListenersToComplete();
358
+ // The final status messages have been forwarded by now; stop listening so
359
+ // that a periodic one can't overwrite the terminal message set below.
360
+ if (this.#statusMessageForwarder) {
361
+ this.off(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
362
+ }
296
363
  if (client.teardown) {
297
364
  let finished = false;
298
365
  setTimeout(() => {
@@ -318,7 +385,8 @@ export class Actor {
318
385
  });
319
386
  // Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
320
387
  // When process.exit() actually terminates the process, this line is never reached - which is fine.
321
- this.isExiting = false;
388
+ this.#isExiting = false;
389
+ this.#childRunTracker.resetAbort();
322
390
  if (!options.exit) {
323
391
  return;
324
392
  }
@@ -328,18 +396,29 @@ export class Actor {
328
396
  * @ignore
329
397
  */
330
398
  async fail(messageOrOptions, options = {}) {
331
- return this.exit(messageOrOptions, { exitCode: 1, ...options });
399
+ const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
400
+ return this.exit(messageOrOptions, { ...options, exitCode });
332
401
  }
333
402
  /**
334
403
  * @ignore
335
404
  */
336
405
  on(event, listener) {
406
+ // Before init() the service locator must stay untouched, otherwise it
407
+ // creates a default Configuration that init() then conflicts with.
408
+ if (!this.initialized) {
409
+ this.#pendingListeners.push([event, listener]);
410
+ return;
411
+ }
337
412
  serviceLocator.getEventManager().on(event, listener);
338
413
  }
339
414
  /**
340
415
  * @ignore
341
416
  */
342
417
  off(event, listener) {
418
+ if (!this.initialized) {
419
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
420
+ return;
421
+ }
343
422
  serviceLocator.getEventManager().off(event, listener);
344
423
  }
345
424
  /**
@@ -360,17 +439,45 @@ export class Actor {
360
439
  * @param actorId
361
440
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
362
441
  * @param [input]
363
- * Input for the Actor. If it is an object, it will be stringified to
364
- * JSON and its content type set to `application/json; charset=utf-8`.
365
- * Otherwise the `options.contentType` parameter must be provided.
442
+ * Input for the Actor. A plain object is stringified to JSON with content type
443
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
366
444
  * @param [options]
367
445
  * @ignore
368
446
  */
369
447
  async call(actorId, input, options = {}) {
370
- const timeout = options.timeout === 'inherit' ? this.getRemainingTime() : options.timeout;
371
- const { token, ...rest } = options;
448
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
449
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
372
450
  const client = token ? this.newClient({ token }) : this.apifyClient;
373
- return client.actor(actorId).call(input, { ...rest, timeout });
451
+ // Like `ActorClient.call()`, but the run is recorded before it is waited for.
452
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
453
+ const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
454
+ return this.#waitForChildRun(client, run, { log, waitSecs, timeoutSecs, signal });
455
+ }
456
+ /**
457
+ * Waits for a child run to finish while its log is redirected, like `call()` of `apify-client`, and records the
458
+ * status it finished in.
459
+ */
460
+ async #waitForChildRun(client, run, { log: toLog, ...waitOptions }) {
461
+ const runClient = client.run(run.id);
462
+ let streamedLog;
463
+ try {
464
+ streamedLog = await runClient.getStreamedLog({ toLog, signal: waitOptions.signal });
465
+ }
466
+ catch (error) {
467
+ // An aborted call rejects with the reason of its signal, which the wait below takes care of.
468
+ if (!waitOptions.signal?.aborted) {
469
+ log.warning(`Waiting for run ${run.id} without log redirection, which could not be set up: ${error.message}`);
470
+ }
471
+ }
472
+ streamedLog?.start();
473
+ try {
474
+ const finishedRun = await runClient.waitForFinish(waitOptions);
475
+ await this.#childRunTracker.update(finishedRun);
476
+ return finishedRun;
477
+ }
478
+ finally {
479
+ await streamedLog?.stop();
480
+ }
374
481
  }
375
482
  /**
376
483
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -390,17 +497,16 @@ export class Actor {
390
497
  * @param actorId
391
498
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
392
499
  * @param [input]
393
- * Input for the Actor. If it is an object, it will be stringified to
394
- * JSON and its content type set to `application/json; charset=utf-8`.
395
- * Otherwise the `options.contentType` parameter must be provided.
500
+ * Input for the Actor. A plain object is stringified to JSON with content type
501
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
396
502
  * @param [options]
397
503
  * @ignore
398
504
  */
399
505
  async start(actorId, input, options = {}) {
400
- const timeout = options.timeout === 'inherit' ? this.getRemainingTime() : options.timeout;
401
- const { token, ...rest } = options;
506
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
507
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
402
508
  const client = token ? this.newClient({ token }) : this.apifyClient;
403
- return client.actor(actorId).start(input, { ...rest, timeout });
509
+ return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...rest, runTimeoutSecs }));
404
510
  }
405
511
  /**
406
512
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -420,12 +526,35 @@ export class Actor {
420
526
  async abort(runId, options = {}) {
421
527
  const { token, statusMessage, ...rest } = options;
422
528
  const client = token ? this.newClient({ token }) : this.apifyClient;
529
+ const runClient = client.run(runId);
423
530
  if (statusMessage) {
424
- await this.setStatusMessage(statusMessage, {
425
- isStatusMessageTerminal: true,
426
- });
531
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
427
532
  }
428
- return client.run(runId).abort(rest);
533
+ return runClient.abort(rest);
534
+ }
535
+ /**
536
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
537
+ *
538
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
539
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
540
+ *
541
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
542
+ *
543
+ * For more information about Actors, read the
544
+ * [documentation](https://docs.apify.com/actor).
545
+ *
546
+ * **Example usage:**
547
+ *
548
+ * ```js
549
+ * const run = await Actor.resurrect(runId);
550
+ * ```
551
+ * @ignore
552
+ */
553
+ async resurrect(runId, options = {}) {
554
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
555
+ const { token, timeout: _timeout, ...rest } = options;
556
+ const client = token ? this.newClient({ token }) : this.apifyClient;
557
+ return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
429
558
  }
430
559
  /**
431
560
  * Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -454,10 +583,60 @@ export class Actor {
454
583
  * @ignore
455
584
  */
456
585
  async callTask(taskId, input, options = {}) {
457
- const timeout = options.timeout === 'inherit' ? this.getRemainingTime() : options.timeout;
458
- const { token, ...rest } = options;
586
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
587
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
459
588
  const client = token ? this.newClient({ token }) : this.apifyClient;
460
- return client.task(taskId).call(input, { ...rest, timeout });
589
+ // Like `TaskClient.call()`, but the run is recorded before it is waited for.
590
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
591
+ const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
592
+ return this.#waitForChildRun(client, run, { log, waitSecs, timeoutSecs, signal });
593
+ }
594
+ /**
595
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
596
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
597
+ * migration, reboot or resurrection of this run.
598
+ *
599
+ * ```js
600
+ * const childRuns = await Actor.childRuns();
601
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
602
+ * ```
603
+ *
604
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
605
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
606
+ * resurrection of this run, which uses the default client.
607
+ */
608
+ async childRuns() {
609
+ this.ensureActorInit('childRuns');
610
+ return this.#childRunTracker.getRunClients();
611
+ }
612
+ /**
613
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
614
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
615
+ *
616
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
617
+ *
618
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
619
+ *
620
+ * **Example usage:**
621
+ *
622
+ * ```js
623
+ * const run = await Actor.startTask('bob/some-task');
624
+ * ```
625
+ *
626
+ * @param taskId
627
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
628
+ * @param [input]
629
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
630
+ * JSON and its content type set to `application/json; charset=utf-8`.
631
+ * Provided input will be merged with Actor task input.
632
+ * @param [options]
633
+ * @ignore
634
+ */
635
+ async startTask(taskId, input, options = {}) {
636
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
637
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
638
+ const client = token ? this.newClient({ token }) : this.apifyClient;
639
+ return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...rest, runTimeoutSecs }));
461
640
  }
462
641
  /**
463
642
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -467,9 +646,8 @@ export class Actor {
467
646
  * @param targetActorId
468
647
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
469
648
  * @param [input]
470
- * Input for the Actor. If it is an object, it will be stringified to
471
- * JSON and its content type set to `application/json; charset=utf-8`.
472
- * Otherwise, the `options.contentType` parameter must be provided.
649
+ * Input for the Actor. A plain object is stringified to JSON with content type
650
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
473
651
  * @param [options]
474
652
  * @ignore
475
653
  */
@@ -478,8 +656,10 @@ export class Actor {
478
656
  log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
479
657
  return;
480
658
  }
481
- const { customAfterSleepMillis = this.config.metamorphAfterSleepMillis, ...metamorphOpts } = options;
482
- const runId = this.config.actorRunId;
659
+ const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
660
+ const runId = this.configuration.actorRunId;
661
+ // The target Actor would not know about a child run whose start is not recorded yet.
662
+ await this.#childRunTracker.waitForStartsInFlight();
483
663
  await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
484
664
  // Wait some time for container to be stopped.
485
665
  await sleep(customAfterSleepMillis);
@@ -492,33 +672,49 @@ export class Actor {
492
672
  * @ignore
493
673
  */
494
674
  async reboot(options = {}) {
495
- this._ensureActorInit('reboot');
675
+ this.ensureActorInit('reboot');
496
676
  if (!this.isAtHome()) {
497
677
  log.warning('Actor.reboot() is only supported when running on the Apify platform.');
498
678
  return;
499
679
  }
500
- if (this.isRebooting) {
680
+ if (this.#isRebooting) {
501
681
  log.debug('Actor is already rebooting, skipping the additional reboot call.');
502
682
  return;
503
683
  }
504
- this.isRebooting = true;
684
+ this.#isRebooting = true;
685
+ const { timeoutSecs = 30, customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
686
+ const callListeners = (event, data) => serviceLocator
687
+ .getEventManager()
688
+ .listeners(event)
689
+ .map(async (listener) => {
690
+ try {
691
+ await listener(data);
692
+ }
693
+ catch (err) {
694
+ log.exception(err, 'A pre-reboot event listener failed');
695
+ }
696
+ });
505
697
  // Waiting for all the listeners to finish, as `.reboot()` kills the container.
506
- await Promise.all([
507
- // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
508
- ...serviceLocator
509
- .getEventManager()
510
- .listeners("persistState" /* EventType.PERSIST_STATE */)
511
- .map(async (x) => x({})),
512
- // `migrating` to pause Apify crawlers
513
- ...serviceLocator
514
- .getEventManager()
515
- .listeners("migrating" /* EventType.MIGRATING */)
516
- .map(async (x) => x({})),
517
- ]);
518
- const runId = this.config.actorRunId;
519
- await this.apifyClient.run(runId).reboot();
698
+ await addTimeoutToPromise(async () => {
699
+ await Promise.all([
700
+ // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
701
+ ...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
702
+ // `migrating` to pause Apify crawlers
703
+ ...callListeners(EventType.MIGRATING, {}),
704
+ ]);
705
+ }, timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
706
+ const runId = this.configuration.actorRunId;
707
+ // The new container would not know about a child run whose start is not recorded yet.
708
+ await this.#childRunTracker.waitForStartsInFlight();
709
+ try {
710
+ await this.apifyClient.run(runId).reboot();
711
+ }
712
+ catch (err) {
713
+ // Reset the flag so that a failed reboot can be retried.
714
+ this.#isRebooting = false;
715
+ throw err;
716
+ }
520
717
  // Wait some time for container to be stopped.
521
- const { customAfterSleepMillis = this.config.metamorphAfterSleepMillis } = options;
522
718
  await sleep(customAfterSleepMillis);
523
719
  }
524
720
  /**
@@ -534,23 +730,25 @@ export class Actor {
534
730
  * @ignore
535
731
  */
536
732
  async addWebhook(options) {
537
- ow(options, ow.object.exactShape({
538
- eventTypes: ow.array.ofType(ow.string),
539
- requestUrl: ow.string,
540
- payloadTemplate: ow.optional.string,
541
- idempotencyKey: ow.optional.string,
542
- headersTemplate: ow.optional.string,
543
- description: ow.optional.string,
544
- ignoreSslErrors: ow.optional.boolean,
545
- doNotRetry: ow.optional.boolean,
546
- shouldInterpolateStrings: ow.optional.boolean,
547
- isApifyIntegration: ow.optional.boolean,
548
- }));
733
+ parseArgument(options, z
734
+ .object({
735
+ eventTypes: z.array(z.string()),
736
+ requestUrl: z.string(),
737
+ payloadTemplate: z.string().optional(),
738
+ idempotencyKey: z.string().optional(),
739
+ headersTemplate: z.string().optional(),
740
+ description: z.string().optional(),
741
+ ignoreSslErrors: z.boolean().optional(),
742
+ doNotRetry: z.boolean().optional(),
743
+ shouldInterpolateStrings: z.boolean().optional(),
744
+ isApifyIntegration: z.boolean().optional(),
745
+ })
746
+ .strict());
549
747
  if (!this.isAtHome()) {
550
748
  log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
551
749
  return undefined;
552
750
  }
553
- const runId = this.config.actorRunId;
751
+ const runId = this.configuration.actorRunId;
554
752
  if (!runId) {
555
753
  throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
556
754
  }
@@ -565,15 +763,16 @@ export class Actor {
565
763
  /**
566
764
  * Sets the status message for the current Actor run.
567
765
  *
568
- * @returns The return value is the Run object.
766
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
767
+ * or when the update failed or timed out (a warning is logged in that case).
569
768
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
570
769
  * @ignore
571
770
  */
572
771
  async setStatusMessage(statusMessage, options) {
573
772
  const { isStatusMessageTerminal, level } = options || {};
574
- ow(statusMessage, ow.string);
575
- ow(isStatusMessageTerminal, ow.optional.boolean);
576
- this._ensureActorInit('setStatusMessage');
773
+ parseArgument(statusMessage, z.string());
774
+ parseArgument(isStatusMessageTerminal, z.boolean().optional());
775
+ this.ensureActorInit('setStatusMessage');
577
776
  const loggedStatusMessage = `[Status message]: ${statusMessage}`;
578
777
  switch (level) {
579
778
  case 'DEBUG':
@@ -589,21 +788,22 @@ export class Actor {
589
788
  log.info(loggedStatusMessage);
590
789
  break;
591
790
  }
592
- const client = serviceLocator.getStorageClient();
593
- // just to be sure, this should be fast
594
- await addTimeoutToPromise(async () => client.setStatusMessage(statusMessage, {
595
- isStatusMessageTerminal,
596
- level,
597
- }), 1000, 'Setting status message timed out after 1s').catch((e) => log.warning(e.message));
598
- const runId = this.config.actorRunId;
599
- if (runId) {
600
- // just to be sure, this should be fast
601
- const run = await addTimeoutToPromise(async () => this.apifyClient.run(runId).get(), 1000, 'Getting the current run timed out after 1s').catch((e) => log.warning(e.message));
602
- if (run) {
603
- return run;
604
- }
791
+ return this.#updateRunStatusMessage(statusMessage, isStatusMessageTerminal);
792
+ }
793
+ /**
794
+ * Propagates a status message to the current run, without logging it locally.
795
+ * Resolves `undefined` when there is no run to update, or when the update failed or timed out.
796
+ */
797
+ async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
798
+ const runId = this.configuration.actorRunId;
799
+ if (!runId) {
800
+ return undefined;
605
801
  }
606
- return {};
802
+ // just to be sure, this should be fast
803
+ return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
804
+ log.warning(e.message);
805
+ return undefined;
806
+ });
607
807
  }
608
808
  /**
609
809
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -625,27 +825,67 @@ export class Actor {
625
825
  * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
626
826
  * otherwise the Actor process might finish before the data are stored!
627
827
  *
828
+ * Inside a crawlee storage transaction, the items are stored - and charged for - at commit time,
829
+ * so the returned counts are zero and charging for an explicit `eventName` is rejected outright.
830
+ *
628
831
  * @param item Object or array of objects containing data to be stored in the default dataset.
629
832
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
630
833
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
834
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
631
835
  * @ignore
632
836
  */
633
837
  async pushData(item, eventName) {
634
- this._ensureActorInit('pushData');
838
+ this.ensureActorInit('pushData');
635
839
  if (eventName?.startsWith('apify-')) {
636
840
  throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
637
841
  }
842
+ if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
843
+ 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.');
844
+ }
845
+ if (eventName !== undefined) {
846
+ rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
847
+ 'so a rolled-back request would be billed for items that were never stored.');
848
+ }
638
849
  const dataset = await this.openDataset();
639
- // Two code paths for charging:
640
- // 1. Intercepted client: PatchedDatasetClient intercepts pushItems() calls, handling charging
641
- // internally. This is needed because Crawlee's Dataset may call pushItems() directly,
642
- // bypassing Actor.pushData(). We propagate eventName via AsyncLocalStorage context.
643
- // 2. Direct charging: When using a non-patched client (e.g., forceCloud option or custom client),
644
- // we handle charging here before delegating to the dataset.
645
- if (this.usesPushDataInterception(dataset)) {
646
- return await this.pushDataViaInterceptedClient(dataset, item, eventName);
850
+ const items = Array.isArray(item) ? item : [item];
851
+ // `Actor.pushData()` historically worked even without calling `Actor.init()`.
852
+ // In that case, charging isn't configured, so just push the data through.
853
+ if (!this.#chargingManager.isInitialized) {
854
+ await dataset.pushData(items);
855
+ return { eventChargeLimitReached: false, chargedCount: 0, chargeableWithinLimit: {} };
647
856
  }
648
- return await this.pushDataWithExplicitCharging(dataset, item, eventName);
857
+ // The reservation below and the charge that acts on it have to stay under one lock, so that
858
+ // a concurrent push cannot charge in between. The dataset backend re-enters the same lock to
859
+ // charge the synthetic per-item event.
860
+ return await this.#chargingManager.withChargeLock(async () => {
861
+ if (eventName === undefined) {
862
+ // Nothing to charge here - the dataset backend charges the synthetic event for
863
+ // whatever it stores, so the result is read back off the charging state.
864
+ const chargedBefore = this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT);
865
+ await dataset.pushData(items);
866
+ return {
867
+ eventChargeLimitReached: this.#chargingManager.isEventChargeLimitReached(DEFAULT_DATASET_ITEM_EVENT),
868
+ chargedCount: this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT) - chargedBefore,
869
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
870
+ };
871
+ }
872
+ const limit = this.#chargingManager.calculatePushDataLimit(items.length, {
873
+ eventName,
874
+ // Pushing one item charges the synthetic per-item event too when the dataset backend
875
+ // is the charging one, so that price is part of what an item costs here. Only the Actor's
876
+ // own backend wraps the default dataset for charging, a caller-supplied one is left as is.
877
+ isDefaultDataset: serviceLocator.getStorageBackend() === this.#cachedStorageBackend,
878
+ });
879
+ if (limit === 0) {
880
+ return {
881
+ eventChargeLimitReached: items.length > 0,
882
+ chargedCount: 0,
883
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
884
+ };
885
+ }
886
+ await dataset.pushData(limit < items.length ? items.slice(0, limit) : items);
887
+ return await this.#chargingManager.charge({ eventName, count: limit });
888
+ });
649
889
  }
650
890
  /**
651
891
  * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
@@ -659,50 +899,24 @@ export class Actor {
659
899
  * @param [datasetIdOrName]
660
900
  * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
661
901
  * the function returns the default dataset associated with the Actor run.
662
- * You can also pass `{ alias: 'name' }` to open a dataset defined in the Actor's schema storages,
663
- * `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
902
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
903
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
664
904
  * @param [options]
665
905
  * @ignore
666
906
  */
667
907
  async openDataset(datasetIdOrName, options = {}) {
668
- ow(options, ow.object.exactShape({
669
- forceCloud: ow.optional.boolean,
670
- }));
671
- this._ensureActorInit('openDataset');
672
- return this._openStorage(Dataset, datasetIdOrName, options);
908
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
909
+ this.ensureActorInit('openDataset');
910
+ return Dataset.open(datasetIdOrName ?? null, {
911
+ storageBackend: options.forceCloud
912
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
913
+ : undefined,
914
+ });
673
915
  }
674
- /**
675
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
676
- *
677
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
678
- * For example, calling the following code:
679
- * ```js
680
- * const value = await Actor.getValue('my-key');
681
- * ```
682
- *
683
- * is equivalent to:
684
- * ```js
685
- * const store = await Actor.openKeyValueStore();
686
- * const value = await store.getValue('my-key');
687
- * ```
688
- *
689
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
690
- *
691
- * For more information, see {@link Actor.openKeyValueStore}
692
- * and {@link KeyValueStore.getValue}.
693
- *
694
- * @param key Unique record key.
695
- * @returns
696
- * Returns a promise that resolves to an object, string
697
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
698
- * on the MIME content type of the record, or `null`
699
- * if the record is missing.
700
- * @ignore
701
- */
702
- async getValue(key) {
703
- this._ensureActorInit('getValue');
916
+ async getValue(key, defaultValue) {
917
+ this.ensureActorInit('getValue');
704
918
  const store = await this.openKeyValueStore();
705
- return store.getValue(key);
919
+ return store.getValue(key, defaultValue);
706
920
  }
707
921
  /**
708
922
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -736,24 +950,28 @@ export class Actor {
736
950
  * @ignore
737
951
  */
738
952
  async setValue(key, value, options = {}) {
739
- this._ensureActorInit('setValue');
953
+ this.ensureActorInit('setValue');
740
954
  const store = await this.openKeyValueStore();
741
955
  return store.setValue(key, value, options);
742
956
  }
743
957
  /**
744
958
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
745
959
  *
746
- * This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](core/class/KeyValueStore#getValue).
747
- * For example, calling the following code:
748
- * ```js
749
- * const input = await Actor.getInput();
750
- * ```
960
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`).
961
+ * A record stored as `application/octet-stream` — which is what a local input file without an
962
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
751
963
  *
752
- * is equivalent to:
753
- * ```js
754
- * const store = await Actor.openKeyValueStore();
755
- * await store.getValue('INPUT');
756
- * ```
964
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
965
+ * working directory. A storage backend that doesn't read the default key-value store's directory under
966
+ * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
967
+ *
968
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
969
+ * replaced with the links of their CSV exports.
970
+ *
971
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
972
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
973
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
974
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
757
975
  *
758
976
  * Note that the `getInput()` function does not cache the value read from the key-value store.
759
977
  * If you need to use the input multiple times in your Actor,
@@ -765,39 +983,85 @@ export class Actor {
765
983
  * @returns
766
984
  * Returns a promise that resolves to an object, string
767
985
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
768
- * on the MIME content type of the record, or `null`
769
- * if the record is missing.
986
+ * on the MIME content type of the record.
987
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
770
988
  * @ignore
771
989
  */
772
990
  async getInput() {
773
- this._ensureActorInit('getInput');
774
- const { inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase } = this.config;
775
- const rawInput = await this.getValue(this.config.inputKey);
991
+ this.ensureActorInit('getInput');
992
+ const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
993
+ // Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
994
+ const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
995
+ const store = await this.openKeyValueStore();
996
+ const record = await store.getRecord(inputKey);
997
+ // Not a conflict check: under the file-system backend the record *is* the store directory's file.
998
+ const storeInput = record
999
+ ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
1000
+ : await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
1001
+ const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
1002
+ if (storeInput != null && cwdInput != null) {
1003
+ 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.`);
1004
+ }
1005
+ const rawInput = storeInput ?? cwdInput;
1006
+ if (rawInput == null) {
1007
+ const locations = [`the "${inputKey}" record of the default key-value store`];
1008
+ if (!this.configuration.isAtHome) {
1009
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
1010
+ }
1011
+ throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
1012
+ }
776
1013
  let input = rawInput;
777
- if (ow.isValid(rawInput, ow.object.nonEmpty) &&
778
- inputSecretsPrivateKeyFile &&
779
- inputSecretsPrivateKeyPassphrase) {
780
- const privateKey = createPrivateKey({
781
- key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
782
- passphrase: inputSecretsPrivateKeyPassphrase,
783
- });
784
- input = decryptInputSecrets({ input: rawInput, privateKey });
1014
+ if (isNonEmptyObject(rawInput) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
1015
+ try {
1016
+ const privateKey = createPrivateKey({
1017
+ key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
1018
+ passphrase: inputSecretsPrivateKeyPassphrase,
1019
+ });
1020
+ input = decryptInputSecrets({ input: rawInput, privateKey });
1021
+ }
1022
+ catch (cause) {
1023
+ throw new ActorInputError('DECRYPTION_FAILED', 'Failed to decrypt the secret fields of the input.', {
1024
+ cause,
1025
+ });
1026
+ }
785
1027
  }
786
- if (ow.isValid(input, ow.object.nonEmpty) && !Buffer.isBuffer(input)) {
787
- input = await this.inferDefaultsFromInputSchema(input);
1028
+ if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
1029
+ input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
788
1030
  }
789
1031
  return input;
790
1032
  }
791
1033
  /**
792
- * Gets the Actor input value just like the {@link Actor.getInput} method,
793
- * but throws if it is not found.
1034
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
1035
+ * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
1036
+ * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
1037
+ * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
1038
+ *
1039
+ * @returns `undefined` when running on the platform or when neither file exists.
794
1040
  */
795
- async getInputOrThrow() {
796
- const input = await this.getInput();
797
- if (input == null) {
798
- throw new Error('Input does not exist');
1041
+ async readInputFromDirectory(inputKey, directory, label) {
1042
+ if (this.configuration.isAtHome) {
1043
+ return undefined;
799
1044
  }
800
- return input;
1045
+ const candidates = [
1046
+ { filename: inputKey, contentType: BINARY_CONTENT_TYPE },
1047
+ { filename: `${inputKey}.json`, contentType: JSON_CONTENT_TYPE },
1048
+ ];
1049
+ const found = [];
1050
+ for (const candidate of candidates) {
1051
+ const path = join(directory, candidate.filename);
1052
+ const stats = await stat(path).catch(() => null);
1053
+ if (stats?.isFile()) {
1054
+ found.push({ ...candidate, path });
1055
+ }
1056
+ }
1057
+ if (found.length > 1) {
1058
+ throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
1059
+ }
1060
+ if (found.length === 0) {
1061
+ return undefined;
1062
+ }
1063
+ const [file] = found;
1064
+ return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
801
1065
  }
802
1066
  /**
803
1067
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -809,18 +1073,21 @@ export class Actor {
809
1073
  * For more details and code examples, see the {@link KeyValueStore} class.
810
1074
  *
811
1075
  * @param [storeIdOrName]
812
- * ID or name of the key-value store to be opened. If `null` or `undefined`,
1076
+ * ID, name, or alias of the key-value store to be opened. If `null` or `undefined`,
813
1077
  * the function returns the default key-value store associated with the Actor run.
814
- * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1078
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1079
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
815
1080
  * @param [options]
816
1081
  * @ignore
817
1082
  */
818
1083
  async openKeyValueStore(storeIdOrName, options = {}) {
819
- ow(options, ow.object.exactShape({
820
- forceCloud: ow.optional.boolean,
821
- }));
822
- this._ensureActorInit('openKeyValueStore');
823
- return this._openStorage(KeyValueStore, storeIdOrName, options);
1084
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1085
+ this.ensureActorInit('openKeyValueStore');
1086
+ return KeyValueStore.open(storeIdOrName ?? null, {
1087
+ storageBackend: options.forceCloud
1088
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1089
+ : undefined,
1090
+ });
824
1091
  }
825
1092
  /**
826
1093
  * Opens a request queue and returns a promise resolving to an instance
@@ -834,21 +1101,21 @@ export class Actor {
834
1101
  * For more details and code examples, see the {@link RequestQueue} class.
835
1102
  *
836
1103
  * @param [queueIdOrName]
837
- * ID or name of the request queue to be opened. If `null` or `undefined`,
1104
+ * ID, name, or alias of the request queue to be opened. If `null` or `undefined`,
838
1105
  * the function returns the default request queue associated with the Actor run.
839
- * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1106
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1107
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
840
1108
  * @param [options]
841
1109
  * @ignore
842
1110
  */
843
1111
  async openRequestQueue(queueIdOrName, options = {}) {
844
- ow(options, ow.object.exactShape({
845
- forceCloud: ow.optional.boolean,
846
- }));
847
- this._ensureActorInit('openRequestQueue');
848
- const queue = await this._openStorage(RequestQueue, queueIdOrName, options);
849
- // eslint-disable-next-line dot-notation
850
- queue['initialCount'] = (await queue.client.getMetadata())?.totalRequestCount ?? 0;
851
- return queue;
1112
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1113
+ this.ensureActorInit('openRequestQueue');
1114
+ return RequestQueue.open(queueIdOrName ?? null, {
1115
+ storageBackend: options.forceCloud
1116
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1117
+ : undefined,
1118
+ });
852
1119
  }
853
1120
  /**
854
1121
  * Creates a proxy configuration and returns a promise resolving to an instance
@@ -899,7 +1166,7 @@ export class Actor {
899
1166
  if (dontUseApifyProxy && dontUseCustomProxies) {
900
1167
  return undefined;
901
1168
  }
902
- const proxyConfiguration = new ProxyConfiguration(options, this.config);
1169
+ const proxyConfiguration = new ProxyConfiguration(options, this.configuration);
903
1170
  if (await proxyConfiguration.initialize({ checkAccess })) {
904
1171
  return proxyConfiguration;
905
1172
  }
@@ -919,66 +1186,58 @@ export class Actor {
919
1186
  * rather than batching via `count` — this gives finer control over budget consumption
920
1187
  * and avoids situations where more work is requested than the budget allows.
921
1188
  *
1189
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1190
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1191
+ * be globally unique (e.g. derived from `requestId`).
1192
+ *
922
1193
  * @param options The name of the event to charge for and the number of events to be charged.
923
1194
  * @ignore
924
1195
  */
925
1196
  async charge(options) {
926
- this._ensureActorInit('charge');
927
- return this.chargingManager.charge(options);
1197
+ this.ensureActorInit('charge');
1198
+ return this.#chargingManager.charge(options);
928
1199
  }
929
1200
  /**
930
1201
  * Retrieve the charging manager to access granular pricing information.
931
1202
  * @ignore
932
1203
  */
933
1204
  getChargingManager() {
934
- this._ensureActorInit('getChargingManager');
935
- return this.chargingManager;
1205
+ this.ensureActorInit('getChargingManager');
1206
+ return this.#chargingManager;
936
1207
  }
937
1208
  /**
938
- * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
1209
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1210
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1211
+ * Resolves to `undefined` when not running on the Apify platform.
939
1212
  */
940
- getModifiedActorEnvVars() {
941
- const modifiedActorEnvVars = {};
942
- Object.entries(ACTOR_ENV_VARS).forEach(([k, v]) => {
943
- // Prepend `ACTOR_` to env vars so ApifyEnv structure is preserved
944
- if (['ID', 'RUN_ID', 'TASK_ID'].includes(k)) {
945
- modifiedActorEnvVars[`ACTOR_${k}`] = v;
946
- }
947
- else {
948
- modifiedActorEnvVars[k] = v;
949
- }
1213
+ async getCurrentRun() {
1214
+ const runId = this.configuration.actorRunId;
1215
+ if (!runId) {
1216
+ return undefined;
1217
+ }
1218
+ this.#runPromise ??= this.apifyClient
1219
+ .run(runId)
1220
+ .get()
1221
+ .catch((err) => {
1222
+ this.#runPromise = undefined;
1223
+ throw err;
950
1224
  });
951
- return modifiedActorEnvVars;
1225
+ return this.#runPromise;
952
1226
  }
953
- /**
954
- * Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
955
- *
956
- * For the list of the Apify environment variables, see
957
- * [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
958
- * If some variables are not defined or are invalid, the corresponding value in the resulting object will be null.
959
- * @ignore
960
- */
961
- getEnv() {
962
- // NOTE: Don't throw if env vars are invalid to simplify local development and debugging of Actors
963
- const env = process.env || {};
964
- const envVars = {};
965
- for (const [shortName, fullName] of Object.entries({
966
- ...APIFY_ENV_VARS,
967
- ...this.getModifiedActorEnvVars(),
968
- })) {
969
- const camelCaseName = snakeCaseToCamelCase(shortName);
970
- let value = env[fullName];
971
- // Parse dates and integers.
972
- if (value && fullName.endsWith('_AT')) {
973
- const unix = Date.parse(value);
974
- value = unix > 0 ? new Date(unix) : undefined;
975
- }
976
- else if (INTEGER_ENV_VARS.includes(fullName)) {
977
- value = parseInt(value, 10);
978
- }
979
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1227
+ /** Cached for the lifetime of the Actor; only the charging manager needs it. */
1228
+ async #getCurrentActor() {
1229
+ const { actorId } = this.configuration;
1230
+ if (!actorId) {
1231
+ return undefined;
980
1232
  }
981
- return envVars;
1233
+ this.#actorPromise ??= this.apifyClient
1234
+ .actor(actorId)
1235
+ .get()
1236
+ .catch((err) => {
1237
+ this.#actorPromise = undefined;
1238
+ throw err;
1239
+ });
1240
+ return this.#actorPromise;
982
1241
  }
983
1242
  /**
984
1243
  * Returns a new instance of the Apify API client. The `ApifyClient` class is provided
@@ -989,12 +1248,12 @@ export class Actor {
989
1248
  * @ignore
990
1249
  */
991
1250
  newClient(options = {}) {
992
- const { storageDir, ...storageClientOptions } = (this.config.storageClientOptions ?? {});
1251
+ const { storageDir, ...storageClientOptions } = (this.configuration.storageClientOptions ?? {});
993
1252
  const { apifyVersion, crawleeVersion } = getSystemInfo();
994
1253
  return new ApifyClient({
995
- baseUrl: this.config.apiBaseUrl,
996
- publicBaseUrl: this.config.apiPublicBaseUrl,
997
- token: this.config.token,
1254
+ baseUrl: this.configuration.apiBaseUrl,
1255
+ publicBaseUrl: this.configuration.apiPublicBaseUrl,
1256
+ token: this.configuration.token,
998
1257
  userAgentSuffix: [`SDK/${apifyVersion}`, `Crawlee/${crawleeVersion}`],
999
1258
  ...storageClientOptions,
1000
1259
  ...options, // allow overriding the instance configuration
@@ -1012,14 +1271,14 @@ export class Actor {
1012
1271
  *
1013
1272
  * Values can be modified by simply using the assignment operator.
1014
1273
  *
1015
- * @param name The name of the store to use.
1274
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
1016
1275
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
1017
1276
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
1018
1277
  */
1019
1278
  async useState(name, defaultValue = {}, options) {
1020
- this._ensureActorInit('useState');
1279
+ this.ensureActorInit('useState');
1021
1280
  const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
1022
- config: options?.config || Configuration.getGlobalConfig(),
1281
+ configuration: options?.configuration ?? this.configuration,
1023
1282
  });
1024
1283
  return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
1025
1284
  }
@@ -1028,7 +1287,7 @@ export class Actor {
1028
1287
  *
1029
1288
  * Values can be modified by simply using the assignment operator.
1030
1289
  *
1031
- * @param name The name of the store to use.
1290
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
1032
1291
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
1033
1292
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
1034
1293
  */
@@ -1070,24 +1329,22 @@ export class Actor {
1070
1329
  *
1071
1330
  * If the user function returns a promise, it is considered asynchronous:
1072
1331
  * ```js
1073
- * import { gotScraping } from 'got-scraping';
1074
- *
1075
1332
  * await Actor.main(() => {
1076
1333
  * // My asynchronous function that returns a promise
1077
- * return gotScraping('http://www.example.com').then((html) => {
1078
- * console.log(html);
1079
- * });
1334
+ * return fetch('http://www.example.com')
1335
+ * .then((response) => response.text())
1336
+ * .then((html) => {
1337
+ * console.log(html);
1338
+ * });
1080
1339
  * });
1081
1340
  * ```
1082
1341
  *
1083
1342
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
1084
1343
  *
1085
1344
  * ```js
1086
- * import { gotScraping } from 'got-scraping';
1087
- *
1088
1345
  * await Actor.main(async () => {
1089
1346
  * // My asynchronous function
1090
- * const html = await gotScraping('http://www.example.com');
1347
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
1091
1348
  * console.log(html);
1092
1349
  * });
1093
1350
  * ```
@@ -1115,11 +1372,9 @@ export class Actor {
1115
1372
  * behavior by setting `options.gracefulShutdown` to `false`.
1116
1373
  *
1117
1374
  * ```js
1118
- * import { gotScraping } from 'got-scraping';
1119
- *
1120
1375
  * await Actor.init();
1121
1376
  *
1122
- * const html = await gotScraping('http://www.example.com');
1377
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
1123
1378
  * console.log(html);
1124
1379
  *
1125
1380
  * await Actor.exit();
@@ -1170,9 +1425,8 @@ export class Actor {
1170
1425
  * @param actorId
1171
1426
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1172
1427
  * @param [input]
1173
- * Input for the Actor. If it is an object, it will be stringified to
1174
- * JSON and its content type set to `application/json; charset=utf-8`.
1175
- * Otherwise the `options.contentType` parameter must be provided.
1428
+ * Input for the Actor. A plain object is stringified to JSON with content type
1429
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1176
1430
  * @param [options]
1177
1431
  */
1178
1432
  static async call(actorId, input, options = {}) {
@@ -1206,6 +1460,31 @@ export class Actor {
1206
1460
  static async callTask(taskId, input, options = {}) {
1207
1461
  return Actor.getDefaultInstance().callTask(taskId, input, options);
1208
1462
  }
1463
+ /**
1464
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1465
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
1466
+ *
1467
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1468
+ *
1469
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
1470
+ *
1471
+ * **Example usage:**
1472
+ *
1473
+ * ```js
1474
+ * const run = await Actor.startTask('bob/some-task');
1475
+ * ```
1476
+ *
1477
+ * @param taskId
1478
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
1479
+ * @param [input]
1480
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
1481
+ * JSON and its content type set to `application/json; charset=utf-8`.
1482
+ * Provided input will be merged with Actor task input.
1483
+ * @param [options]
1484
+ */
1485
+ static async startTask(taskId, input, options = {}) {
1486
+ return Actor.getDefaultInstance().startTask(taskId, input, options);
1487
+ }
1209
1488
  /**
1210
1489
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1211
1490
  * unlike `Actor.call`, this method just starts the run without waiting for finish.
@@ -1224,14 +1503,30 @@ export class Actor {
1224
1503
  * @param actorId
1225
1504
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1226
1505
  * @param [input]
1227
- * Input for the Actor. If it is an object, it will be stringified to
1228
- * JSON and its content type set to `application/json; charset=utf-8`.
1229
- * Otherwise the `options.contentType` parameter must be provided.
1506
+ * Input for the Actor. A plain object is stringified to JSON with content type
1507
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1230
1508
  * @param [options]
1231
1509
  */
1232
1510
  static async start(actorId, input, options = {}) {
1233
1511
  return Actor.getDefaultInstance().start(actorId, input, options);
1234
1512
  }
1513
+ /**
1514
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
1515
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
1516
+ * migration, reboot or resurrection of this run.
1517
+ *
1518
+ * ```js
1519
+ * const childRuns = await Actor.childRuns();
1520
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
1521
+ * ```
1522
+ *
1523
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
1524
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
1525
+ * resurrection of this run, which uses the default client.
1526
+ */
1527
+ static async childRuns() {
1528
+ return Actor.getDefaultInstance().childRuns();
1529
+ }
1235
1530
  /**
1236
1531
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1237
1532
  *
@@ -1249,6 +1544,26 @@ export class Actor {
1249
1544
  static async abort(runId, options = {}) {
1250
1545
  return Actor.getDefaultInstance().abort(runId, options);
1251
1546
  }
1547
+ /**
1548
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1549
+ *
1550
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
1551
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
1552
+ *
1553
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1554
+ *
1555
+ * For more information about Actors, read the
1556
+ * [documentation](https://docs.apify.com/actor).
1557
+ *
1558
+ * **Example usage:**
1559
+ *
1560
+ * ```js
1561
+ * const run = await Actor.resurrect(runId);
1562
+ * ```
1563
+ */
1564
+ static async resurrect(runId, options = {}) {
1565
+ return Actor.getDefaultInstance().resurrect(runId, options);
1566
+ }
1252
1567
  /**
1253
1568
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
1254
1569
  * the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
@@ -1257,9 +1572,8 @@ export class Actor {
1257
1572
  * @param targetActorId
1258
1573
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
1259
1574
  * @param [input]
1260
- * Input for the Actor. If it is an object, it will be stringified to
1261
- * JSON and its content type set to `application/json; charset=utf-8`.
1262
- * Otherwise, the `options.contentType` parameter must be provided.
1575
+ * Input for the Actor. A plain object is stringified to JSON with content type
1576
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1263
1577
  * @param [options]
1264
1578
  */
1265
1579
  static async metamorph(targetActorId, input, options = {}) {
@@ -1294,7 +1608,8 @@ export class Actor {
1294
1608
  * @param [options]
1295
1609
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1296
1610
  * This is required for the last status message of the run. Default value is `false`.
1297
- * @returns The return value is the Run object. When run locally, this method returns empty object (`{}`).
1611
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1612
+ * or when the update failed or timed out (a warning is logged in that case).
1298
1613
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1299
1614
  */
1300
1615
  static async setStatusMessage(statusMessage, options) {
@@ -1323,6 +1638,7 @@ export class Actor {
1323
1638
  * @param item Object or array of objects containing data to be stored in the default dataset.
1324
1639
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1325
1640
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1641
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1326
1642
  */
1327
1643
  static async pushData(item, eventName) {
1328
1644
  if (eventName === undefined) {
@@ -1342,42 +1658,15 @@ export class Actor {
1342
1658
  * @param [datasetIdOrName]
1343
1659
  * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
1344
1660
  * the function returns the default dataset associated with the Actor run.
1345
- * You can also pass `{ alias: 'name' }` to open a dataset defined in the Actor's schema storages,
1346
- * `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1661
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1662
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
1347
1663
  * @param [options]
1348
1664
  */
1349
1665
  static async openDataset(datasetIdOrName, options = {}) {
1350
1666
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1351
1667
  }
1352
- /**
1353
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
1354
- *
1355
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
1356
- * For example, calling the following code:
1357
- * ```js
1358
- * const value = await Actor.getValue('my-key');
1359
- * ```
1360
- *
1361
- * is equivalent to:
1362
- * ```js
1363
- * const store = await Actor.openKeyValueStore();
1364
- * const value = await store.getValue('my-key');
1365
- * ```
1366
- *
1367
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
1368
- *
1369
- * For more information, see {@link Actor.openKeyValueStore}
1370
- * and {@link KeyValueStore.getValue}.
1371
- *
1372
- * @param key Unique record key.
1373
- * @returns
1374
- * Returns a promise that resolves to an object, string
1375
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1376
- * on the MIME content type of the record, or `null`
1377
- * if the record is missing.
1378
- */
1379
- static async getValue(key) {
1380
- return Actor.getDefaultInstance().getValue(key);
1668
+ static async getValue(key, defaultValue) {
1669
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1381
1670
  }
1382
1671
  /**
1383
1672
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1415,16 +1704,31 @@ export class Actor {
1415
1704
  /**
1416
1705
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
1417
1706
  *
1418
- * This is just a convenient shortcut for {@link KeyValueStore.getValue | `keyValueStore.getValue('INPUT')`}.
1419
- * For example, calling the following code:
1707
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`):
1420
1708
  * ```js
1421
1709
  * const input = await Actor.getInput();
1422
1710
  * ```
1423
1711
  *
1424
- * is equivalent to:
1712
+ * A record stored as `application/octet-stream` — which is what a local input file without an
1713
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1714
+ *
1715
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1716
+ * working directory.
1717
+ *
1718
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
1719
+ * replaced with the links of their CSV exports.
1720
+ *
1721
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1722
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1723
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1724
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1425
1725
  * ```js
1426
- * const store = await Actor.openKeyValueStore();
1427
- * await store.getValue('INPUT');
1726
+ * let input = {};
1727
+ * try {
1728
+ * input = await Actor.getInput();
1729
+ * } catch (error) {
1730
+ * if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
1731
+ * }
1428
1732
  * ```
1429
1733
  *
1430
1734
  * Note that the `getInput()` function does not cache the value read from the key-value store.
@@ -1436,19 +1740,12 @@ export class Actor {
1436
1740
  * @returns
1437
1741
  * Returns a promise that resolves to an object, string
1438
1742
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1439
- * on the MIME content type of the record, or `null`
1440
- * if the record is missing.
1743
+ * on the MIME content type of the record.
1744
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
1441
1745
  */
1442
1746
  static async getInput() {
1443
1747
  return Actor.getDefaultInstance().getInput();
1444
1748
  }
1445
- /**
1446
- * Gets the Actor input value just like the {@link Actor.getInput} method,
1447
- * but throws if it is not found.
1448
- */
1449
- static async getInputOrThrow() {
1450
- return Actor.getDefaultInstance().getInputOrThrow();
1451
- }
1452
1749
  /**
1453
1750
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
1454
1751
  *
@@ -1542,6 +1839,10 @@ export class Actor {
1542
1839
  * rather than batching via `count` — this gives finer control over budget consumption
1543
1840
  * and avoids situations where more work is requested than the budget allows.
1544
1841
  *
1842
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1843
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1844
+ * be globally unique (e.g. derived from `requestId`).
1845
+ *
1545
1846
  * @param options The name of the event to charge for and the number of events to be charged.
1546
1847
  */
1547
1848
  static async charge(options) {
@@ -1553,16 +1854,6 @@ export class Actor {
1553
1854
  static getChargingManager() {
1554
1855
  return Actor.getDefaultInstance().getChargingManager();
1555
1856
  }
1556
- /**
1557
- * Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
1558
- *
1559
- * For the list of the Apify environment variables, see
1560
- * [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
1561
- * If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.
1562
- */
1563
- static getEnv() {
1564
- return Actor.getDefaultInstance().getEnv();
1565
- }
1566
1857
  /**
1567
1858
  * Returns a new instance of the Apify API client. The `ApifyClient` class is provided
1568
1859
  * by the [apify-client](https://www.npmjs.com/package/apify-client)
@@ -1579,88 +1870,123 @@ export class Actor {
1579
1870
  static isAtHome() {
1580
1871
  return Actor.getDefaultInstance().isAtHome();
1581
1872
  }
1873
+ /**
1874
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1875
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1876
+ * Resolves to `undefined` when not running on the Apify platform.
1877
+ */
1878
+ static async getCurrentRun() {
1879
+ return Actor.getDefaultInstance().getCurrentRun();
1880
+ }
1582
1881
  /** Default {@link ApifyClient} instance. */
1583
1882
  static get apifyClient() {
1584
1883
  return Actor.getDefaultInstance().apifyClient;
1585
1884
  }
1586
1885
  /** Default {@link Configuration} instance. */
1587
- static get config() {
1588
- return Actor.getDefaultInstance().config;
1886
+ static get configuration() {
1887
+ return Actor.getDefaultInstance().configuration;
1589
1888
  }
1590
1889
  /** @internal */
1591
1890
  static getDefaultInstance() {
1592
- this._instance ??= new Actor();
1593
- return this._instance;
1891
+ Actor.#instance ??= new Actor();
1892
+ return Actor.#instance;
1594
1893
  }
1595
- usesPushDataInterception(dataset) {
1596
- return Boolean(dataset.client[USES_PUSH_DATA_INTERCEPTION]);
1894
+ /**
1895
+ * Replaces or clears the cached default instance returned by {@link Actor.getDefaultInstance}.
1896
+ * @internal
1897
+ */
1898
+ static setDefaultInstance(instance) {
1899
+ Actor.#instance = instance;
1597
1900
  }
1598
- async pushDataViaInterceptedClient(dataset, item, eventName) {
1599
- // PatchedDatasetClient will handle charging and item limiting.
1600
- // We only need to propagate `eventName` and (optionally) return aggregated charge info.
1601
- const context = {
1602
- eventName,
1901
+ /**
1902
+ * The backend the Actor installs unless the caller brings one: Apify platform storage on the
1903
+ * platform, crawlee's local default outside of it.
1904
+ *
1905
+ * Both sides are wrapped for dataset-item charging - crawlee's local default stands in for
1906
+ * Apify storage, so local pay-per-event testing stays faithful. A caller-supplied backend
1907
+ * (`Actor.init({ storage })`) is billed nothing and is installed unwrapped, in place of this.
1908
+ *
1909
+ * One instance per Actor: a second platform backend would mint unnamed storages of its own for
1910
+ * aliases this one has already resolved.
1911
+ */
1912
+ get #storageBackend() {
1913
+ const charging = {
1914
+ configuration: this.configuration,
1915
+ getChargingManager: () => this.#chargingManager,
1603
1916
  };
1604
- await pushDataChargingContext.run(context, async () => {
1605
- await dataset.pushData(item);
1606
- });
1607
- return (context.chargeResult ?? {
1608
- eventChargeLimitReached: false,
1609
- chargedCount: 0,
1610
- chargeableWithinLimit: {},
1611
- });
1917
+ // Crawlers leave retries to the storage backend; 3 matches what they used to add on top of the client.
1918
+ const { maxRetries = 3 } = (this.configuration.storageClientOptions ?? {});
1919
+ return (this.#cachedStorageBackend ??= new SmartApifyStorageBackend({
1920
+ cloudStorageBackend: new ChargingStorageBackend(new ApifyStorageBackend(this.newClient({ maxRetries }), {
1921
+ configuration: this.configuration,
1922
+ requestQueueAccess: this.#requestQueueAccess,
1923
+ }), charging),
1924
+ localStorageBackend: new ChargingStorageBackend(this.createLocalStorageBackend(), charging),
1925
+ configuration: this.configuration,
1926
+ }));
1612
1927
  }
1613
- async pushDataWithExplicitCharging(dataset, items, explicitEventName) {
1614
- // `Actor.pushData()` historically worked even without calling `Actor.init()`.
1615
- // In that case, charging isn't configured, so just push the data through.
1616
- if (!this.initialized && explicitEventName === undefined) {
1617
- await dataset.pushData(items);
1618
- return {
1619
- eventChargeLimitReached: false,
1620
- chargedCount: 0,
1621
- chargeableWithinLimit: {},
1622
- };
1928
+ /**
1929
+ * The same choice crawlee's `ServiceLocator` makes for its implicit default backend, with the
1930
+ * input-aware {@link ApifyFileSystemStorageBackend} in place of crawlee's — crawlee has no
1931
+ * notion of a run input.
1932
+ */
1933
+ createLocalStorageBackend() {
1934
+ const { persistStorage, storageDir, inputKey } = this.configuration;
1935
+ const logger = serviceLocator.getLogger();
1936
+ if (!persistStorage) {
1937
+ return new MemoryStorageBackend({ logger: logger.child({ prefix: 'MemoryStorageBackend' }) });
1623
1938
  }
1624
- const isDefaultDataset = dataset.id === this.config.defaultDatasetId;
1625
- return pushDataAndCharge({
1626
- chargingManager: this.chargingManager,
1627
- items,
1628
- eventName: explicitEventName,
1629
- isDefaultDataset,
1630
- pushFn: async (limitedItems) => dataset.pushData(limitedItems),
1939
+ return new ApifyFileSystemStorageBackend({
1940
+ localDataDirectory: storageDir,
1941
+ inputKey,
1942
+ logger: logger.child({ prefix: 'ApifyFileSystemStorageBackend' }),
1631
1943
  });
1632
1944
  }
1633
- async _openStorage(storageClass, identifier, options = {}) {
1634
- return openStorage(storageClass, identifier, {
1635
- config: this.config,
1636
- client: options.forceCloud
1637
- ? new ApifyStorageClient(this.apifyClient, this.config, () => this.chargingManager)
1638
- : undefined,
1639
- purgedStorageAliases: this.purgedStorageAliases,
1640
- });
1945
+ /** Whether items reaching the run's default dataset are counted for pay-per-event charging. */
1946
+ #chargesDefaultDatasetItems() {
1947
+ const installed = serviceLocator.getStorageBackend();
1948
+ return installed instanceof SmartApifyStorageBackend || installed instanceof ChargingStorageBackend;
1641
1949
  }
1642
- _ensureActorInit(methodCalled) {
1950
+ /**
1951
+ * crawlee's service locator is set-once, so a backend registered before `init()` wins and the
1952
+ * Actor cannot install its own over it. Replaces the resulting `ServiceConflictError` with the
1953
+ * way out.
1954
+ */
1955
+ installStorageBackend(backend) {
1956
+ try {
1957
+ serviceLocator.setStorageBackend(backend);
1958
+ }
1959
+ catch (error) {
1960
+ throw new Error('A storage backend is already registered with crawlee, so the Actor cannot install its own. Pass it ' +
1961
+ 'as `Actor.init({ storage })` instead of calling `serviceLocator.setStorageBackend()`.', { cause: error });
1962
+ }
1963
+ }
1964
+ ensureActorInit(methodCalled) {
1643
1965
  // If we already warned the user once, don't do it again to prevent spam
1644
- if (this.warnedAboutMissingInitCall) {
1966
+ if (this.#warnedAboutMissingInitCall) {
1645
1967
  return;
1646
1968
  }
1647
1969
  if (this.initialized) {
1648
1970
  return;
1649
1971
  }
1650
- this.warnedAboutMissingInitCall = true;
1972
+ this.#warnedAboutMissingInitCall = true;
1651
1973
  log.warning([
1652
1974
  `Actor.${methodCalled}() was called but the Actor instance was not initialized.`,
1653
1975
  'Did you forget to call Actor.init()?',
1654
1976
  ].join('\n'));
1655
1977
  }
1656
1978
  /**
1657
- * Get time remaining from the Actor run timeout. Returns `undefined` if not on an Apify platform or the current
1658
- * run was started without a timeout.
1979
+ * Get time remaining from the Actor run timeout in seconds, rounded up to whole seconds with minimum value of 1 second.
1980
+ *
1981
+ * The API treats a 0 second timeout as no timeout, the minimum acceptable timeout is 1 second.
1982
+ *
1983
+ * Returns `undefined` if not on the Apify platform or the current run was started without a timeout.
1659
1984
  */
1660
- getRemainingTime() {
1661
- const env = this.getEnv();
1662
- if (this.isAtHome() && env.timeoutAt !== null) {
1663
- return env.timeoutAt.getTime() - Date.now();
1985
+ getRemainingTimeSecs() {
1986
+ const { timeoutAt } = this.configuration;
1987
+ const MINIMUM_API_TIMEOUT_SECS = 1;
1988
+ if (this.isAtHome() && timeoutAt !== undefined) {
1989
+ return Math.max(Math.ceil((timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
1664
1990
  }
1665
1991
  log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
1666
1992
  'timeout for the Actor run is set.');