apify 4.0.0-beta.63 → 4.0.0-beta.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actor.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { EventManager, EventTypeName, RecordOptions, UseStateOptions } from '@crawlee/core';
2
2
  import { Dataset, KeyValueStore, RequestQueue } from '@crawlee/core';
3
3
  import type { Awaitable, Dictionary, StorageBackend } from '@crawlee/types';
4
- import type { ActorCallOptions, ActorInput, ActorStartOptions, ApifyClientOptions, RunAbortOptions, RunResurrectOptions, TaskCallOptions, TaskStartOptions, WebhookResource, WebhookEventType } from 'apify-client';
4
+ import type { ActorCallOptions, ActorInput, ActorStartOptions, ApifyClientOptions, RunAbortOptions, RunClient, RunResurrectOptions, TaskCallOptions, TaskStartOptions, WebhookResource, WebhookEventType } from 'apify-client';
5
5
  import { ApifyClient, Run as ClientActorRun } from 'apify-client';
6
6
  import { type ACTOR_PERMISSION_LEVEL } from '@apify/consts';
7
7
  import type { RequestQueueAccessMode } from './apify_request_queue_backend.js';
@@ -222,15 +222,26 @@ export interface Timeout {
222
222
  */
223
223
  timeout?: number | 'inherit';
224
224
  }
225
- export interface CallOptions extends Omit<ActorCallOptions, 'runTimeoutSecs'>, Token, Timeout {
225
+ export interface ChildRunOptions {
226
+ /**
227
+ * Local name for the child run, unique across all Actors and tasks started by this run.
228
+ *
229
+ * If a `READY`, `RUNNING` or `SUCCEEDED` run is already tracked under this name, it is returned instead of
230
+ * starting a new one, including after a migration or resurrection of this run. A run that was aborted or timed out
231
+ * is resurrected with the given options, once it finishes aborting or timing out. A run that failed is replaced
232
+ * by a new one. Reusing the name for a different Actor, task or input throws, unless the tracked run is replaced.
233
+ */
234
+ runName?: string;
226
235
  }
227
- export interface StartOptions extends Omit<ActorStartOptions, 'waitForFinish' | 'runTimeoutSecs'>, Token, Timeout {
236
+ export interface CallOptions extends Omit<ActorCallOptions, 'runTimeoutSecs'>, Token, Timeout, ChildRunOptions {
228
237
  }
229
- export interface CallTaskOptions extends Omit<TaskCallOptions, 'runTimeoutSecs'>, Token, Timeout {
238
+ export interface StartOptions extends Omit<ActorStartOptions, 'waitForFinish' | 'runTimeoutSecs'>, Token, Timeout, ChildRunOptions {
239
+ }
240
+ export interface CallTaskOptions extends Omit<TaskCallOptions, 'runTimeoutSecs'>, Token, Timeout, ChildRunOptions {
230
241
  }
231
242
  export interface ResurrectOptions extends Omit<RunResurrectOptions, 'runTimeoutSecs'>, Token, Timeout {
232
243
  }
233
- export interface StartTaskOptions extends Omit<TaskStartOptions, 'waitForFinish' | 'runTimeoutSecs'>, Token, Timeout {
244
+ export interface StartTaskOptions extends Omit<TaskStartOptions, 'waitForFinish' | 'runTimeoutSecs'>, Token, Timeout, ChildRunOptions {
234
245
  }
235
246
  export interface AbortOptions extends RunAbortOptions, Token {
236
247
  /** Exit with given status message */
@@ -542,6 +553,19 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
542
553
  * @ignore
543
554
  */
544
555
  callTask(taskId: string, input?: Dictionary, options?: CallTaskOptions): Promise<ClientActorRun>;
556
+ /**
557
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
558
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
559
+ *
560
+ * ```js
561
+ * await Actor.childRuns['my-child'].waitForFinish();
562
+ * ```
563
+ *
564
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
565
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
566
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
567
+ */
568
+ get childRuns(): Record<string, RunClient>;
545
569
  /**
546
570
  * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
547
571
  * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
@@ -725,10 +749,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
725
749
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
726
750
  *
727
751
  * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
728
- * `<inputKey>.json` file in the current working directory instead.
752
+ * `<inputKey>.json` file in the current working directory, then in the storage directory.
729
753
  *
730
754
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
731
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
755
+ * files exist in the working/storage directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
732
756
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
733
757
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
734
758
  *
@@ -748,14 +772,14 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
748
772
  */
749
773
  getInput<T = Dictionary | string | Buffer>(): Promise<T>;
750
774
  /**
751
- * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the working directory, for local runs
775
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
752
776
  * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
753
777
  * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
754
778
  * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
755
779
  *
756
780
  * @returns `undefined` when running on the platform or when neither file exists.
757
781
  */
758
- private readInputFromWorkingDirectory;
782
+ private readInputFromDirectory;
759
783
  /**
760
784
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
761
785
  *
@@ -1103,6 +1127,19 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1103
1127
  * @param [options]
1104
1128
  */
1105
1129
  static start(actorId: string, input?: Dictionary, options?: StartOptions): Promise<ClientActorRun>;
1130
+ /**
1131
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1132
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
1133
+ *
1134
+ * ```js
1135
+ * await Actor.childRuns['my-child'].waitForFinish();
1136
+ * ```
1137
+ *
1138
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
1139
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1140
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1141
+ */
1142
+ static get childRuns(): Record<string, RunClient>;
1106
1143
  /**
1107
1144
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1108
1145
  *
package/dist/actor.js CHANGED
@@ -14,6 +14,7 @@ import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backe
14
14
  import { ApifyStorageBackend } from './apify_storage_backend.js';
15
15
  import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
16
16
  import { ChargingStorageBackend } from './charging_storage_backend.js';
17
+ import { ChildRunTracker } from './child_run_tracker.js';
17
18
  import { Configuration } from './configuration.js';
18
19
  import { ActorInputError } from './errors.js';
19
20
  import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
@@ -52,6 +53,7 @@ export const EXIT_CODES = {
52
53
  export class Actor {
53
54
  /** @internal */
54
55
  static #instance;
56
+ #childRunTracker;
55
57
  /**
56
58
  * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
57
59
  * @internal
@@ -122,6 +124,7 @@ export class Actor {
122
124
  this.apifyClient = this.newClient();
123
125
  this.eventManager = new PlatformEventManager(this.configuration);
124
126
  this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
127
+ this.#childRunTracker = new ChildRunTracker();
125
128
  }
126
129
  /**
127
130
  * Runs the main user function that performs the job of the Actor
@@ -270,6 +273,7 @@ export class Actor {
270
273
  onlyPurgeOnce: true,
271
274
  });
272
275
  log.debug(`Default storages purged`);
276
+ await this.#childRunTracker.load();
273
277
  await this.#chargingManager.init();
274
278
  log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
275
279
  // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
@@ -401,9 +405,24 @@ export class Actor {
401
405
  */
402
406
  async call(actorId, input, options = {}) {
403
407
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
404
- const { token, timeout: _timeout, ...rest } = options;
408
+ const { token, timeout: _timeout, runName, ...rest } = options;
405
409
  const client = token ? this.newClient({ token }) : this.apifyClient;
406
- return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
410
+ if (!runName)
411
+ return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
412
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
413
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
414
+ const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, async () => client.actor(actorId).start(input, startOptions));
415
+ // The earlier part of a resumed run's log was already redirected before the migration.
416
+ const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
417
+ streamedLog?.start();
418
+ try {
419
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
420
+ await this.#childRunTracker.update(runName, finishedRun);
421
+ return finishedRun;
422
+ }
423
+ finally {
424
+ await streamedLog?.stop();
425
+ }
407
426
  }
408
427
  /**
409
428
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -430,9 +449,13 @@ export class Actor {
430
449
  */
431
450
  async start(actorId, input, options = {}) {
432
451
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
433
- const { token, timeout: _timeout, ...rest } = options;
452
+ const { token, timeout: _timeout, runName, ...rest } = options;
434
453
  const client = token ? this.newClient({ token }) : this.apifyClient;
435
- return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
454
+ if (!runName)
455
+ return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
456
+ const startOptions = { ...rest, runTimeoutSecs };
457
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, async () => client.actor(actorId).start(input, startOptions));
458
+ return run;
436
459
  }
437
460
  /**
438
461
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -511,9 +534,32 @@ export class Actor {
511
534
  */
512
535
  async callTask(taskId, input, options = {}) {
513
536
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
514
- const { token, timeout: _timeout, ...rest } = options;
537
+ const { token, timeout: _timeout, runName, ...rest } = options;
515
538
  const client = token ? this.newClient({ token }) : this.apifyClient;
516
- return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
539
+ if (!runName)
540
+ return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
541
+ const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
542
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
543
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, async () => client.task(taskId).start(input, startOptions));
544
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
545
+ await this.#childRunTracker.update(runName, finishedRun);
546
+ return finishedRun;
547
+ }
548
+ /**
549
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
550
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
551
+ *
552
+ * ```js
553
+ * await Actor.childRuns['my-child'].waitForFinish();
554
+ * ```
555
+ *
556
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
557
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
558
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
559
+ */
560
+ get childRuns() {
561
+ this.ensureActorInit('childRuns');
562
+ return this.#childRunTracker.getRunClients(this.apifyClient);
517
563
  }
518
564
  /**
519
565
  * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -540,9 +586,13 @@ export class Actor {
540
586
  */
541
587
  async startTask(taskId, input, options = {}) {
542
588
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
543
- const { token, timeout: _timeout, ...rest } = options;
589
+ const { token, timeout: _timeout, runName, ...rest } = options;
544
590
  const client = token ? this.newClient({ token }) : this.apifyClient;
545
- return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
591
+ if (!runName)
592
+ return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
593
+ const startOptions = { ...rest, runTimeoutSecs };
594
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, async () => client.task(taskId).start(input, startOptions));
595
+ return run;
546
596
  }
547
597
  /**
548
598
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -872,10 +922,10 @@ export class Actor {
872
922
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
873
923
  *
874
924
  * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
875
- * `<inputKey>.json` file in the current working directory instead.
925
+ * `<inputKey>.json` file in the current working directory, then in the storage directory.
876
926
  *
877
927
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
878
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
928
+ * files exist in the working/storage directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
879
929
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
880
930
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
881
931
  *
@@ -900,11 +950,12 @@ export class Actor {
900
950
  const record = await store.getRecord(inputKey);
901
951
  const rawInput = record
902
952
  ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
903
- : await this.readInputFromWorkingDirectory(inputKey);
953
+ : ((await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory')) ??
954
+ (await this.readInputFromDirectory(inputKey, this.configuration.storageDir, 'storage directory')));
904
955
  if (rawInput == null) {
905
956
  const locations = [`the "${inputKey}" record of the default key-value store`];
906
957
  if (!this.configuration.isAtHome) {
907
- locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working directory`);
958
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or storage directory`);
908
959
  }
909
960
  throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
910
961
  }
@@ -929,14 +980,14 @@ export class Actor {
929
980
  return input;
930
981
  }
931
982
  /**
932
- * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the working directory, for local runs
983
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
933
984
  * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
934
985
  * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
935
986
  * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
936
987
  *
937
988
  * @returns `undefined` when running on the platform or when neither file exists.
938
989
  */
939
- async readInputFromWorkingDirectory(inputKey) {
990
+ async readInputFromDirectory(inputKey, directory, label) {
940
991
  if (this.configuration.isAtHome) {
941
992
  return undefined;
942
993
  }
@@ -946,20 +997,20 @@ export class Actor {
946
997
  ];
947
998
  const found = [];
948
999
  for (const candidate of candidates) {
949
- const path = join(process.cwd(), candidate.filename);
1000
+ const path = join(directory, candidate.filename);
950
1001
  const stats = await stat(path).catch(() => null);
951
1002
  if (stats?.isFile()) {
952
1003
  found.push({ ...candidate, path });
953
1004
  }
954
1005
  }
955
1006
  if (found.length > 1) {
956
- throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the working directory: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
1007
+ throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
957
1008
  }
958
1009
  if (found.length === 0) {
959
1010
  return undefined;
960
1011
  }
961
1012
  const [file] = found;
962
- return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the working directory`);
1013
+ return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
963
1014
  }
964
1015
  /**
965
1016
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -1416,6 +1467,21 @@ export class Actor {
1416
1467
  static async start(actorId, input, options = {}) {
1417
1468
  return Actor.getDefaultInstance().start(actorId, input, options);
1418
1469
  }
1470
+ /**
1471
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1472
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
1473
+ *
1474
+ * ```js
1475
+ * await Actor.childRuns['my-child'].waitForFinish();
1476
+ * ```
1477
+ *
1478
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
1479
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1480
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1481
+ */
1482
+ static get childRuns() {
1483
+ return Actor.getDefaultInstance().childRuns;
1484
+ }
1419
1485
  /**
1420
1486
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1421
1487
  *
package/dist/charging.js CHANGED
@@ -1,24 +1,7 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
1
  import { Dataset, KeyValueStore } from '@crawlee/core';
3
2
  import log from '@apify/log';
3
+ import { ReentrantAsyncLock } from './utils.js';
4
4
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
5
- /**
6
- * A FIFO mutex that a critical section may re-enter from a nested call — the charge lock is taken by
7
- * `Actor.pushData()` and again, one level down, by the dataset backend it pushes through.
8
- */
9
- class ReentrantAsyncLock {
10
- #tail = Promise.resolve();
11
- #held = new AsyncLocalStorage();
12
- async runExclusive(fn) {
13
- if (this.#held.getStore()) {
14
- return await fn();
15
- }
16
- const run = this.#tail.then(async () => this.#held.run(true, fn));
17
- // Keep the chain alive even when the critical section throws.
18
- this.#tail = run.catch(() => { });
19
- return await run;
20
- }
21
- }
22
5
  /**
23
6
  * Handles pay-per-event charging.
24
7
  */
@@ -0,0 +1,72 @@
1
+ import type { Run as ActorRun, RunClient, RunResurrectOptions } from 'apify-client';
2
+ import type { ApifyClient } from './index.js';
3
+ /**
4
+ * Status of a tracked child run. This copies the `ActorRun['status']` type,
5
+ * but adds `LOST` to mark a locally tracked run that the platform no longer returns.
6
+ *
7
+ * `LOST` runs can happen as a result of a manual removal or expiration.
8
+ */
9
+ export type ChildRunStatus = ActorRun['status'] | 'LOST';
10
+ export interface ChildRunInfo {
11
+ runId: string;
12
+ status: ChildRunStatus;
13
+ /** ISO 8601 timestamp. */
14
+ startedAt: string;
15
+ }
16
+ export interface TrackedChildRun extends ChildRunInfo {
17
+ /** Identifies the Actor / task and input the run was started with. */
18
+ checksum: string;
19
+ /** Earlier runs that were replaced under the same name, oldest first. */
20
+ history: ChildRunInfo[];
21
+ }
22
+ export interface ChildRunRequest {
23
+ type: 'actor' | 'task';
24
+ id: string;
25
+ input?: unknown;
26
+ }
27
+ export declare class ChildRunTracker {
28
+ private trackedRuns;
29
+ private loading?;
30
+ /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
31
+ private clients;
32
+ private lastWrite;
33
+ private locks;
34
+ /**
35
+ * Throws if the run tracked under `runName` was started for a different Actor / task or input,
36
+ * as it would otherwise be silently returned or resurrected in place of the requested one.
37
+ */
38
+ verifyRequest(runName: string, request: ChildRunRequest): Promise<void>;
39
+ /**
40
+ * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
41
+ * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
42
+ * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
43
+ * keeping the previous one in the history.
44
+ */
45
+ startOrResumeChildRun(client: ApifyClient, runName: string, request: ChildRunRequest, startOptions: RunResurrectOptions, start: () => Promise<ActorRun>): Promise<{
46
+ run: ActorRun;
47
+ resumed: boolean;
48
+ }>;
49
+ /**
50
+ * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
51
+ * history, with `replacedStatus` as its last known status.
52
+ */
53
+ track(runName: string, run: ActorRun, request: ChildRunRequest, replacedStatus: ChildRunStatus): Promise<void>;
54
+ /**
55
+ * Records the latest observed state of the run tracked under `runName`.
56
+ */
57
+ update(runName: string, run: ActorRun): Promise<void>;
58
+ /**
59
+ * Returns the tracked run and its history for `runName`, if there is one.
60
+ */
61
+ get(runName: string): Promise<TrackedChildRun>;
62
+ /**
63
+ * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
64
+ * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
65
+ */
66
+ getRunClients(defaultClient: ApifyClient): Record<string, RunClient>;
67
+ private persist;
68
+ /**
69
+ * Loads the tracked runs from the default key-value store, once.
70
+ */
71
+ load(): Promise<Record<string, TrackedChildRun>>;
72
+ }
@@ -0,0 +1,181 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { KeyValueStore, withDirectStorageAccess } from '@crawlee/core';
3
+ import { sleep } from '@crawlee/utils';
4
+ import { z } from 'zod';
5
+ import { ReentrantAsyncLock } from './utils.js';
6
+ const sortKeys = (value) => {
7
+ if (Array.isArray(value))
8
+ return value.map(sortKeys);
9
+ if (value === null || typeof value !== 'object')
10
+ return value;
11
+ return Object.fromEntries(Object.entries(value)
12
+ .sort(([a], [b]) => Number(a > b) - Number(a < b))
13
+ .map(([key, nested]) => [key, sortKeys(nested)]));
14
+ };
15
+ // Hashes the JSON form that `apify-client` sends (`Date` -> ISO string, `URL` -> href, functions -> source),
16
+ // not the objects' own keys.
17
+ const toSentJson = (value) => JSON.parse(JSON.stringify(value, (_key, nested) => (typeof nested === 'function' ? nested.toString() : nested)));
18
+ const checksumRequest = ({ type, id, input }) => createHash('sha256')
19
+ .update(JSON.stringify(sortKeys(toSentJson({ type, id, input }))))
20
+ .digest('hex');
21
+ const toInfo = (run) => ({
22
+ runId: run.id,
23
+ status: run.status,
24
+ startedAt: run.startedAt.toISOString(),
25
+ });
26
+ const CHILD_RUNS_KVS_KEY = '__ACTOR_CHILD_RUNS';
27
+ const childRunInfoSchema = z.object({ runId: z.string(), status: z.string(), startedAt: z.string() });
28
+ const trackedRunsSchema = z.record(z.string(), childRunInfoSchema.extend({ checksum: z.string(), history: z.array(childRunInfoSchema).default([]) }));
29
+ /** How many times a tracked run that the API reports as missing is looked up again before it counts as gone. */
30
+ const NOT_FOUND_RETRIES = 12;
31
+ const NOT_FOUND_RETRY_INTERVAL_MILLIS = 250;
32
+ /**
33
+ * Fetches a tracked run, retrying a 404 for a few seconds. A run started moments ago (e.g. by a concurrent call or
34
+ * right before a migration) may not be on every API replica yet, and treating it as gone would start a duplicate.
35
+ */
36
+ const getTrackedRun = async (runClient) => {
37
+ let run = await runClient.get();
38
+ for (let retry = 0; !run && retry < NOT_FOUND_RETRIES; retry++) {
39
+ await sleep(NOT_FOUND_RETRY_INTERVAL_MILLIS);
40
+ run = await runClient.get();
41
+ }
42
+ return run;
43
+ };
44
+ /** Statuses that shortly end as `ABORTED` / `TIMED-OUT`. */
45
+ const SETTLING_STATUSES = ['ABORTING', 'TIMING-OUT'];
46
+ const RESURRECTABLE_STATUSES = ['ABORTED', 'TIMED-OUT'];
47
+ const REUSABLE_STATUSES = ['READY', 'RUNNING', 'SUCCEEDED', ...RESURRECTABLE_STATUSES];
48
+ export class ChildRunTracker {
49
+ trackedRuns = {};
50
+ loading;
51
+ /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
52
+ clients = new Map();
53
+ lastWrite = Promise.resolve();
54
+ locks = new Map();
55
+ /**
56
+ * Throws if the run tracked under `runName` was started for a different Actor / task or input,
57
+ * as it would otherwise be silently returned or resurrected in place of the requested one.
58
+ */
59
+ async verifyRequest(runName, request) {
60
+ const tracked = await this.get(runName);
61
+ if (tracked && tracked.checksum !== checksumRequest(request)) {
62
+ throw new Error(`The run name "${runName}" was already used for a different Actor, task or input. Use a unique \`runName\` for each child run.`);
63
+ }
64
+ }
65
+ /**
66
+ * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
67
+ * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
68
+ * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
69
+ * keeping the previous one in the history.
70
+ */
71
+ async startOrResumeChildRun(client, runName, request, startOptions, start) {
72
+ if (!this.locks.has(runName)) {
73
+ this.locks.set(runName, new ReentrantAsyncLock());
74
+ }
75
+ return this.locks.get(runName).runExclusive(async () => {
76
+ const { build, memory, runTimeoutSecs, maxItems, maxTotalChargeUsd, restartOnError, timeoutSecs, signal } = startOptions;
77
+ const tracked = await this.get(runName);
78
+ let trackedRun = tracked ? await getTrackedRun(client.run(tracked.runId)) : undefined;
79
+ if (trackedRun && SETTLING_STATUSES.includes(trackedRun.status)) {
80
+ trackedRun = await client.run(trackedRun.id).waitForFinish({ timeoutSecs, signal });
81
+ }
82
+ if (trackedRun && REUSABLE_STATUSES.includes(trackedRun.status)) {
83
+ await this.verifyRequest(runName, request);
84
+ const run = RESURRECTABLE_STATUSES.includes(trackedRun.status)
85
+ ? await client.run(trackedRun.id).resurrect({
86
+ build,
87
+ memory,
88
+ runTimeoutSecs,
89
+ maxItems,
90
+ maxTotalChargeUsd,
91
+ restartOnError,
92
+ timeoutSecs,
93
+ signal,
94
+ })
95
+ : trackedRun;
96
+ await this.update(runName, run);
97
+ this.clients.set(runName, client);
98
+ return { run, resumed: true };
99
+ }
100
+ const run = await start();
101
+ await this.track(runName, run, request, trackedRun?.status ?? 'LOST');
102
+ this.clients.set(runName, client);
103
+ return { run, resumed: false };
104
+ });
105
+ }
106
+ /**
107
+ * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
108
+ * history, with `replacedStatus` as its last known status.
109
+ */
110
+ async track(runName, run, request, replacedStatus) {
111
+ const trackedRuns = await this.load();
112
+ const previous = trackedRuns[runName];
113
+ trackedRuns[runName] = {
114
+ ...toInfo(run),
115
+ checksum: checksumRequest(request),
116
+ history: previous
117
+ ? [
118
+ ...previous.history,
119
+ { runId: previous.runId, startedAt: previous.startedAt, status: replacedStatus },
120
+ ]
121
+ : [],
122
+ };
123
+ await this.persist();
124
+ }
125
+ /**
126
+ * Records the latest observed state of the run tracked under `runName`.
127
+ */
128
+ async update(runName, run) {
129
+ const trackedRuns = await this.load();
130
+ const tracked = trackedRuns[runName];
131
+ if (tracked?.runId !== run.id || tracked.status === run.status)
132
+ return;
133
+ tracked.status = run.status;
134
+ await this.persist();
135
+ }
136
+ /**
137
+ * Returns the tracked run and its history for `runName`, if there is one.
138
+ */
139
+ async get(runName) {
140
+ const trackedRuns = await this.load();
141
+ return trackedRuns[runName];
142
+ }
143
+ /**
144
+ * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
145
+ * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
146
+ */
147
+ getRunClients(defaultClient) {
148
+ return Object.fromEntries(Object.entries(this.trackedRuns).map(([runName, { runId }]) => [
149
+ runName,
150
+ (this.clients.get(runName) ?? defaultClient).run(runId),
151
+ ]));
152
+ }
153
+ async persist() {
154
+ const write = this.lastWrite.then(async () => withDirectStorageAccess(async () => {
155
+ const defaultStore = await KeyValueStore.open();
156
+ await defaultStore.setValue(CHILD_RUNS_KVS_KEY, this.trackedRuns);
157
+ }));
158
+ this.lastWrite = write.catch(() => { });
159
+ await write;
160
+ }
161
+ /**
162
+ * Loads the tracked runs from the default key-value store, once.
163
+ */
164
+ async load() {
165
+ this.loading ??= KeyValueStore.open()
166
+ .then(async (defaultStore) => defaultStore.getValue(CHILD_RUNS_KVS_KEY))
167
+ .then((storedRuns) => {
168
+ const parsed = trackedRunsSchema.safeParse(storedRuns ?? {});
169
+ if (!parsed.success) {
170
+ throw new Error(`The child runs stored under the "${CHILD_RUNS_KVS_KEY}" key in the default key-value store are malformed.`, { cause: parsed.error });
171
+ }
172
+ this.trackedRuns = parsed.data;
173
+ })
174
+ .catch((error) => {
175
+ this.loading = undefined;
176
+ throw error;
177
+ });
178
+ await this.loading;
179
+ return this.trackedRuns;
180
+ }
181
+ }
package/dist/utils.d.ts CHANGED
@@ -41,3 +41,10 @@ export declare function checkCrawleeVersion(): void;
41
41
  * @ignore
42
42
  */
43
43
  export declare function printOutdatedSdkWarning(): void;
44
+ /**
45
+ * A FIFO mutex that a critical section may re-enter from a nested call without deadlocking.
46
+ */
47
+ export declare class ReentrantAsyncLock {
48
+ #private;
49
+ runExclusive<T>(fn: () => Promise<T>): Promise<T>;
50
+ }
package/dist/utils.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { existsSync, readFileSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import { type } from 'node:os';
@@ -120,3 +121,19 @@ export function printOutdatedSdkWarning() {
120
121
  log.warning(`You are using an outdated version (${apifyPkgJson.version}) of Apify SDK. We recommend you to update to the latest version (${latestApifyVersion}).
121
122
  Read more about Apify SDK versioning at: https://help.apify.com/en/articles/3184510-updates-and-versioning-of-apify-sdk`);
122
123
  }
124
+ /**
125
+ * A FIFO mutex that a critical section may re-enter from a nested call without deadlocking.
126
+ */
127
+ export class ReentrantAsyncLock {
128
+ #tail = Promise.resolve();
129
+ #held = new AsyncLocalStorage();
130
+ async runExclusive(fn) {
131
+ if (this.#held.getStore()) {
132
+ return await fn();
133
+ }
134
+ const run = this.#tail.then(async () => this.#held.run(true, fn));
135
+ // Keep the chain alive even when the critical section throws.
136
+ this.#tail = run.catch(() => { });
137
+ return await run;
138
+ }
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.63",
3
+ "version": "4.0.0-beta.65",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"