apify 4.0.0-beta.12 → 4.0.0-beta.120

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 (69) hide show
  1. package/README.md +29 -43
  2. package/dist/actor.d.ts +511 -167
  3. package/dist/actor.js +895 -322
  4. package/dist/apify_dataset_backend.d.ts +19 -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 +23 -0
  9. package/dist/apify_key_value_store_backend.js +56 -0
  10. package/dist/apify_request_queue_backend.d.ts +78 -0
  11. package/dist/apify_request_queue_backend.js +114 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +82 -18
  19. package/dist/charging.js +388 -128
  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 +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +86 -136
  25. package/dist/configuration.js +136 -145
  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 +11 -5
  33. package/dist/index.js +8 -5
  34. package/dist/input-schemas.d.ts +7 -0
  35. package/dist/input-schemas.js +58 -0
  36. package/dist/platform_event_manager.d.ts +15 -6
  37. package/dist/platform_event_manager.js +187 -41
  38. package/dist/proxy_configuration.d.ts +66 -59
  39. package/dist/proxy_configuration.js +172 -154
  40. package/dist/smart_apify_storage_backend.d.ts +52 -0
  41. package/dist/smart_apify_storage_backend.js +73 -0
  42. package/dist/storage.d.ts +38 -0
  43. package/dist/storage.js +1 -0
  44. package/dist/utils.d.ts +28 -4
  45. package/dist/utils.js +60 -20
  46. package/package.json +117 -73
  47. package/.turbo/turbo-build.log +0 -26
  48. package/.turbo/turbo-copy.log +0 -4
  49. package/dist/LICENSE.md +0 -201
  50. package/dist/README.md +0 -98
  51. package/dist/actor.d.ts.map +0 -1
  52. package/dist/actor.js.map +0 -1
  53. package/dist/charging.d.ts.map +0 -1
  54. package/dist/charging.js.map +0 -1
  55. package/dist/configuration.d.ts.map +0 -1
  56. package/dist/configuration.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/key_value_store.d.ts +0 -17
  60. package/dist/key_value_store.d.ts.map +0 -1
  61. package/dist/key_value_store.js +0 -33
  62. package/dist/key_value_store.js.map +0 -1
  63. package/dist/package.json +0 -75
  64. package/dist/platform_event_manager.d.ts.map +0 -1
  65. package/dist/platform_event_manager.js.map +0 -1
  66. package/dist/proxy_configuration.d.ts.map +0 -1
  67. package/dist/proxy_configuration.js.map +0 -1
  68. package/dist/utils.d.ts.map +0 -1
  69. package/dist/utils.js.map +0 -1
package/dist/actor.js CHANGED
@@ -1,18 +1,49 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
- import { Configuration as CoreConfiguration, Dataset, purgeDefaultStorages, RequestQueue, StorageManager, } 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 { coerceBoolean, 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, 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, INTEGER_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 { ChargingManager } from './charging.js';
12
+ import { timeoutPromise } from '@apify/utilities';
13
+ import { parseArgument } from '@apify/validations';
14
+ import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
15
+ import { ApifyStorageBackend } from './apify_storage_backend.js';
16
+ import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
17
+ import { ChargingStorageBackend } from './charging_storage_backend.js';
18
+ import { ChildRunTracker } from './child_run_tracker.js';
11
19
  import { Configuration } from './configuration.js';
12
- import { KeyValueStore } from './key_value_store.js';
20
+ import { ActorInputError } from './errors.js';
21
+ import { fixGoogleSheetsUrls } from './google_sheets.js';
22
+ import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
13
23
  import { PlatformEventManager } from './platform_event_manager.js';
14
24
  import { ProxyConfiguration } from './proxy_configuration.js';
15
- import { checkCrawleeVersion, getSystemInfo, printOutdatedSdkWarning, } from './utils.js';
25
+ import { SmartApifyStorageBackend } from './smart_apify_storage_backend.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
+ ];
35
+ /**
36
+ * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
37
+ * JSON input reports where it came from.
38
+ */
39
+ function parseInput(value, contentType, source) {
40
+ try {
41
+ return parseInputValue(value, contentType);
42
+ }
43
+ catch (cause) {
44
+ throw new ActorInputError('PARSE_FAILED', `The input in ${source} is not valid JSON.`, { cause });
45
+ }
46
+ }
16
47
  /**
17
48
  * Exit codes for the Actor process.
18
49
  * The error codes must be in the range 1-128, to avoid collision with signal exits
@@ -31,13 +62,13 @@ export const EXIT_CODES = {
31
62
  */
32
63
  export class Actor {
33
64
  /** @internal */
34
- // eslint-disable-next-line no-use-before-define -- self-reference
35
- static _instance;
65
+ static #instance;
66
+ #childRunTracker;
36
67
  /**
37
68
  * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
38
69
  * @internal
39
70
  */
40
- config;
71
+ configuration;
41
72
  /**
42
73
  * Default {@link ApifyClient} instance.
43
74
  * @internal
@@ -56,21 +87,62 @@ export class Actor {
56
87
  * Set if the Actor called a method that requires the instance to be initialized, but did not do so.
57
88
  * A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
58
89
  */
59
- warnedAboutMissingInitCall = false;
90
+ #warnedAboutMissingInitCall = false;
60
91
  /**
61
92
  * Set if the Actor is currently rebooting.
62
93
  */
63
- isRebooting = false;
64
- chargingManager;
94
+ #isRebooting = false;
95
+ /**
96
+ * Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
97
+ */
98
+ #isExiting = false;
99
+ /**
100
+ * References to graceful shutdown handlers so they can be removed during cleanup.
101
+ */
102
+ #gracefulShutdownHandlers = {};
103
+ /**
104
+ * Reference to the crawlee status message forwarder, so it can be removed during cleanup.
105
+ */
106
+ #statusMessageForwarder;
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);
112
+ /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
113
+ #requestQueueAccess = 'single';
114
+ /** Lazily built by the `#storageBackend` getter. */
115
+ #cachedStorageBackend;
116
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
117
+ #pendingListeners = [];
65
118
  constructor(options = {}) {
66
- // use default configuration object if nothing overridden (it fallbacks to env vars)
67
- this.config =
68
- Object.keys(options).length === 0
69
- ? Configuration.getGlobalConfig()
70
- : new Configuration(options);
119
+ const { configuration, ...configOptions } = options;
120
+ if (configuration) {
121
+ // BYO Configuration takes precedence; field-level overrides are
122
+ // ignored to keep the contract unambiguous. It must be the SDK's
123
+ // Configuration subclass, not a bare crawlee one — env-var
124
+ // resolution is driven by the subclass's `static fields`
125
+ // (`apifyConfigFields`) at construction, so a crawlee instance
126
+ // would silently expose none of the `APIFY_*`/`ACTOR_*` values.
127
+ if (!(configuration instanceof Configuration)) {
128
+ throw new Error('Actor `configuration` must be an Apify SDK Configuration (imported from `apify`), ' +
129
+ 'not a crawlee Configuration, otherwise APIFY_*/ACTOR_* environment variables are not resolved.');
130
+ }
131
+ this.configuration = configuration;
132
+ }
133
+ else if (Object.keys(configOptions).length === 0) {
134
+ // use default configuration object if nothing overridden (it fallbacks to env vars)
135
+ this.configuration = Configuration.getGlobalConfiguration();
136
+ }
137
+ else {
138
+ this.configuration = new Configuration(configOptions);
139
+ }
71
140
  this.apifyClient = this.newClient();
72
- this.eventManager = new PlatformEventManager(this.config);
73
- this.chargingManager = new ChargingManager(this.config, 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();
74
146
  }
75
147
  /**
76
148
  * Runs the main user function that performs the job of the Actor
@@ -107,24 +179,22 @@ export class Actor {
107
179
  *
108
180
  * If the user function returns a promise, it is considered asynchronous:
109
181
  * ```js
110
- * import { gotScraping } from 'got-scraping';
111
- *
112
182
  * await Actor.main(() => {
113
183
  * // My asynchronous function that returns a promise
114
- * return gotScraping('http://www.example.com').then((html) => {
115
- * console.log(html);
116
- * });
184
+ * return fetch('http://www.example.com')
185
+ * .then((response) => response.text())
186
+ * .then((html) => {
187
+ * console.log(html);
188
+ * });
117
189
  * });
118
190
  * ```
119
191
  *
120
192
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
121
193
  *
122
194
  * ```js
123
- * import { gotScraping } from 'got-scraping';
124
- *
125
195
  * await Actor.main(async () => {
126
196
  * // My asynchronous function
127
- * const html = await request('http://www.example.com');
197
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
128
198
  * console.log(html);
129
199
  * });
130
200
  * ```
@@ -147,9 +217,7 @@ export class Actor {
147
217
  }
148
218
  catch (err) {
149
219
  log.exception(err, err.message);
150
- await this.exit({
151
- exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
152
- });
220
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
153
221
  }
154
222
  return ret;
155
223
  })();
@@ -163,7 +231,7 @@ export class Actor {
163
231
  return;
164
232
  }
165
233
  // If the warning about forgotten init call was emitted, we will not continue the init procedure.
166
- if (this.warnedAboutMissingInitCall) {
234
+ if (this.#warnedAboutMissingInitCall) {
167
235
  throw new Error([
168
236
  'Actor.init() was called after a method that would access a storage client was used.',
169
237
  'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
@@ -172,34 +240,93 @@ export class Actor {
172
240
  this.initialized = true;
173
241
  checkCrawleeVersion();
174
242
  log.info('System info', getSystemInfo());
175
- printOutdatedSdkWarning();
176
- // reset global config instance to respect APIFY_ prefixed env vars
177
- CoreConfiguration.globalConfig = Configuration.getGlobalConfig();
243
+ // Register this Actor's config as the global one so crawlee storages and
244
+ // the event manager resolve the same instance (`availableMemoryRatio` /
245
+ // `disableBrowserSandbox` at-home defaults now live in `Configuration`).
246
+ serviceLocator.setConfiguration(this.configuration);
247
+ this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
178
248
  if (this.isAtHome()) {
179
- this.config.set('availableMemoryRatio', 1);
180
- this.config.set('disableBrowserSandbox', true); // for browser launcher, adds `--no-sandbox` to args
181
- this.config.useStorageClient(this.apifyClient);
182
- this.config.useEventManager(this.eventManager);
249
+ serviceLocator.setEventManager(this.eventManager);
250
+ }
251
+ if (!serviceLocator.getServicesIfSet().storageBackend) {
252
+ this.installStorageBackend(options.storage ?? this.#storageBackend);
183
253
  }
184
254
  else if (options.storage) {
185
- this.config.useStorageClient(options.storage);
255
+ this.installStorageBackend(options.storage);
256
+ }
257
+ // Register handlers for aborting and migrating events for automatic graceful shutdown.
258
+ // - aborting: calls Actor.exit() to terminate the run gracefully
259
+ // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
260
+ // Using setTimeout to avoid deadlock with waitForAllListenersToComplete() in exit()/reboot()
261
+ if (options.gracefulShutdown !== false) {
262
+ const delay = options.gracefulShutdownDelayMillis ?? 0;
263
+ this.#gracefulShutdownHandlers.aborting = () => {
264
+ setTimeout(() => {
265
+ this.exit().catch((err) => {
266
+ log.exception(err, 'Failed to exit gracefully');
267
+ });
268
+ }, delay);
269
+ };
270
+ this.on(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
271
+ this.#gracefulShutdownHandlers.migrating = () => {
272
+ setTimeout(() => {
273
+ this.reboot().catch((err) => {
274
+ log.exception(err, 'Failed to reboot on migration');
275
+ });
276
+ }, delay);
277
+ };
278
+ this.on(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
279
+ }
280
+ // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
281
+ this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
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 = [];
186
293
  }
187
- // Init the event manager the config uses
188
- await this.config.getEventManager().init();
294
+ await events.init();
189
295
  log.debug(`Events initialized`);
190
296
  await purgeDefaultStorages({
191
- config: this.config,
297
+ configuration: this.configuration,
192
298
  onlyPurgeOnce: true,
193
299
  });
194
300
  log.debug(`Default storages purged`);
195
- Configuration.storage.enterWith(this.config);
196
- await this.chargingManager.init();
197
- log.debug(`ChargingManager initialized`, this.chargingManager.getPricingInfo());
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
+ }
309
+ await this.#chargingManager.init();
310
+ log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
311
+ // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
312
+ // registered with crawlee directly; the storages the Actor installs itself are wrapped.
313
+ if (this.#chargingManager.isPayPerEvent &&
314
+ !this.#chargingManager.isMultiTenant &&
315
+ !this.#chargesDefaultDatasetItems()) {
316
+ log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
317
+ 'storage - the platform only counts items it stores itself.');
318
+ }
198
319
  }
199
320
  /**
200
321
  * @ignore
201
322
  */
202
323
  async exit(messageOrOptions, options = {}) {
324
+ // Prevent double-exit from graceful shutdown handlers
325
+ if (this.#isExiting) {
326
+ log.debug('Actor.exit() called while already exiting, skipping');
327
+ return;
328
+ }
329
+ this.#isExiting = true;
203
330
  options =
204
331
  typeof messageOrOptions === 'string'
205
332
  ? { ...options, statusMessage: messageOrOptions }
@@ -207,17 +334,37 @@ export class Actor {
207
334
  options.exit ??= true;
208
335
  options.exitCode ??= EXIT_CODES.SUCCESS;
209
336
  options.timeoutSecs ??= 30;
210
- const client = this.config.getStorageClient();
211
- const events = this.config.getEventManager();
337
+ this.ensureActorInit('exit');
338
+ const client = serviceLocator.getStorageBackend();
339
+ const events = serviceLocator.getEventManager();
340
+ // Remove graceful shutdown handlers to prevent them from interfering with exit
341
+ if (this.#gracefulShutdownHandlers.aborting) {
342
+ this.off(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
343
+ }
344
+ if (this.#gracefulShutdownHandlers.migrating) {
345
+ this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
346
+ }
212
347
  // Close the event manager and emit the final PERSIST_STATE event
213
348
  await events.close();
214
349
  log.debug(`Events closed`);
215
350
  // Emit the exit event
216
- events.emit("exit" /* EventType.EXIT */, options);
351
+ events.emit(EventType.EXIT, options);
217
352
  // Wait for all event listeners to be processed
218
353
  log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
354
+ if (options.exit) {
355
+ // `addTimeoutToPromise` is a cooperative timeout. This ensures that the process exits
356
+ // after the timeout, even if the event listeners don't trigger the timeout.
357
+ setTimeout(() => {
358
+ process.exit(options.exitCode);
359
+ }, options.timeoutSecs * 1000);
360
+ }
219
361
  await addTimeoutToPromise(async () => {
220
362
  await events.waitForAllListenersToComplete();
363
+ // The final status messages have been forwarded by now; stop listening so
364
+ // that a periodic one can't overwrite the terminal message set below.
365
+ if (this.#statusMessageForwarder) {
366
+ this.off(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
367
+ }
221
368
  if (client.teardown) {
222
369
  let finished = false;
223
370
  setTimeout(() => {
@@ -229,16 +376,21 @@ export class Actor {
229
376
  finished = true;
230
377
  }
231
378
  if (options.statusMessage != null) {
232
- await this.setStatusMessage(options.statusMessage, {
379
+ const statusMessagePromise = this.setStatusMessage(options.statusMessage, {
233
380
  isStatusMessageTerminal: true,
234
381
  level: options.exitCode > 0 ? 'ERROR' : 'INFO',
235
382
  });
383
+ // Waiting 1ms is enough for the network request to be sent. We don't need to wait for the response.
384
+ await Promise.race([statusMessagePromise, sleep(1)]);
236
385
  }
237
386
  }, options.timeoutSecs * 1000, `Waiting for all event listeners to complete their execution timed out after ${options.timeoutSecs} seconds`).catch(() => {
238
387
  if (options.exit) {
239
388
  process.exit(options.exitCode);
240
389
  }
241
390
  });
391
+ // Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
392
+ // When process.exit() actually terminates the process, this line is never reached - which is fine.
393
+ this.#isExiting = false;
242
394
  if (!options.exit) {
243
395
  return;
244
396
  }
@@ -248,19 +400,30 @@ export class Actor {
248
400
  * @ignore
249
401
  */
250
402
  async fail(messageOrOptions, options = {}) {
251
- 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 });
252
405
  }
253
406
  /**
254
407
  * @ignore
255
408
  */
256
409
  on(event, listener) {
257
- this.config.getEventManager().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
+ }
416
+ serviceLocator.getEventManager().on(event, listener);
258
417
  }
259
418
  /**
260
419
  * @ignore
261
420
  */
262
421
  off(event, listener) {
263
- this.config.getEventManager().off(event, listener);
422
+ if (!this.initialized) {
423
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
424
+ return;
425
+ }
426
+ serviceLocator.getEventManager().off(event, listener);
264
427
  }
265
428
  /**
266
429
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -280,16 +443,33 @@ export class Actor {
280
443
  * @param actorId
281
444
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
282
445
  * @param [input]
283
- * Input for the Actor. If it is an object, it will be stringified to
284
- * JSON and its content type set to `application/json; charset=utf-8`.
285
- * Otherwise the `options.contentType` parameter must be provided.
446
+ * Input for the Actor. A plain object is stringified to JSON with content type
447
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
286
448
  * @param [options]
287
449
  * @ignore
288
450
  */
289
451
  async call(actorId, input, options = {}) {
290
- const { token, ...rest } = options;
452
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
453
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
291
454
  const client = token ? this.newClient({ token }) : this.apifyClient;
292
- return client.actor(actorId).call(input, rest);
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
+ }
293
473
  }
294
474
  /**
295
475
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -309,16 +489,22 @@ export class Actor {
309
489
  * @param actorId
310
490
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
311
491
  * @param [input]
312
- * Input for the Actor. If it is an object, it will be stringified to
313
- * JSON and its content type set to `application/json; charset=utf-8`.
314
- * Otherwise the `options.contentType` parameter must be provided.
492
+ * Input for the Actor. A plain object is stringified to JSON with content type
493
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
315
494
  * @param [options]
316
495
  * @ignore
317
496
  */
318
497
  async start(actorId, input, options = {}) {
319
- const { token, ...rest } = options;
498
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
499
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
320
500
  const client = token ? this.newClient({ token }) : this.apifyClient;
321
- return client.actor(actorId).start(input, rest);
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;
322
508
  }
323
509
  /**
324
510
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -338,12 +524,35 @@ export class Actor {
338
524
  async abort(runId, options = {}) {
339
525
  const { token, statusMessage, ...rest } = options;
340
526
  const client = token ? this.newClient({ token }) : this.apifyClient;
527
+ const runClient = client.run(runId);
341
528
  if (statusMessage) {
342
- await this.setStatusMessage(statusMessage, {
343
- isStatusMessageTerminal: true,
344
- });
529
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
345
530
  }
346
- 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 });
347
556
  }
348
557
  /**
349
558
  * Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -372,9 +581,70 @@ export class Actor {
372
581
  * @ignore
373
582
  */
374
583
  async callTask(taskId, input, options = {}) {
375
- const { token, ...rest } = options;
584
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
585
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
586
+ const client = token ? this.newClient({ token }) : this.apifyClient;
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;
376
640
  const client = token ? this.newClient({ token }) : this.apifyClient;
377
- return client.task(taskId).call(input, rest);
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;
378
648
  }
379
649
  /**
380
650
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -384,9 +654,8 @@ export class Actor {
384
654
  * @param targetActorId
385
655
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
386
656
  * @param [input]
387
- * Input for the Actor. If it is an object, it will be stringified to
388
- * JSON and its content type set to `application/json; charset=utf-8`.
389
- * Otherwise, the `options.contentType` parameter must be provided.
657
+ * Input for the Actor. A plain object is stringified to JSON with content type
658
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
390
659
  * @param [options]
391
660
  * @ignore
392
661
  */
@@ -395,11 +664,9 @@ export class Actor {
395
664
  log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
396
665
  return;
397
666
  }
398
- const { customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis'), ...metamorphOpts } = options;
399
- const runId = this.config.get('actorRunId');
400
- await this.apifyClient
401
- .run(runId)
402
- .metamorph(targetActorId, input, metamorphOpts);
667
+ const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
668
+ const runId = this.configuration.actorRunId;
669
+ await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
403
670
  // Wait some time for container to be stopped.
404
671
  await sleep(customAfterSleepMillis);
405
672
  }
@@ -411,32 +678,46 @@ export class Actor {
411
678
  * @ignore
412
679
  */
413
680
  async reboot(options = {}) {
681
+ this.ensureActorInit('reboot');
414
682
  if (!this.isAtHome()) {
415
683
  log.warning('Actor.reboot() is only supported when running on the Apify platform.');
416
684
  return;
417
685
  }
418
- if (this.isRebooting) {
686
+ if (this.#isRebooting) {
419
687
  log.debug('Actor is already rebooting, skipping the additional reboot call.');
420
688
  return;
421
689
  }
422
- this.isRebooting = true;
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
+ });
423
703
  // Waiting for all the listeners to finish, as `.reboot()` kills the container.
424
- 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([
425
706
  // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
426
- ...this.config
427
- .getEventManager()
428
- .listeners("persistState" /* EventType.PERSIST_STATE */)
429
- .map(async (x) => x()),
707
+ ...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
430
708
  // `migrating` to pause Apify crawlers
431
- ...this.config
432
- .getEventManager()
433
- .listeners("migrating" /* EventType.MIGRATING */)
434
- .map(async (x) => x()),
435
- ]);
436
- const runId = this.config.get('actorRunId');
437
- await this.apifyClient.run(runId).reboot();
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));
711
+ const runId = this.configuration.actorRunId;
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
+ }
438
720
  // Wait some time for container to be stopped.
439
- const { customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis'), } = options;
440
721
  await sleep(customAfterSleepMillis);
441
722
  }
442
723
  /**
@@ -452,43 +733,49 @@ export class Actor {
452
733
  * @ignore
453
734
  */
454
735
  async addWebhook(options) {
455
- ow(options, ow.object.exactShape({
456
- eventTypes: ow.array.ofType(ow.string),
457
- requestUrl: ow.string,
458
- payloadTemplate: ow.optional.string,
459
- idempotencyKey: ow.optional.string,
460
- }));
461
- const { eventTypes, requestUrl, payloadTemplate, idempotencyKey } = options;
736
+ parseArgument(options, z
737
+ .object({
738
+ eventTypes: z.array(z.string()),
739
+ requestUrl: z.string(),
740
+ payloadTemplate: z.string().optional(),
741
+ idempotencyKey: z.string().optional(),
742
+ headersTemplate: z.string().optional(),
743
+ description: z.string().optional(),
744
+ ignoreSslErrors: z.boolean().optional(),
745
+ doNotRetry: z.boolean().optional(),
746
+ shouldInterpolateStrings: z.boolean().optional(),
747
+ isApifyIntegration: z.boolean().optional(),
748
+ })
749
+ .strict());
462
750
  if (!this.isAtHome()) {
463
751
  log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
464
752
  return undefined;
465
753
  }
466
- const runId = this.config.get('actorRunId');
754
+ const runId = this.configuration.actorRunId;
467
755
  if (!runId) {
468
756
  throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
469
757
  }
470
758
  return this.apifyClient.webhooks().create({
759
+ ...options,
471
760
  isAdHoc: true,
472
- eventTypes,
473
761
  condition: {
474
762
  actorRunId: runId,
475
763
  },
476
- requestUrl,
477
- payloadTemplate,
478
- idempotencyKey,
479
764
  });
480
765
  }
481
766
  /**
482
767
  * Sets the status message for the current Actor run.
483
768
  *
484
- * @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).
485
771
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
486
772
  * @ignore
487
773
  */
488
774
  async setStatusMessage(statusMessage, options) {
489
775
  const { isStatusMessageTerminal, level } = options || {};
490
- ow(statusMessage, ow.string);
491
- ow(isStatusMessageTerminal, ow.optional.boolean);
776
+ parseArgument(statusMessage, z.string());
777
+ parseArgument(isStatusMessageTerminal, z.boolean().optional());
778
+ this.ensureActorInit('setStatusMessage');
492
779
  const loggedStatusMessage = `[Status message]: ${statusMessage}`;
493
780
  switch (level) {
494
781
  case 'DEBUG':
@@ -504,21 +791,22 @@ export class Actor {
504
791
  log.info(loggedStatusMessage);
505
792
  break;
506
793
  }
507
- const client = this.config.getStorageClient();
508
- // just to be sure, this should be fast
509
- await addTimeoutToPromise(async () => client.setStatusMessage(statusMessage, {
510
- isStatusMessageTerminal,
511
- level,
512
- }), 1000, 'Setting status message timed out after 1s').catch((e) => log.warning(e.message));
513
- const runId = this.config.get('actorRunId');
514
- if (runId) {
515
- // just to be sure, this should be fast
516
- 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));
517
- if (run) {
518
- return run;
519
- }
794
+ return this.#updateRunStatusMessage(statusMessage, isStatusMessageTerminal);
795
+ }
796
+ /**
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.
799
+ */
800
+ async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
801
+ const runId = this.configuration.actorRunId;
802
+ if (!runId) {
803
+ return undefined;
520
804
  }
521
- 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
+ });
522
810
  }
523
811
  /**
524
812
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -540,33 +828,67 @@ export class Actor {
540
828
  * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
541
829
  * otherwise the Actor process might finish before the data are stored!
542
830
  *
831
+ * Inside a crawlee storage transaction, the items are stored - and charged for - at commit time,
832
+ * so the returned counts are zero and charging for an explicit `eventName` is rejected outright.
833
+ *
543
834
  * @param item Object or array of objects containing data to be stored in the default dataset.
544
835
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
545
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()`.
546
838
  * @ignore
547
839
  */
548
- // eslint-disable-next-line consistent-return -- The `return` is inconsistent by design here (`ChargeResult` with `eventName` parameter)
549
840
  async pushData(item, eventName) {
550
- this._ensureActorInit('pushData');
551
- const dataset = await this.openDataset();
552
- const maxChargedCount = eventName !== undefined
553
- ? this.chargingManager.calculateMaxEventChargeCountWithinLimit(eventName)
554
- : Infinity;
555
- const toCharge = Array.isArray(item) ? item.length : 1;
556
- if (toCharge > maxChargedCount) {
557
- // Push as many items as we can charge for
558
- const items = Array.isArray(item) ? item : [item];
559
- await dataset.pushData(items.slice(0, maxChargedCount));
841
+ this.ensureActorInit('pushData');
842
+ if (eventName?.startsWith('apify-')) {
843
+ throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
560
844
  }
561
- else {
562
- await dataset.pushData(item);
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.');
563
847
  }
564
- if (eventName) {
565
- return await this.chargingManager.charge({
848
+ if (eventName !== undefined) {
849
+ rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
850
+ 'so a rolled-back request would be billed for items that were never stored.');
851
+ }
852
+ const dataset = await this.openDataset();
853
+ const items = Array.isArray(item) ? item : [item];
854
+ // `Actor.pushData()` historically worked even without calling `Actor.init()`.
855
+ // In that case, charging isn't configured, so just push the data through.
856
+ if (!this.#chargingManager.isInitialized) {
857
+ await dataset.pushData(items);
858
+ return { eventChargeLimitReached: false, chargedCount: 0, chargeableWithinLimit: {} };
859
+ }
860
+ // The reservation below and the charge that acts on it have to stay under one lock, so that
861
+ // a concurrent push cannot charge in between. The dataset backend re-enters the same lock to
862
+ // charge the synthetic per-item event.
863
+ return await this.#chargingManager.withChargeLock(async () => {
864
+ if (eventName === undefined) {
865
+ // Nothing to charge here - the dataset backend charges the synthetic event for
866
+ // whatever it stores, so the result is read back off the charging state.
867
+ const chargedBefore = this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT);
868
+ await dataset.pushData(items);
869
+ return {
870
+ eventChargeLimitReached: this.#chargingManager.isEventChargeLimitReached(DEFAULT_DATASET_ITEM_EVENT),
871
+ chargedCount: this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT) - chargedBefore,
872
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
873
+ };
874
+ }
875
+ const limit = this.#chargingManager.calculatePushDataLimit(items.length, {
566
876
  eventName,
567
- count: Math.min(toCharge, maxChargedCount),
877
+ // Pushing one item charges the synthetic per-item event too when the dataset backend
878
+ // is the charging one, so that price is part of what an item costs here. Only the Actor's
879
+ // own backend wraps the default dataset for charging, a caller-supplied one is left as is.
880
+ isDefaultDataset: serviceLocator.getStorageBackend() === this.#cachedStorageBackend,
568
881
  });
569
- }
882
+ if (limit === 0) {
883
+ return {
884
+ eventChargeLimitReached: items.length > 0,
885
+ chargedCount: 0,
886
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
887
+ };
888
+ }
889
+ await dataset.pushData(limit < items.length ? items.slice(0, limit) : items);
890
+ return await this.#chargingManager.charge({ eventName, count: limit });
891
+ });
570
892
  }
571
893
  /**
572
894
  * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
@@ -578,51 +900,26 @@ export class Actor {
578
900
  * For more details and code examples, see the {@link Dataset} class.
579
901
  *
580
902
  * @param [datasetIdOrName]
581
- * ID or name of the dataset to be opened. If `null` or `undefined`,
903
+ * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
582
904
  * the function returns the default dataset associated with the Actor run.
905
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
906
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
583
907
  * @param [options]
584
908
  * @ignore
585
909
  */
586
910
  async openDataset(datasetIdOrName, options = {}) {
587
- ow(datasetIdOrName, ow.optional.string);
588
- ow(options, ow.object.exactShape({
589
- forceCloud: ow.optional.boolean,
590
- }));
591
- this._ensureActorInit('openDataset');
592
- return this._openStorage(Dataset, datasetIdOrName, options);
911
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
912
+ this.ensureActorInit('openDataset');
913
+ return Dataset.open(datasetIdOrName ?? null, {
914
+ storageBackend: options.forceCloud
915
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
916
+ : undefined,
917
+ });
593
918
  }
594
- /**
595
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
596
- *
597
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
598
- * For example, calling the following code:
599
- * ```js
600
- * const value = await Actor.getValue('my-key');
601
- * ```
602
- *
603
- * is equivalent to:
604
- * ```js
605
- * const store = await Actor.openKeyValueStore();
606
- * const value = await store.getValue('my-key');
607
- * ```
608
- *
609
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
610
- *
611
- * For more information, see {@link Actor.openKeyValueStore}
612
- * and {@link KeyValueStore.getValue}.
613
- *
614
- * @param key Unique record key.
615
- * @returns
616
- * Returns a promise that resolves to an object, string
617
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
618
- * on the MIME content type of the record, or `null`
619
- * if the record is missing.
620
- * @ignore
621
- */
622
- async getValue(key) {
623
- this._ensureActorInit('getValue');
919
+ async getValue(key, defaultValue) {
920
+ this.ensureActorInit('getValue');
624
921
  const store = await this.openKeyValueStore();
625
- return store.getValue(key);
922
+ return store.getValue(key, defaultValue);
626
923
  }
627
924
  /**
628
925
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -656,24 +953,28 @@ export class Actor {
656
953
  * @ignore
657
954
  */
658
955
  async setValue(key, value, options = {}) {
659
- this._ensureActorInit('setValue');
956
+ this.ensureActorInit('setValue');
660
957
  const store = await this.openKeyValueStore();
661
958
  return store.setValue(key, value, options);
662
959
  }
663
960
  /**
664
961
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
665
962
  *
666
- * This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](core/class/KeyValueStore#getValue).
667
- * For example, calling the following code:
668
- * ```js
669
- * const input = await Actor.getInput();
670
- * ```
963
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`).
964
+ * A record stored as `application/octet-stream` — which is what a local input file without an
965
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
671
966
  *
672
- * is equivalent to:
673
- * ```js
674
- * const store = await Actor.openKeyValueStore();
675
- * await store.getValue('INPUT');
676
- * ```
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.
973
+ *
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
976
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
977
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
677
978
  *
678
979
  * Note that the `getInput()` function does not cache the value read from the key-value store.
679
980
  * If you need to use the input multiple times in your Actor,
@@ -685,36 +986,85 @@ export class Actor {
685
986
  * @returns
686
987
  * Returns a promise that resolves to an object, string
687
988
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
688
- * on the MIME content type of the record, or `null`
689
- * if the record is missing.
989
+ * on the MIME content type of the record.
990
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
690
991
  * @ignore
691
992
  */
692
993
  async getInput() {
693
- this._ensureActorInit('getInput');
694
- const inputSecretsPrivateKeyFile = this.config.get('inputSecretsPrivateKeyFile');
695
- const inputSecretsPrivateKeyPassphrase = this.config.get('inputSecretsPrivateKeyPassphrase');
696
- const input = await this.getValue(this.config.get('inputKey'));
697
- if (ow.isValid(input, ow.object.nonEmpty) &&
698
- inputSecretsPrivateKeyFile &&
699
- inputSecretsPrivateKeyPassphrase) {
700
- const privateKey = createPrivateKey({
701
- key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
702
- passphrase: inputSecretsPrivateKeyPassphrase,
703
- });
704
- return decryptInputSecrets({ input, privateKey });
994
+ this.ensureActorInit('getInput');
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);
998
+ const store = await this.openKeyValueStore();
999
+ const record = await store.getRecord(inputKey);
1000
+ // Not a conflict check: under the file-system backend the record *is* the store directory's file.
1001
+ const storeInput = record
1002
+ ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
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;
1009
+ if (rawInput == null) {
1010
+ const locations = [`the "${inputKey}" record of the default key-value store`];
1011
+ if (!this.configuration.isAtHome) {
1012
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
1013
+ }
1014
+ throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
1015
+ }
1016
+ let input = rawInput;
1017
+ if (isNonEmptyObject(rawInput) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
1018
+ try {
1019
+ const privateKey = createPrivateKey({
1020
+ key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
1021
+ passphrase: inputSecretsPrivateKeyPassphrase,
1022
+ });
1023
+ input = decryptInputSecrets({ input: rawInput, privateKey });
1024
+ }
1025
+ catch (cause) {
1026
+ throw new ActorInputError('DECRYPTION_FAILED', 'Failed to decrypt the secret fields of the input.', {
1027
+ cause,
1028
+ });
1029
+ }
1030
+ }
1031
+ if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
1032
+ input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
705
1033
  }
706
1034
  return input;
707
1035
  }
708
1036
  /**
709
- * Gets the Actor input value just like the {@link Actor.getInput} method,
710
- * but throws if it is not found.
1037
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
1038
+ * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
1039
+ * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
1040
+ * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
1041
+ *
1042
+ * @returns `undefined` when running on the platform or when neither file exists.
711
1043
  */
712
- async getInputOrThrow() {
713
- const input = await this.getInput();
714
- if (input == null) {
715
- throw new Error('Input does not exist');
1044
+ async readInputFromDirectory(inputKey, directory, label) {
1045
+ if (this.configuration.isAtHome) {
1046
+ return undefined;
716
1047
  }
717
- return input;
1048
+ const candidates = [
1049
+ { filename: inputKey, contentType: BINARY_CONTENT_TYPE },
1050
+ { filename: `${inputKey}.json`, contentType: JSON_CONTENT_TYPE },
1051
+ ];
1052
+ const found = [];
1053
+ for (const candidate of candidates) {
1054
+ const path = join(directory, candidate.filename);
1055
+ const stats = await stat(path).catch(() => null);
1056
+ if (stats?.isFile()) {
1057
+ found.push({ ...candidate, path });
1058
+ }
1059
+ }
1060
+ if (found.length > 1) {
1061
+ throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
1062
+ }
1063
+ if (found.length === 0) {
1064
+ return undefined;
1065
+ }
1066
+ const [file] = found;
1067
+ return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
718
1068
  }
719
1069
  /**
720
1070
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -726,18 +1076,21 @@ export class Actor {
726
1076
  * For more details and code examples, see the {@link KeyValueStore} class.
727
1077
  *
728
1078
  * @param [storeIdOrName]
729
- * ID or name of the key-value store to be opened. If `null` or `undefined`,
1079
+ * ID, name, or alias of the key-value store to be opened. If `null` or `undefined`,
730
1080
  * the function returns the default key-value store associated with the Actor run.
1081
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1082
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
731
1083
  * @param [options]
732
1084
  * @ignore
733
1085
  */
734
1086
  async openKeyValueStore(storeIdOrName, options = {}) {
735
- ow(storeIdOrName, ow.optional.string);
736
- ow(options, ow.object.exactShape({
737
- forceCloud: ow.optional.boolean,
738
- }));
739
- this._ensureActorInit('openKeyValueStore');
740
- return this._openStorage(KeyValueStore, storeIdOrName, options);
1087
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1088
+ this.ensureActorInit('openKeyValueStore');
1089
+ return KeyValueStore.open(storeIdOrName ?? null, {
1090
+ storageBackend: options.forceCloud
1091
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1092
+ : undefined,
1093
+ });
741
1094
  }
742
1095
  /**
743
1096
  * Opens a request queue and returns a promise resolving to an instance
@@ -751,22 +1104,21 @@ export class Actor {
751
1104
  * For more details and code examples, see the {@link RequestQueue} class.
752
1105
  *
753
1106
  * @param [queueIdOrName]
754
- * ID or name of the request queue to be opened. If `null` or `undefined`,
1107
+ * ID, name, or alias of the request queue to be opened. If `null` or `undefined`,
755
1108
  * the function returns the default request queue associated with the Actor run.
1109
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1110
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
756
1111
  * @param [options]
757
1112
  * @ignore
758
1113
  */
759
1114
  async openRequestQueue(queueIdOrName, options = {}) {
760
- ow(queueIdOrName, ow.optional.string);
761
- ow(options, ow.object.exactShape({
762
- forceCloud: ow.optional.boolean,
763
- }));
764
- this._ensureActorInit('openRequestQueue');
765
- const queue = await this._openStorage(RequestQueue, queueIdOrName, options);
766
- // eslint-disable-next-line dot-notation
767
- queue['initialCount'] =
768
- (await queue.client.get())?.totalRequestCount ?? 0;
769
- return queue;
1115
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1116
+ this.ensureActorInit('openRequestQueue');
1117
+ return RequestQueue.open(queueIdOrName ?? null, {
1118
+ storageBackend: options.forceCloud
1119
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1120
+ : undefined,
1121
+ });
770
1122
  }
771
1123
  /**
772
1124
  * Creates a proxy configuration and returns a promise resolving to an instance
@@ -802,19 +1154,23 @@ export class Actor {
802
1154
  * ```
803
1155
  * { useApifyProxy: false }
804
1156
  * ```
1157
+ *
1158
+ * As part of the init process, we verify the configuration by checking the proxy status endpoint.
1159
+ * This can make the init slower, to opt-out of this, use `checkAccess: false` (defaults to `true`).
1160
+ *
805
1161
  * @ignore
806
1162
  */
807
1163
  async createProxyConfiguration(proxyConfigurationOptions = {}) {
808
1164
  // Compatibility fix for Input UI where proxy: None returns { useApifyProxy: false }
809
1165
  // Without this, it would cause proxy to use the zero config / auto mode.
810
- const { useApifyProxy, ...options } = proxyConfigurationOptions;
1166
+ const { useApifyProxy, checkAccess, ...options } = proxyConfigurationOptions;
811
1167
  const dontUseApifyProxy = useApifyProxy === false;
812
1168
  const dontUseCustomProxies = !proxyConfigurationOptions.proxyUrls;
813
1169
  if (dontUseApifyProxy && dontUseCustomProxies) {
814
1170
  return undefined;
815
1171
  }
816
- const proxyConfiguration = new ProxyConfiguration(options, this.config);
817
- if (await proxyConfiguration.initialize()) {
1172
+ const proxyConfiguration = new ProxyConfiguration(options, this.configuration);
1173
+ if (await proxyConfiguration.initialize({ checkAccess })) {
818
1174
  return proxyConfiguration;
819
1175
  }
820
1176
  return undefined;
@@ -825,20 +1181,66 @@ export class Actor {
825
1181
  * This method attempts to charge for the specified number of events, but may charge fewer
826
1182
  * if doing so would exceed the total budget limit (`maxTotalChargeUsd`).
827
1183
  *
1184
+ * **Important:** When using the `count` parameter to charge for multiple events at once,
1185
+ * be aware that the charge may be partially fulfilled — i.e. `chargedCount` can be less
1186
+ * than the requested `count`. Always check the returned `chargedCount` to know how many
1187
+ * events were actually charged, and only perform that much work. If your work is
1188
+ * meaningfully divisible into individual units, prefer calling `charge()` once per unit
1189
+ * rather than batching via `count` — this gives finer control over budget consumption
1190
+ * and avoids situations where more work is requested than the budget allows.
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
+ *
828
1196
  * @param options The name of the event to charge for and the number of events to be charged.
829
1197
  * @ignore
830
1198
  */
831
1199
  async charge(options) {
832
- this._ensureActorInit('charge');
833
- return this.chargingManager.charge(options);
1200
+ this.ensureActorInit('charge');
1201
+ return this.#chargingManager.charge(options);
834
1202
  }
835
1203
  /**
836
1204
  * Retrieve the charging manager to access granular pricing information.
837
1205
  * @ignore
838
1206
  */
839
1207
  getChargingManager() {
840
- this._ensureActorInit('getChargingManager');
841
- return this.chargingManager;
1208
+ this.ensureActorInit('getChargingManager');
1209
+ return this.#chargingManager;
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;
842
1244
  }
843
1245
  /**
844
1246
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
@@ -860,7 +1262,7 @@ export class Actor {
860
1262
  * Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
861
1263
  *
862
1264
  * For the list of the Apify environment variables, see
863
- * [Actor documentation](https://docs.apify.com/actor/run#environment-variables).
1265
+ * [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
864
1266
  * If some variables are not defined or are invalid, the corresponding value in the resulting object will be null.
865
1267
  * @ignore
866
1268
  */
@@ -872,17 +1274,22 @@ export class Actor {
872
1274
  ...APIFY_ENV_VARS,
873
1275
  ...this.getModifiedActorEnvVars(),
874
1276
  })) {
1277
+ if (IGNORED_ENV_VARS.includes(fullName))
1278
+ continue;
875
1279
  const camelCaseName = snakeCaseToCamelCase(shortName);
876
1280
  let value = env[fullName];
877
- // Parse dates and integers.
878
- 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')) {
879
1286
  const unix = Date.parse(value);
880
1287
  value = unix > 0 ? new Date(unix) : undefined;
881
1288
  }
882
1289
  else if (INTEGER_ENV_VARS.includes(fullName)) {
883
1290
  value = parseInt(value, 10);
884
1291
  }
885
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1292
+ Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
886
1293
  }
887
1294
  return envVars;
888
1295
  }
@@ -895,15 +1302,13 @@ export class Actor {
895
1302
  * @ignore
896
1303
  */
897
1304
  newClient(options = {}) {
898
- const { storageDir, ...storageClientOptions } = this.config.get('storageClientOptions');
1305
+ const { storageDir, ...storageClientOptions } = (this.configuration.storageClientOptions ?? {});
899
1306
  const { apifyVersion, crawleeVersion } = getSystemInfo();
900
1307
  return new ApifyClient({
901
- baseUrl: this.config.get('apiBaseUrl'),
902
- token: this.config.get('token'),
903
- userAgentSuffix: [
904
- `SDK/${apifyVersion}`,
905
- `Crawlee/${crawleeVersion}`,
906
- ],
1308
+ baseUrl: this.configuration.apiBaseUrl,
1309
+ publicBaseUrl: this.configuration.apiPublicBaseUrl,
1310
+ token: this.configuration.token,
1311
+ userAgentSuffix: [`SDK/${apifyVersion}`, `Crawlee/${crawleeVersion}`],
907
1312
  ...storageClientOptions,
908
1313
  ...options, // allow overriding the instance configuration
909
1314
  });
@@ -925,8 +1330,9 @@ export class Actor {
925
1330
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
926
1331
  */
927
1332
  async useState(name, defaultValue = {}, options) {
1333
+ this.ensureActorInit('useState');
928
1334
  const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
929
- config: options?.config || Configuration.getGlobalConfig(),
1335
+ configuration: options?.configuration ?? this.configuration,
930
1336
  });
931
1337
  return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
932
1338
  }
@@ -977,24 +1383,22 @@ export class Actor {
977
1383
  *
978
1384
  * If the user function returns a promise, it is considered asynchronous:
979
1385
  * ```js
980
- * import { gotScraping } from 'got-scraping';
981
- *
982
1386
  * await Actor.main(() => {
983
1387
  * // My asynchronous function that returns a promise
984
- * return gotScraping('http://www.example.com').then((html) => {
985
- * console.log(html);
986
- * });
1388
+ * return fetch('http://www.example.com')
1389
+ * .then((response) => response.text())
1390
+ * .then((html) => {
1391
+ * console.log(html);
1392
+ * });
987
1393
  * });
988
1394
  * ```
989
1395
  *
990
1396
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
991
1397
  *
992
1398
  * ```js
993
- * import { gotScraping } from 'got-scraping';
994
- *
995
1399
  * await Actor.main(async () => {
996
1400
  * // My asynchronous function
997
- * const html = await gotScraping('http://www.example.com');
1401
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
998
1402
  * console.log(html);
999
1403
  * });
1000
1404
  * ```
@@ -1016,12 +1420,15 @@ export class Actor {
1016
1420
  * Calling `Actor.exit()` is required if you use the `Actor.init()` method, since it opens websocket connection
1017
1421
  * (see {@link Actor.events} for details), which needs to be terminated for the code to finish.
1018
1422
  *
1019
- * ```js
1020
- * import { gotScraping } from 'got-scraping';
1423
+ * **Graceful shutdown:** When running on the Apify platform, the Actor may receive `aborting` or `migrating`
1424
+ * events. By default, the SDK will automatically call `Actor.exit()` on `aborting` events and `Actor.reboot()`
1425
+ * on `migrating` events (to speed up the migration and continue the run on a new worker). You can disable this
1426
+ * behavior by setting `options.gracefulShutdown` to `false`.
1021
1427
  *
1428
+ * ```js
1022
1429
  * await Actor.init();
1023
1430
  *
1024
- * const html = await gotScraping('http://www.example.com');
1431
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
1025
1432
  * console.log(html);
1026
1433
  *
1027
1434
  * await Actor.exit();
@@ -1072,9 +1479,8 @@ export class Actor {
1072
1479
  * @param actorId
1073
1480
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1074
1481
  * @param [input]
1075
- * Input for the Actor. If it is an object, it will be stringified to
1076
- * JSON and its content type set to `application/json; charset=utf-8`.
1077
- * Otherwise the `options.contentType` parameter must be provided.
1482
+ * Input for the Actor. A plain object is stringified to JSON with content type
1483
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1078
1484
  * @param [options]
1079
1485
  */
1080
1486
  static async call(actorId, input, options = {}) {
@@ -1108,6 +1514,31 @@ export class Actor {
1108
1514
  static async callTask(taskId, input, options = {}) {
1109
1515
  return Actor.getDefaultInstance().callTask(taskId, input, options);
1110
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
+ }
1111
1542
  /**
1112
1543
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1113
1544
  * unlike `Actor.call`, this method just starts the run without waiting for finish.
@@ -1126,14 +1557,28 @@ export class Actor {
1126
1557
  * @param actorId
1127
1558
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1128
1559
  * @param [input]
1129
- * Input for the Actor. If it is an object, it will be stringified to
1130
- * JSON and its content type set to `application/json; charset=utf-8`.
1131
- * Otherwise the `options.contentType` parameter must be provided.
1560
+ * Input for the Actor. A plain object is stringified to JSON with content type
1561
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1132
1562
  * @param [options]
1133
1563
  */
1134
1564
  static async start(actorId, input, options = {}) {
1135
1565
  return Actor.getDefaultInstance().start(actorId, input, options);
1136
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
+ }
1137
1582
  /**
1138
1583
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1139
1584
  *
@@ -1151,6 +1596,26 @@ export class Actor {
1151
1596
  static async abort(runId, options = {}) {
1152
1597
  return Actor.getDefaultInstance().abort(runId, options);
1153
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
+ }
1154
1619
  /**
1155
1620
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
1156
1621
  * the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
@@ -1159,9 +1624,8 @@ export class Actor {
1159
1624
  * @param targetActorId
1160
1625
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
1161
1626
  * @param [input]
1162
- * Input for the Actor. If it is an object, it will be stringified to
1163
- * JSON and its content type set to `application/json; charset=utf-8`.
1164
- * Otherwise, the `options.contentType` parameter must be provided.
1627
+ * Input for the Actor. A plain object is stringified to JSON with content type
1628
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1165
1629
  * @param [options]
1166
1630
  */
1167
1631
  static async metamorph(targetActorId, input, options = {}) {
@@ -1196,7 +1660,8 @@ export class Actor {
1196
1660
  * @param [options]
1197
1661
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1198
1662
  * This is required for the last status message of the run. Default value is `false`.
1199
- * @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).
1200
1665
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1201
1666
  */
1202
1667
  static async setStatusMessage(statusMessage, options) {
@@ -1225,6 +1690,7 @@ export class Actor {
1225
1690
  * @param item Object or array of objects containing data to be stored in the default dataset.
1226
1691
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1227
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()`.
1228
1694
  */
1229
1695
  static async pushData(item, eventName) {
1230
1696
  if (eventName === undefined) {
@@ -1242,42 +1708,17 @@ export class Actor {
1242
1708
  * For more details and code examples, see the {@link Dataset} class.
1243
1709
  *
1244
1710
  * @param [datasetIdOrName]
1245
- * ID or name of the dataset to be opened. If `null` or `undefined`,
1711
+ * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
1246
1712
  * the function returns the default dataset associated with the Actor run.
1713
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1714
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
1247
1715
  * @param [options]
1248
1716
  */
1249
1717
  static async openDataset(datasetIdOrName, options = {}) {
1250
1718
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1251
1719
  }
1252
- /**
1253
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
1254
- *
1255
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
1256
- * For example, calling the following code:
1257
- * ```js
1258
- * const value = await Actor.getValue('my-key');
1259
- * ```
1260
- *
1261
- * is equivalent to:
1262
- * ```js
1263
- * const store = await Actor.openKeyValueStore();
1264
- * const value = await store.getValue('my-key');
1265
- * ```
1266
- *
1267
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
1268
- *
1269
- * For more information, see {@link Actor.openKeyValueStore}
1270
- * and {@link KeyValueStore.getValue}.
1271
- *
1272
- * @param key Unique record key.
1273
- * @returns
1274
- * Returns a promise that resolves to an object, string
1275
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1276
- * on the MIME content type of the record, or `null`
1277
- * if the record is missing.
1278
- */
1279
- static async getValue(key) {
1280
- return Actor.getDefaultInstance().getValue(key);
1720
+ static async getValue(key, defaultValue) {
1721
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1281
1722
  }
1282
1723
  /**
1283
1724
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1315,16 +1756,31 @@ export class Actor {
1315
1756
  /**
1316
1757
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
1317
1758
  *
1318
- * This is just a convenient shortcut for {@link KeyValueStore.getValue | `keyValueStore.getValue('INPUT')`}.
1319
- * For example, calling the following code:
1759
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`):
1320
1760
  * ```js
1321
1761
  * const input = await Actor.getInput();
1322
1762
  * ```
1323
1763
  *
1324
- * is equivalent to:
1764
+ * A record stored as `application/octet-stream` — which is what a local input file without an
1765
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1766
+ *
1767
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1768
+ * working directory.
1769
+ *
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
1775
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1776
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1325
1777
  * ```js
1326
- * const store = await Actor.openKeyValueStore();
1327
- * await store.getValue('INPUT');
1778
+ * let input = {};
1779
+ * try {
1780
+ * input = await Actor.getInput();
1781
+ * } catch (error) {
1782
+ * if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
1783
+ * }
1328
1784
  * ```
1329
1785
  *
1330
1786
  * Note that the `getInput()` function does not cache the value read from the key-value store.
@@ -1336,19 +1792,12 @@ export class Actor {
1336
1792
  * @returns
1337
1793
  * Returns a promise that resolves to an object, string
1338
1794
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1339
- * on the MIME content type of the record, or `null`
1340
- * if the record is missing.
1795
+ * on the MIME content type of the record.
1796
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
1341
1797
  */
1342
1798
  static async getInput() {
1343
1799
  return Actor.getDefaultInstance().getInput();
1344
1800
  }
1345
- /**
1346
- * Gets the Actor input value just like the {@link Actor.getInput} method,
1347
- * but throws if it is not found.
1348
- */
1349
- static async getInputOrThrow() {
1350
- return Actor.getDefaultInstance().getInputOrThrow();
1351
- }
1352
1801
  /**
1353
1802
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
1354
1803
  *
@@ -1361,6 +1810,7 @@ export class Actor {
1361
1810
  * @param [storeIdOrName]
1362
1811
  * ID or name of the key-value store to be opened. If `null` or `undefined`,
1363
1812
  * the function returns the default key-value store associated with the Actor run.
1813
+ * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1364
1814
  * @param [options]
1365
1815
  */
1366
1816
  static async openKeyValueStore(storeIdOrName, options = {}) {
@@ -1380,6 +1830,7 @@ export class Actor {
1380
1830
  * @param [queueIdOrName]
1381
1831
  * ID or name of the request queue to be opened. If `null` or `undefined`,
1382
1832
  * the function returns the default request queue associated with the Actor run.
1833
+ * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1383
1834
  * @param [options]
1384
1835
  */
1385
1836
  static async openRequestQueue(queueIdOrName, options = {}) {
@@ -1419,6 +1870,9 @@ export class Actor {
1419
1870
  * ```
1420
1871
  * { useApifyProxy: false }
1421
1872
  * ```
1873
+ *
1874
+ * As part of the init process, we verify the configuration by checking the proxy status endpoint.
1875
+ * This can make the init slower, to opt-out of this, use `checkAccess: false` (defaults to `true`).
1422
1876
  */
1423
1877
  static async createProxyConfiguration(proxyConfigurationOptions = {}) {
1424
1878
  return Actor.getDefaultInstance().createProxyConfiguration(proxyConfigurationOptions);
@@ -1429,6 +1883,18 @@ export class Actor {
1429
1883
  * This method attempts to charge for the specified number of events, but may charge fewer
1430
1884
  * if doing so would exceed the total budget limit (`maxTotalChargeUsd`).
1431
1885
  *
1886
+ * **Important:** When using the `count` parameter to charge for multiple events at once,
1887
+ * be aware that the charge may be partially fulfilled — i.e. `chargedCount` can be less
1888
+ * than the requested `count`. Always check the returned `chargedCount` to know how many
1889
+ * events were actually charged, and only perform that much work. If your work is
1890
+ * meaningfully divisible into individual units, prefer calling `charge()` once per unit
1891
+ * rather than batching via `count` — this gives finer control over budget consumption
1892
+ * and avoids situations where more work is requested than the budget allows.
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
+ *
1432
1898
  * @param options The name of the event to charge for and the number of events to be charged.
1433
1899
  */
1434
1900
  static async charge(options) {
@@ -1444,7 +1910,7 @@ export class Actor {
1444
1910
  * Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
1445
1911
  *
1446
1912
  * For the list of the Apify environment variables, see
1447
- * [Actor documentation](https://docs.apify.com/actor/run#environment-variables).
1913
+ * [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
1448
1914
  * If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.
1449
1915
  */
1450
1916
  static getEnv() {
@@ -1466,36 +1932,143 @@ export class Actor {
1466
1932
  static isAtHome() {
1467
1933
  return Actor.getDefaultInstance().isAtHome();
1468
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
+ }
1469
1943
  /** Default {@link ApifyClient} instance. */
1470
1944
  static get apifyClient() {
1471
1945
  return Actor.getDefaultInstance().apifyClient;
1472
1946
  }
1473
1947
  /** Default {@link Configuration} instance. */
1474
- static get config() {
1475
- return Actor.getDefaultInstance().config;
1948
+ static get configuration() {
1949
+ return Actor.getDefaultInstance().configuration;
1476
1950
  }
1477
1951
  /** @internal */
1478
1952
  static getDefaultInstance() {
1479
- this._instance ??= new Actor();
1480
- return this._instance;
1953
+ Actor.#instance ??= new Actor();
1954
+ return Actor.#instance;
1955
+ }
1956
+ /**
1957
+ * Replaces or clears the cached default instance returned by {@link Actor.getDefaultInstance}.
1958
+ * @internal
1959
+ */
1960
+ static setDefaultInstance(instance) {
1961
+ Actor.#instance = instance;
1962
+ }
1963
+ /**
1964
+ * The backend the Actor installs unless the caller brings one: Apify platform storage on the
1965
+ * platform, crawlee's local default outside of it.
1966
+ *
1967
+ * Both sides are wrapped for dataset-item charging - crawlee's local default stands in for
1968
+ * Apify storage, so local pay-per-event testing stays faithful. A caller-supplied backend
1969
+ * (`Actor.init({ storage })`) is billed nothing and is installed unwrapped, in place of this.
1970
+ *
1971
+ * One instance per Actor: a second platform backend would mint unnamed storages of its own for
1972
+ * aliases this one has already resolved.
1973
+ */
1974
+ get #storageBackend() {
1975
+ const charging = {
1976
+ configuration: this.configuration,
1977
+ getChargingManager: () => this.#chargingManager,
1978
+ };
1979
+ return (this.#cachedStorageBackend ??= new SmartApifyStorageBackend({
1980
+ cloudStorageBackend: new ChargingStorageBackend(new ApifyStorageBackend(this.apifyClient, {
1981
+ configuration: this.configuration,
1982
+ requestQueueAccess: this.#requestQueueAccess,
1983
+ }), charging),
1984
+ localStorageBackend: new ChargingStorageBackend(this.createLocalStorageBackend(), charging),
1985
+ configuration: this.configuration,
1986
+ }));
1987
+ }
1988
+ /**
1989
+ * The same choice crawlee's `ServiceLocator` makes for its implicit default backend, with the
1990
+ * input-aware {@link ApifyFileSystemStorageBackend} in place of crawlee's — crawlee has no
1991
+ * notion of a run input.
1992
+ */
1993
+ createLocalStorageBackend() {
1994
+ const { persistStorage, storageDir, inputKey } = this.configuration;
1995
+ const logger = serviceLocator.getLogger();
1996
+ if (!persistStorage) {
1997
+ return new MemoryStorageBackend({ logger: logger.child({ prefix: 'MemoryStorageBackend' }) });
1998
+ }
1999
+ return new ApifyFileSystemStorageBackend({
2000
+ localDataDirectory: storageDir,
2001
+ inputKey,
2002
+ logger: logger.child({ prefix: 'ApifyFileSystemStorageBackend' }),
2003
+ });
2004
+ }
2005
+ /** Whether items reaching the run's default dataset are counted for pay-per-event charging. */
2006
+ #chargesDefaultDatasetItems() {
2007
+ const installed = serviceLocator.getStorageBackend();
2008
+ return installed instanceof SmartApifyStorageBackend || installed instanceof ChargingStorageBackend;
1481
2009
  }
1482
- async _openStorage(storageClass, id, options = {}) {
1483
- const client = options.forceCloud ? this.apifyClient : undefined;
1484
- return StorageManager.openStorage(storageClass, id, client, this.config);
2010
+ /**
2011
+ * crawlee's service locator is set-once, so a backend registered before `init()` wins and the
2012
+ * Actor cannot install its own over it. Replaces the resulting `ServiceConflictError` with the
2013
+ * way out.
2014
+ */
2015
+ installStorageBackend(backend) {
2016
+ try {
2017
+ serviceLocator.setStorageBackend(backend);
2018
+ }
2019
+ catch (error) {
2020
+ throw new Error('A storage backend is already registered with crawlee, so the Actor cannot install its own. Pass it ' +
2021
+ 'as `Actor.init({ storage })` instead of calling `serviceLocator.setStorageBackend()`.', { cause: error });
2022
+ }
1485
2023
  }
1486
- _ensureActorInit(methodCalled) {
2024
+ ensureActorInit(methodCalled) {
1487
2025
  // If we already warned the user once, don't do it again to prevent spam
1488
- if (this.warnedAboutMissingInitCall) {
2026
+ if (this.#warnedAboutMissingInitCall) {
1489
2027
  return;
1490
2028
  }
1491
2029
  if (this.initialized) {
1492
2030
  return;
1493
2031
  }
1494
- this.warnedAboutMissingInitCall = true;
2032
+ this.#warnedAboutMissingInitCall = true;
1495
2033
  log.warning([
1496
2034
  `Actor.${methodCalled}() was called but the Actor instance was not initialized.`,
1497
2035
  'Did you forget to call Actor.init()?',
1498
2036
  ].join('\n'));
1499
2037
  }
2038
+ /**
2039
+ * Get time remaining from the Actor run timeout in seconds, rounded up to whole seconds with minimum value of 1 second.
2040
+ *
2041
+ * The API treats a 0 second timeout as no timeout, the minimum acceptable timeout is 1 second.
2042
+ *
2043
+ * Returns `undefined` if not on the Apify platform or the current run was started without a timeout.
2044
+ */
2045
+ getRemainingTimeSecs() {
2046
+ const env = this.getEnv();
2047
+ const MINIMUM_API_TIMEOUT_SECS = 1;
2048
+ if (this.isAtHome() && env.timeoutAt !== null) {
2049
+ return Math.max(Math.ceil((env.timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
2050
+ }
2051
+ log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
2052
+ 'timeout for the Actor run is set.');
2053
+ return undefined;
2054
+ }
2055
+ async inferDefaultsFromInputSchema(input) {
2056
+ // TODO: https://github.com/apify/apify-shared-js/issues/547
2057
+ // On platform, this is already handled
2058
+ if (this.isAtHome()) {
2059
+ return input;
2060
+ }
2061
+ // On local, we can get the input schema from the local config
2062
+ const inputSchema = readInputSchema();
2063
+ // Don't emit warning if there is no input schema defined
2064
+ if (inputSchema === noActorInputSchemaDefinedMarker) {
2065
+ return input;
2066
+ }
2067
+ if (!inputSchema) {
2068
+ log.warning('Failed to find the input schema for the local run of this Actor. Your input will be missing fields that have default values set if they are missing from the input you are using.');
2069
+ return input;
2070
+ }
2071
+ const defaults = getDefaultsFromInputSchema(inputSchema);
2072
+ return { ...defaults, ...input };
2073
+ }
1500
2074
  }
1501
- //# sourceMappingURL=actor.js.map