apify 4.0.0-beta.145 → 4.0.0-beta.147

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
@@ -47,6 +47,27 @@ export interface InitOptions {
47
47
  * @default 0
48
48
  */
49
49
  gracefulShutdownDelayMillis?: number;
50
+ /**
51
+ * Whether to record the child runs started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` and
52
+ * `Actor.callTask()` in the default key-value store. `Actor.childRuns()`, `abortWithParent` and
53
+ * `maxConcurrentChildRuns` need it.
54
+ *
55
+ * Tracking costs resources, so it may be worth turning off for a run that starts many child runs.
56
+ * @default true
57
+ */
58
+ trackChildRuns?: boolean;
59
+ /**
60
+ * Whether to mute the warning logged once this run records more than 50 child runs.
61
+ * @default false
62
+ */
63
+ disableExcessiveChildRunWarning?: boolean;
64
+ /**
65
+ * Maximum number of child runs that can be active (`READY`, `RUNNING`, `ABORTING` or `TIMING-OUT`) at once. A call
66
+ * of `Actor.start()`, `Actor.call()`, `Actor.startTask()` or `Actor.callTask()` that would start one more waits
67
+ * until another one finishes, and throws instead once this run is being aborted or is exiting. A finished child
68
+ * run that is resurrected, e.g. with `resurrect()` on its client from `Actor.childRuns()`, is not counted.
69
+ */
70
+ maxConcurrentChildRuns?: number;
50
71
  }
51
72
  /**
52
73
  * Options accepted by the {@link Actor} constructor. Either pass field-level
@@ -101,27 +122,25 @@ export interface Timeout {
101
122
  }
102
123
  export interface ChildRunOptions {
103
124
  /**
104
- * Local name for the child run, unique across all Actors and tasks started by this run.
105
- *
106
- * If a `READY`, `RUNNING` or `SUCCEEDED` run is already tracked under this name, it is returned instead of
107
- * starting a new one, including after a migration or resurrection of this run. A run that was aborted or timed out
108
- * is resurrected with the given options, once it finishes aborting or timing out. A run that failed is replaced
109
- * by a new one. Reusing the name for a different Actor, task or input throws, unless the tracked run is replaced.
110
- */
111
- runName?: string;
112
- /**
113
- * Gracefully abort the child run when this run is gracefully aborted. Requires `runName`.
125
+ * Gracefully abort the child run when this run is gracefully aborted, or when it exits through `Actor.exit()`,
126
+ * `Actor.fail()` or `Actor.main()`, whatever the exit code. A hard abort, timeout or crash of this run leaves the
127
+ * child run running, and so does ending this run without `Actor.exit()`.
114
128
  *
115
- * The latest call under the same `runName` sets the value. Once this run is being aborted, a call with this option
116
- * throws instead of starting, resurrecting or returning a run. A hard abort, timeout or crash of this run leaves
117
- * the child run running.
118
- *
119
- * A run started with a custom `token` is aborted with that token, except for a run started before a migration or
120
- * resurrection of this run, which is aborted with the default client.
129
+ * Once this run is being aborted or is exiting, a call with this option throws instead of starting a run. A
130
+ * finished child run that is resurrected, e.g. with `resurrect()` on its client from `Actor.childRuns()`, keeps its
131
+ * finished status in the record and is not aborted. It cannot be combined with `token`, since the token is not
132
+ * stored.
121
133
  * @default false
122
134
  */
123
135
  abortWithParent?: boolean;
124
136
  }
137
+ /**
138
+ * Client for a child run, as returned by {@link Actor.childRuns}.
139
+ */
140
+ export type ChildRunClient = RunClient & {
141
+ /** Whether the run is aborted together with this run, as recorded at the time of the call. */
142
+ readonly abortWithParent: boolean;
143
+ };
125
144
  export interface CallOptions extends Omit<ActorCallOptions, 'runTimeoutSecs' | 'maxItems'>, Token, Timeout, ChildRunOptions {
126
145
  }
127
146
  export interface StartOptions extends Omit<ActorStartOptions, 'waitForFinish' | 'runTimeoutSecs' | 'maxItems'>, Token, Timeout, ChildRunOptions {
@@ -447,18 +466,20 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
447
466
  */
448
467
  callTask(taskId: string, input?: Dictionary, options?: CallTaskOptions): Promise<ClientActorRun>;
449
468
  /**
450
- * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
451
- * before a migration or resurrection of this run. Each client points to the current run under its name.
469
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
470
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
471
+ * migration, reboot or resurrection of this run.
452
472
  *
453
473
  * ```js
454
- * await Actor.childRuns['my-child'].waitForFinish();
474
+ * const childRuns = await Actor.childRuns();
475
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
455
476
  * ```
456
477
  *
457
- * A run started with a custom `token` uses that token, except for a run started before a migration or
458
- * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
459
- * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
478
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
479
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
480
+ * resurrection of this run, which uses the default client.
460
481
  */
461
- get childRuns(): Record<string, RunClient>;
482
+ childRuns(): Promise<ChildRunClient[]>;
462
483
  /**
463
484
  * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
464
485
  * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
@@ -1053,18 +1074,20 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1053
1074
  */
1054
1075
  static start(actorId: string, input?: Dictionary, options?: StartOptions): Promise<ClientActorRun>;
1055
1076
  /**
1056
- * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1057
- * before a migration or resurrection of this run. Each client points to the current run under its name.
1077
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
1078
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
1079
+ * migration, reboot or resurrection of this run.
1058
1080
  *
1059
1081
  * ```js
1060
- * await Actor.childRuns['my-child'].waitForFinish();
1082
+ * const childRuns = await Actor.childRuns();
1083
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
1061
1084
  * ```
1062
1085
  *
1063
- * A run started with a custom `token` uses that token, except for a run started before a migration or
1064
- * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1065
- * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
1086
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
1087
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
1088
+ * resurrection of this run, which uses the default client.
1066
1089
  */
1067
- static get childRuns(): Record<string, RunClient>;
1090
+ static childRuns(): Promise<ChildRunClient[]>;
1068
1091
  /**
1069
1092
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1070
1093
  *
package/dist/actor.js CHANGED
@@ -98,8 +98,8 @@ export class Actor {
98
98
  #chargingManager;
99
99
  #runPromise;
100
100
  #actorPromise;
101
- /** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
102
- #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
101
+ /** Aborts the child runs started with `abortWithParent` on the `aborting` event, or in `Actor.exit()`. */
102
+ #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent();
103
103
  /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
104
104
  #requestQueueAccess = 'single';
105
105
  /** Lazily built by the `#storageBackend` getter. */
@@ -133,7 +133,7 @@ export class Actor {
133
133
  [ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
134
134
  });
135
135
  this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
136
- this.#childRunTracker = new ChildRunTracker();
136
+ this.#childRunTracker = new ChildRunTracker(this.apifyClient);
137
137
  }
138
138
  /**
139
139
  * Runs the main user function that performs the job of the Actor
@@ -228,6 +228,7 @@ export class Actor {
228
228
  'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
229
229
  ].join('\n'));
230
230
  }
231
+ this.#childRunTracker.configure(options);
231
232
  this.initialized = true;
232
233
  checkCrawleeVersion();
233
234
  log.info('System info', getSystemInfo());
@@ -335,6 +336,7 @@ export class Actor {
335
336
  if (this.#gracefulShutdownHandlers.migrating) {
336
337
  this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
337
338
  }
339
+ await this.#abortChildRunsWithParent();
338
340
  // Writes the charged event counts one last time, so that a resurrected run continues from them.
339
341
  await this.#chargingManager.teardown();
340
342
  // Close the event manager and emit the final PERSIST_STATE event
@@ -384,6 +386,7 @@ export class Actor {
384
386
  // Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
385
387
  // When process.exit() actually terminates the process, this line is never reached - which is fine.
386
388
  this.#isExiting = false;
389
+ this.#childRunTracker.resetAbort();
387
390
  if (!options.exit) {
388
391
  return;
389
392
  }
@@ -443,21 +446,16 @@ export class Actor {
443
446
  */
444
447
  async call(actorId, input, options = {}) {
445
448
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
446
- const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
449
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
447
450
  const client = token ? this.newClient({ token }) : this.apifyClient;
448
- if (abortWithParent && !runName)
449
- throw new Error('`abortWithParent` requires `runName`.');
450
- if (!runName)
451
- return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
452
- const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
453
- const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
454
- const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
455
- // The earlier part of a resumed run's log was already redirected before the migration.
456
- const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
451
+ // Like `ActorClient.call()`, but the run is recorded before it is waited for.
452
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
453
+ const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
454
+ const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, signal });
457
455
  streamedLog?.start();
458
456
  try {
459
457
  const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
460
- await this.#childRunTracker.update(runName, finishedRun);
458
+ await this.#childRunTracker.update(finishedRun);
461
459
  return finishedRun;
462
460
  }
463
461
  finally {
@@ -489,15 +487,9 @@ export class Actor {
489
487
  */
490
488
  async start(actorId, input, options = {}) {
491
489
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
492
- const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
490
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
493
491
  const client = token ? this.newClient({ token }) : this.apifyClient;
494
- if (abortWithParent && !runName)
495
- throw new Error('`abortWithParent` requires `runName`.');
496
- if (!runName)
497
- return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
498
- const startOptions = { ...rest, runTimeoutSecs };
499
- const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
500
- return run;
492
+ return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...rest, runTimeoutSecs }));
501
493
  }
502
494
  /**
503
495
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -575,34 +567,32 @@ export class Actor {
575
567
  */
576
568
  async callTask(taskId, input, options = {}) {
577
569
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
578
- const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
570
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
579
571
  const client = token ? this.newClient({ token }) : this.apifyClient;
580
- if (abortWithParent && !runName)
581
- throw new Error('`abortWithParent` requires `runName`.');
582
- if (!runName)
583
- return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
584
- const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
585
- const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
586
- const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
572
+ // Like `TaskClient.call()`, but the run is recorded before it is waited for.
573
+ const { waitSecs, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
574
+ const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
587
575
  const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
588
- await this.#childRunTracker.update(runName, finishedRun);
576
+ await this.#childRunTracker.update(finishedRun);
589
577
  return finishedRun;
590
578
  }
591
579
  /**
592
- * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
593
- * before a migration or resurrection of this run. Each client points to the current run under its name.
580
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
581
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
582
+ * migration, reboot or resurrection of this run.
594
583
  *
595
584
  * ```js
596
- * await Actor.childRuns['my-child'].waitForFinish();
585
+ * const childRuns = await Actor.childRuns();
586
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
597
587
  * ```
598
588
  *
599
- * A run started with a custom `token` uses that token, except for a run started before a migration or
600
- * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
601
- * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
589
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
590
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
591
+ * resurrection of this run, which uses the default client.
602
592
  */
603
- get childRuns() {
593
+ async childRuns() {
604
594
  this.ensureActorInit('childRuns');
605
- return this.#childRunTracker.getRunClients(this.apifyClient);
595
+ return this.#childRunTracker.getRunClients();
606
596
  }
607
597
  /**
608
598
  * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -629,15 +619,9 @@ export class Actor {
629
619
  */
630
620
  async startTask(taskId, input, options = {}) {
631
621
  const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
632
- const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
622
+ const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
633
623
  const client = token ? this.newClient({ token }) : this.apifyClient;
634
- if (abortWithParent && !runName)
635
- throw new Error('`abortWithParent` requires `runName`.');
636
- if (!runName)
637
- return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
638
- const startOptions = { ...rest, runTimeoutSecs };
639
- const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
640
- return run;
624
+ return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...rest, runTimeoutSecs }));
641
625
  }
642
626
  /**
643
627
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -659,6 +643,8 @@ export class Actor {
659
643
  }
660
644
  const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
661
645
  const runId = this.configuration.actorRunId;
646
+ // The target Actor would not know about a child run whose start is not recorded yet.
647
+ await this.#childRunTracker.waitForStartsInFlight();
662
648
  await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
663
649
  // Wait some time for container to be stopped.
664
650
  await sleep(customAfterSleepMillis);
@@ -703,6 +689,8 @@ export class Actor {
703
689
  ]);
704
690
  }, timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
705
691
  const runId = this.configuration.actorRunId;
692
+ // The new container would not know about a child run whose start is not recorded yet.
693
+ await this.#childRunTracker.waitForStartsInFlight();
706
694
  try {
707
695
  await this.apifyClient.run(runId).reboot();
708
696
  }
@@ -1508,19 +1496,21 @@ export class Actor {
1508
1496
  return Actor.getDefaultInstance().start(actorId, input, options);
1509
1497
  }
1510
1498
  /**
1511
- * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1512
- * before a migration or resurrection of this run. Each client points to the current run under its name.
1499
+ * Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
1500
+ * `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
1501
+ * migration, reboot or resurrection of this run.
1513
1502
  *
1514
1503
  * ```js
1515
- * await Actor.childRuns['my-child'].waitForFinish();
1504
+ * const childRuns = await Actor.childRuns();
1505
+ * await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
1516
1506
  * ```
1517
1507
  *
1518
- * A run started with a custom `token` uses that token, except for a run started before a migration or
1519
- * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1520
- * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
1508
+ * The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
1509
+ * started with a custom `token` uses that token, except for a run started before a migration, reboot or
1510
+ * resurrection of this run, which uses the default client.
1521
1511
  */
1522
- static get childRuns() {
1523
- return Actor.getDefaultInstance().childRuns;
1512
+ static async childRuns() {
1513
+ return Actor.getDefaultInstance().childRuns();
1524
1514
  }
1525
1515
  /**
1526
1516
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -1,88 +1,110 @@
1
- import type { Run as ActorRun, RunClient, RunResurrectOptions } from 'apify-client';
1
+ import type { Run as ActorRun } from 'apify-client';
2
+ import type { ChildRunClient, InitOptions } from './actor.js';
2
3
  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
- /** Whether the run is aborted when this run is gracefully aborted. */
22
- abortWithParent: boolean;
23
- }
24
- export interface ChildRunRequest {
25
- type: 'actor' | 'task';
26
- id: string;
27
- input?: unknown;
28
- }
29
4
  /**
30
5
  * How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
31
6
  * run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
32
7
  */
33
8
  export declare const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10000;
9
+ /** How long `waitForStartsInFlight()` waits for the started runs to be recorded. */
10
+ export declare const STARTS_IN_FLIGHT_TIMEOUT_MILLIS = 10000;
11
+ /** Number of recorded runs above which a warning about the size of the registry is logged, once per process. */
12
+ export declare const EXCESSIVE_CHILD_RUNS_THRESHOLD = 50;
13
+ /**
14
+ * Records every child run of this run in the default key-value store, so that it can be listed, aborted together with
15
+ * this run and counted against the concurrency limit, also after a migration, reboot or resurrection of this run.
16
+ */
34
17
  export declare class ChildRunTracker {
35
- private trackedRuns;
18
+ private readonly defaultClient;
19
+ /** Set by `configure()` in `Actor.init()`. Child runs started before it are not tracked. */
20
+ private enabled?;
21
+ private warnOnExcessiveRuns;
22
+ private warnedExcessiveRuns;
23
+ private maxConcurrentRuns?;
24
+ private registry;
36
25
  private loading?;
37
- /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
38
- private clients;
39
26
  private lastWrite;
40
- private locks;
41
- /** Set once this run is being gracefully aborted, after which no run with `abortWithParent` is started. */
42
- private isParentAborting;
27
+ /** A write that is queued and not started yet, which the changes made in the meantime join. */
28
+ private queuedWrite?;
29
+ /** Client each run was started with in this process, if it is not the default one. */
30
+ private clients;
31
+ /** When the status of each record was last returned by the API, in this process. */
32
+ private observedAt;
33
+ /** Starts whose runs are not recorded yet. */
34
+ private startsInFlight;
35
+ /** Start requests that have not returned yet, which the concurrency limit counts. */
36
+ private pendingStartRequests;
37
+ private admissionLock;
38
+ /** Set once this run starts aborting its child runs, after which no run with `abortWithParent` is started. */
39
+ private aborting?;
40
+ constructor(defaultClient: ApifyClient);
43
41
  /**
44
- * Throws if the run tracked under `runName` was started for a different Actor / task or input,
45
- * as it would otherwise be silently returned or resurrected in place of the requested one.
42
+ * Applies the options of `Actor.init()`, before the registry is loaded.
46
43
  */
47
- verifyRequest(runName: string, request: ChildRunRequest): Promise<void>;
44
+ configure({ trackChildRuns, disableExcessiveChildRunWarning, maxConcurrentChildRuns, }: Pick<InitOptions, 'trackChildRuns' | 'disableExcessiveChildRunWarning' | 'maxConcurrentChildRuns'>): void;
48
45
  /**
49
- * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
50
- * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
51
- * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
52
- * keeping the previous one in the history. `abortWithParent` replaces the value tracked under `runName`.
46
+ * Starts a child run using `start`, and records it before returning it. Waits for a slot first, if the concurrency
47
+ * limit is set.
53
48
  */
54
- startOrResumeChildRun(client: ApifyClient, runName: string, request: ChildRunRequest, startOptions: RunResurrectOptions, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<{
55
- run: ActorRun;
56
- resumed: boolean;
57
- }>;
49
+ startChildRun(client: ApifyClient, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<ActorRun>;
58
50
  /**
59
- * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
60
- * history, with `replacedStatus` as its last known status.
51
+ * Records the latest observed status of a child run.
61
52
  */
62
- track(runName: string, run: ActorRun, request: ChildRunRequest, replacedStatus: ChildRunStatus, abortWithParent: boolean): Promise<void>;
53
+ update(run: ActorRun): Promise<void>;
63
54
  /**
64
- * Records the latest observed state of the run tracked under `runName`.
55
+ * Returns a client for every recorded run, in recording order. The client is the one the run was started with in
56
+ * this process, or the default one (e.g. for a run recorded before a migration).
65
57
  */
66
- update(runName: string, run: ActorRun): Promise<void>;
58
+ getRunClients(): Promise<ChildRunClient[]>;
67
59
  /**
68
- * Returns the tracked run and its history for `runName`, if there is one.
60
+ * Gracefully aborts each recorded run with `abortWithParent` and an active recorded status, once, and makes any
61
+ * later start with `abortWithParent` throw. The starts in flight are waited for, so the runs they start are
62
+ * aborted too. Resolves after {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in
63
+ * progress to go on.
69
64
  */
70
- get(runName: string): Promise<TrackedChildRun>;
65
+ abortRunsWithParent(): Promise<void>;
71
66
  /**
72
- * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
73
- * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
67
+ * Lets runs with `abortWithParent` start again, and makes the next exit abort them, after `Actor.exit()` that did
68
+ * not end the process.
74
69
  */
75
- getRunClients(defaultClient: ApifyClient): Record<string, RunClient>;
70
+ resetAbort(): void;
76
71
  /**
77
- * Gracefully aborts the current run under each name tracked with `abortWithParent`, and makes any later start with
78
- * `abortWithParent` throw. A start in flight is waited for, so the run it starts is aborted too. Resolves after
79
- * {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in progress to go on.
72
+ * Waits for the starts in flight to be recorded, for {@link STARTS_IN_FLIGHT_TIMEOUT_MILLIS} at most.
80
73
  */
81
- abortRunsWithParent(defaultClient: ApifyClient): Promise<void>;
82
- private getLock;
83
- private persist;
74
+ waitForStartsInFlight(): Promise<void>;
84
75
  /**
85
- * Loads the tracked runs from the default key-value store, once.
76
+ * Loads the registry from the default key-value store, once.
86
77
  */
87
- load(): Promise<Record<string, TrackedChildRun>>;
78
+ load(): Promise<{
79
+ [x: string]: unknown;
80
+ runs: Record<string, {
81
+ [x: string]: unknown;
82
+ runId: string;
83
+ status: string;
84
+ abortWithParent: boolean;
85
+ }>;
86
+ }>;
87
+ private abortMarkedRuns;
88
+ /**
89
+ * Waits while the active runs and the pending start requests are at the concurrency limit. Throws instead of
90
+ * waiting once this run is being aborted or is exiting.
91
+ */
92
+ private waitForSlot;
93
+ /**
94
+ * Counts the recorded runs with an active status. A status older than {@link STATUS_MAX_AGE_MILLIS}, or recorded
95
+ * by an earlier process, is fetched from the API first.
96
+ */
97
+ private countActiveRuns;
98
+ private clientFor;
99
+ /**
100
+ * Records `record` under `key`. Its status must be one just returned by the API.
101
+ */
102
+ private record;
103
+ /**
104
+ * Writes the registry once the write in progress finishes. The changes made until then are written together. A
105
+ * failed write is logged, not thrown, since the run is already started, and the next write saves the change too.
106
+ */
107
+ private persist;
108
+ private warnIfExcessive;
109
+ private assertEnabled;
88
110
  }
@@ -1,239 +1,333 @@
1
- import { createHash } from 'node:crypto';
1
+ import { isDeepStrictEqual } from 'node:util';
2
2
  import { KeyValueStore, withDirectStorageAccess } from '@crawlee/core';
3
- import { sleep } from '@crawlee/utils';
4
- import { NotFoundError } from 'apify-client';
3
+ import { ApifyApiError, NotFoundError } from 'apify-client';
5
4
  import { z } from 'zod';
5
+ import { ACTOR_JOB_STATUSES } from '@apify/consts';
6
6
  import log from '@apify/log';
7
7
  import { addTimeoutToPromise } from '@apify/timeout';
8
8
  import { ReentrantAsyncLock } from './utils.js';
9
- const sortKeys = (value) => {
10
- if (Array.isArray(value))
11
- return value.map(sortKeys);
12
- if (value === null || typeof value !== 'object')
13
- return value;
14
- return Object.fromEntries(Object.entries(value)
15
- .sort(([a], [b]) => Number(a > b) - Number(a < b))
16
- .map(([key, nested]) => [key, sortKeys(nested)]));
17
- };
18
- // Hashes the JSON form that `apify-client` sends (`Date` -> ISO string, `URL` -> href, functions -> source),
19
- // not the objects' own keys.
20
- const toSentJson = (value) => JSON.parse(JSON.stringify(value, (_key, nested) => (typeof nested === 'function' ? nested.toString() : nested)));
21
- const checksumRequest = ({ type, id, input }) => createHash('sha256')
22
- .update(JSON.stringify(sortKeys(toSentJson({ type, id, input }))))
23
- .digest('hex');
24
- const toInfo = (run) => ({
25
- runId: run.id,
26
- status: run.status,
27
- startedAt: run.startedAt.toISOString(),
28
- });
29
9
  const CHILD_RUNS_KVS_KEY = 'APIFY_ACTOR_CHILD_RUNS';
30
- const childRunInfoSchema = z.object({ runId: z.string(), status: z.string(), startedAt: z.string() });
31
- const trackedRunsSchema = z.record(z.string(), childRunInfoSchema.extend({
32
- checksum: z.string(),
33
- history: z.array(childRunInfoSchema).default([]),
34
- abortWithParent: z.boolean().default(false),
35
- }));
36
- /** How many times a tracked run that the API reports as missing is looked up again before it counts as gone. */
37
- const NOT_FOUND_RETRIES = 12;
38
- const NOT_FOUND_RETRY_INTERVAL_MILLIS = 250;
39
- /**
40
- * Fetches a tracked run, retrying a 404 for a few seconds. A run started moments ago (e.g. by a concurrent call or
41
- * right before a migration) may not be on every API replica yet, and treating it as gone would start a duplicate.
42
- */
43
- const getTrackedRun = async (runClient) => {
44
- let run = await runClient.get();
45
- for (let retry = 0; !run && retry < NOT_FOUND_RETRIES; retry++) {
46
- await sleep(NOT_FOUND_RETRY_INTERVAL_MILLIS);
47
- run = await runClient.get();
48
- }
49
- return run;
50
- };
51
- /** Statuses that shortly end as `ABORTED` / `TIMED-OUT`. */
52
- const SETTLING_STATUSES = ['ABORTING', 'TIMING-OUT'];
53
- const RESURRECTABLE_STATUSES = ['ABORTED', 'TIMED-OUT'];
54
- const REUSABLE_STATUSES = ['READY', 'RUNNING', 'SUCCEEDED', ...RESURRECTABLE_STATUSES];
55
- const ABORTED_STATUSES = ['ABORTING', 'ABORTED'];
10
+ const RUN_KEY_PREFIX = 'run:';
11
+ // Members this SDK does not know, e.g. written by a newer SDK before a metamorph, are kept.
12
+ const registrySchema = z.looseObject({
13
+ runs: z.record(z.string(), z.looseObject({
14
+ runId: z.string(),
15
+ /** Last status observed by this run. It can be out of date. */
16
+ status: z.string(),
17
+ abortWithParent: z.boolean(),
18
+ })),
19
+ });
20
+ const { READY, RUNNING, ABORTING, ABORTED, TIMING_OUT } = ACTOR_JOB_STATUSES;
21
+ const ACTIVE_STATUSES = [READY, RUNNING, ABORTING, TIMING_OUT];
22
+ const ABORTED_STATUSES = [ABORTING, ABORTED];
56
23
  /**
57
24
  * How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
58
25
  * run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
59
26
  */
60
27
  export const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10_000;
28
+ /** How long `waitForStartsInFlight()` waits for the started runs to be recorded. */
29
+ export const STARTS_IN_FLIGHT_TIMEOUT_MILLIS = 10_000;
30
+ /** Number of recorded runs above which a warning about the size of the registry is logged, once per process. */
31
+ export const EXCESSIVE_CHILD_RUNS_THRESHOLD = 50;
32
+ /** How old a recorded active status can be before the concurrency limit fetches the run again. */
33
+ const STATUS_MAX_AGE_MILLIS = 10_000;
34
+ /** How often a start waiting for a concurrency slot counts the active runs again. */
35
+ const CONCURRENCY_POLL_INTERVAL_MILLIS = 1_000;
36
+ /**
37
+ * Records every child run of this run in the default key-value store, so that it can be listed, aborted together with
38
+ * this run and counted against the concurrency limit, also after a migration, reboot or resurrection of this run.
39
+ */
61
40
  export class ChildRunTracker {
62
- trackedRuns = {};
41
+ defaultClient;
42
+ /** Set by `configure()` in `Actor.init()`. Child runs started before it are not tracked. */
43
+ enabled;
44
+ warnOnExcessiveRuns = true;
45
+ warnedExcessiveRuns = false;
46
+ maxConcurrentRuns;
47
+ registry = { runs: {} };
63
48
  loading;
64
- /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
65
- clients = new Map();
66
49
  lastWrite = Promise.resolve();
67
- locks = new Map();
68
- /** Set once this run is being gracefully aborted, after which no run with `abortWithParent` is started. */
69
- isParentAborting = false;
50
+ /** A write that is queued and not started yet, which the changes made in the meantime join. */
51
+ queuedWrite;
52
+ /** Client each run was started with in this process, if it is not the default one. */
53
+ clients = new Map();
54
+ /** When the status of each record was last returned by the API, in this process. */
55
+ observedAt = new Map();
56
+ /** Starts whose runs are not recorded yet. */
57
+ startsInFlight = new Set();
58
+ /** Start requests that have not returned yet, which the concurrency limit counts. */
59
+ pendingStartRequests = 0;
60
+ admissionLock = new ReentrantAsyncLock();
61
+ /** Set once this run starts aborting its child runs, after which no run with `abortWithParent` is started. */
62
+ aborting;
63
+ constructor(defaultClient) {
64
+ this.defaultClient = defaultClient;
65
+ }
70
66
  /**
71
- * Throws if the run tracked under `runName` was started for a different Actor / task or input,
72
- * as it would otherwise be silently returned or resurrected in place of the requested one.
67
+ * Applies the options of `Actor.init()`, before the registry is loaded.
73
68
  */
74
- async verifyRequest(runName, request) {
75
- const tracked = await this.get(runName);
76
- if (tracked && tracked.checksum !== checksumRequest(request)) {
77
- 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.`);
69
+ configure({ trackChildRuns = true, disableExcessiveChildRunWarning = false, maxConcurrentChildRuns, }) {
70
+ if (maxConcurrentChildRuns != null) {
71
+ if (!Number.isInteger(maxConcurrentChildRuns) || maxConcurrentChildRuns < 1) {
72
+ throw new Error('`maxConcurrentChildRuns` must be a positive integer.');
73
+ }
74
+ if (!trackChildRuns) {
75
+ throw new Error('`maxConcurrentChildRuns` requires child run tracking, which is turned off with `trackChildRuns: false`.');
76
+ }
78
77
  }
78
+ this.enabled = trackChildRuns;
79
+ this.warnOnExcessiveRuns = !disableExcessiveChildRunWarning;
80
+ this.maxConcurrentRuns = maxConcurrentChildRuns ?? undefined;
79
81
  }
80
82
  /**
81
- * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
82
- * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
83
- * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
84
- * keeping the previous one in the history. `abortWithParent` replaces the value tracked under `runName`.
83
+ * Starts a child run using `start`, and records it before returning it. Waits for a slot first, if the concurrency
84
+ * limit is set.
85
85
  */
86
- async startOrResumeChildRun(client, runName, request, startOptions, abortWithParent, start) {
87
- return this.getLock(runName).runExclusive(async () => {
88
- if (abortWithParent && this.isParentAborting) {
89
- throw new Error(`Child run "${runName}" with \`abortWithParent\` was not started, because this run is being aborted.`);
90
- }
91
- const { build, memory, runTimeoutSecs, maxItems, maxTotalChargeUsd, restartOnError, timeoutSecs, signal } = startOptions;
92
- const tracked = await this.get(runName);
93
- let trackedRun = tracked ? await getTrackedRun(client.run(tracked.runId)) : undefined;
94
- if (trackedRun && SETTLING_STATUSES.includes(trackedRun.status)) {
95
- trackedRun = await client.run(trackedRun.id).waitForFinish({ timeoutSecs, signal });
86
+ async startChildRun(client, abortWithParent, start) {
87
+ if (abortWithParent)
88
+ this.assertEnabled('`abortWithParent`');
89
+ // A later process would abort the run with the default client.
90
+ if (abortWithParent && client !== this.defaultClient) {
91
+ throw new Error('`abortWithParent` cannot be combined with `token`, since the token is not stored.');
92
+ }
93
+ if (!this.enabled)
94
+ return start();
95
+ await this.load();
96
+ // One start at a time is admitted, so that it is counted before the next one checks the limit.
97
+ const { starting } = await this.admissionLock.runExclusive(async () => {
98
+ await this.waitForSlot();
99
+ if (abortWithParent && this.aborting) {
100
+ throw new Error('A child run with `abortWithParent` was not started, because this run is being aborted or is exiting.');
96
101
  }
97
- if (trackedRun && REUSABLE_STATUSES.includes(trackedRun.status)) {
98
- await this.verifyRequest(runName, request);
99
- const run = RESURRECTABLE_STATUSES.includes(trackedRun.status)
100
- ? await client.run(trackedRun.id).resurrect({
101
- build,
102
- memory,
103
- runTimeoutSecs,
104
- maxItems,
105
- maxTotalChargeUsd,
106
- restartOnError,
107
- timeoutSecs,
108
- signal,
109
- })
110
- : trackedRun;
111
- if (tracked.abortWithParent !== abortWithParent) {
112
- tracked.abortWithParent = abortWithParent;
113
- await this.persist();
102
+ this.pendingStartRequests++;
103
+ const started = (async () => {
104
+ let run;
105
+ try {
106
+ run = await start();
114
107
  }
115
- await this.update(runName, run);
116
- this.clients.set(runName, client);
117
- return { run, resumed: true };
118
- }
119
- const run = await start();
120
- await this.track(runName, run, request, trackedRun?.status ?? 'LOST', abortWithParent);
121
- this.clients.set(runName, client);
122
- return { run, resumed: false };
108
+ finally {
109
+ // The run is recorded right after this, so it never counts twice or not at all.
110
+ this.pendingStartRequests--;
111
+ }
112
+ const key = RUN_KEY_PREFIX + run.id;
113
+ if (client !== this.defaultClient)
114
+ this.clients.set(key, client);
115
+ await this.record(key, { runId: run.id, status: run.status, abortWithParent });
116
+ return run;
117
+ })();
118
+ this.startsInFlight.add(started);
119
+ return { starting: started };
123
120
  });
121
+ try {
122
+ return await starting;
123
+ }
124
+ finally {
125
+ this.startsInFlight.delete(starting);
126
+ }
124
127
  }
125
128
  /**
126
- * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
127
- * history, with `replacedStatus` as its last known status.
129
+ * Records the latest observed status of a child run.
128
130
  */
129
- async track(runName, run, request, replacedStatus, abortWithParent) {
130
- const trackedRuns = await this.load();
131
- const previous = trackedRuns[runName];
132
- trackedRuns[runName] = {
133
- ...toInfo(run),
134
- checksum: checksumRequest(request),
135
- history: previous
136
- ? [
137
- ...previous.history,
138
- { runId: previous.runId, startedAt: previous.startedAt, status: replacedStatus },
139
- ]
140
- : [],
141
- abortWithParent,
142
- };
143
- await this.persist();
131
+ async update(run) {
132
+ if (!this.enabled)
133
+ return;
134
+ const key = RUN_KEY_PREFIX + run.id;
135
+ const recorded = (await this.load()).runs[key];
136
+ if (recorded)
137
+ await this.record(key, { ...recorded, status: run.status });
144
138
  }
145
139
  /**
146
- * Records the latest observed state of the run tracked under `runName`.
140
+ * Returns a client for every recorded run, in recording order. The client is the one the run was started with in
141
+ * this process, or the default one (e.g. for a run recorded before a migration).
147
142
  */
148
- async update(runName, run) {
149
- const trackedRuns = await this.load();
150
- const tracked = trackedRuns[runName];
151
- if (tracked?.runId !== run.id || tracked.status === run.status)
152
- return;
153
- tracked.status = run.status;
154
- await this.persist();
143
+ async getRunClients() {
144
+ // Nothing is recorded before `Actor.init()`, whose missing call `Actor.childRuns()` warns about.
145
+ if (this.enabled === undefined)
146
+ return [];
147
+ this.assertEnabled('`Actor.childRuns()`');
148
+ const { runs } = await this.load();
149
+ return Object.entries(runs).map(([key, { runId, abortWithParent }]) => Object.defineProperty(this.clientFor(key).run(runId), 'abortWithParent', {
150
+ value: abortWithParent,
151
+ enumerable: true,
152
+ }));
155
153
  }
156
154
  /**
157
- * Returns the tracked run and its history for `runName`, if there is one.
155
+ * Gracefully aborts each recorded run with `abortWithParent` and an active recorded status, once, and makes any
156
+ * later start with `abortWithParent` throw. The starts in flight are waited for, so the runs they start are
157
+ * aborted too. Resolves after {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in
158
+ * progress to go on.
158
159
  */
159
- async get(runName) {
160
- const trackedRuns = await this.load();
161
- return trackedRuns[runName];
160
+ async abortRunsWithParent() {
161
+ if (!this.enabled)
162
+ return;
163
+ this.aborting ??= this.abortMarkedRuns();
164
+ await this.aborting;
162
165
  }
163
166
  /**
164
- * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
165
- * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
167
+ * Lets runs with `abortWithParent` start again, and makes the next exit abort them, after `Actor.exit()` that did
168
+ * not end the process.
166
169
  */
167
- getRunClients(defaultClient) {
168
- return Object.fromEntries(Object.entries(this.trackedRuns).map(([runName, { runId }]) => [
169
- runName,
170
- (this.clients.get(runName) ?? defaultClient).run(runId),
171
- ]));
170
+ resetAbort() {
171
+ this.aborting = undefined;
172
172
  }
173
173
  /**
174
- * Gracefully aborts the current run under each name tracked with `abortWithParent`, and makes any later start with
175
- * `abortWithParent` throw. A start in flight is waited for, so the run it starts is aborted too. Resolves after
176
- * {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in progress to go on.
174
+ * Waits for the starts in flight to be recorded, for {@link STARTS_IN_FLIGHT_TIMEOUT_MILLIS} at most.
177
175
  */
178
- async abortRunsWithParent(defaultClient) {
179
- this.isParentAborting = true;
180
- const trackedRuns = await this.load();
181
- const runNames = new Set([...Object.keys(trackedRuns), ...this.locks.keys()]);
182
- const aborts = Promise.all([...runNames].map(async (runName) => this.getLock(runName).runExclusive(async () => {
183
- const tracked = await this.get(runName);
184
- if (!tracked?.abortWithParent)
185
- return;
186
- try {
187
- const run = await (this.clients.get(runName) ?? defaultClient)
188
- .run(tracked.runId)
189
- .abort({ gracefully: true });
190
- if (ABORTED_STATUSES.includes(run.status)) {
191
- log.info(`Aborted child run "${runName}" with the parent`, { runId: run.id });
192
- }
193
- }
194
- catch (error) {
195
- if (error instanceof NotFoundError)
196
- return;
197
- log.exception(error, `Failed to abort child run "${runName}"`, {
198
- runId: tracked.runId,
199
- });
200
- }
201
- })));
202
- // `Actor.exit()` waits for this listener without a timeout of its own.
203
- await addTimeoutToPromise(async () => aborts, ABORT_WITH_PARENT_TIMEOUT_MILLIS, `Aborting the child runs with the parent timed out after ${ABORT_WITH_PARENT_TIMEOUT_MILLIS / 1000}s`).catch((error) => log.warning(error.message));
204
- }
205
- getLock(runName) {
206
- if (!this.locks.has(runName)) {
207
- this.locks.set(runName, new ReentrantAsyncLock());
208
- }
209
- return this.locks.get(runName);
210
- }
211
- async persist() {
212
- const write = this.lastWrite.then(async () => withDirectStorageAccess(async () => {
213
- const defaultStore = await KeyValueStore.open();
214
- await defaultStore.setValue(CHILD_RUNS_KVS_KEY, this.trackedRuns);
215
- }));
216
- this.lastWrite = write.catch(() => { });
217
- await write;
176
+ async waitForStartsInFlight() {
177
+ if (this.startsInFlight.size === 0)
178
+ return;
179
+ await addTimeoutToPromise(async () => Promise.allSettled([...this.startsInFlight]), STARTS_IN_FLIGHT_TIMEOUT_MILLIS, `Waiting for the child runs being started timed out after ${STARTS_IN_FLIGHT_TIMEOUT_MILLIS / 1000}s`).catch((error) => log.warning(error.message));
218
180
  }
219
181
  /**
220
- * Loads the tracked runs from the default key-value store, once.
182
+ * Loads the registry from the default key-value store, once.
221
183
  */
222
184
  async load() {
185
+ if (!this.enabled)
186
+ return this.registry;
223
187
  this.loading ??= KeyValueStore.open()
224
- .then(async (defaultStore) => defaultStore.getValue(CHILD_RUNS_KVS_KEY))
225
- .then((storedRuns) => {
226
- const parsed = trackedRunsSchema.safeParse(storedRuns ?? {});
188
+ .then(async (store) => store.getValue(CHILD_RUNS_KVS_KEY))
189
+ .then((stored) => {
190
+ const parsed = registrySchema.safeParse(stored ?? { runs: {} });
227
191
  if (!parsed.success) {
228
192
  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 });
229
193
  }
230
- this.trackedRuns = parsed.data;
194
+ this.registry = parsed.data;
195
+ this.warnIfExcessive();
231
196
  })
232
197
  .catch((error) => {
233
198
  this.loading = undefined;
234
199
  throw error;
235
200
  });
236
201
  await this.loading;
237
- return this.trackedRuns;
202
+ return this.registry;
203
+ }
204
+ async abortMarkedRuns() {
205
+ const startsInFlight = [...this.startsInFlight];
206
+ const aborts = (async () => {
207
+ await Promise.allSettled(startsInFlight);
208
+ const { runs } = await this.load();
209
+ await Promise.all(Object.entries(runs)
210
+ .filter(([, { abortWithParent, status }]) => abortWithParent && ACTIVE_STATUSES.includes(status))
211
+ .map(async ([key, { runId }]) => {
212
+ try {
213
+ const run = await this.clientFor(key).run(runId).abort({ gracefully: true });
214
+ if (ABORTED_STATUSES.includes(run.status)) {
215
+ log.info('Aborted child run with the parent', { runId });
216
+ }
217
+ }
218
+ catch (error) {
219
+ if (error instanceof NotFoundError) {
220
+ log.warning('Child run to abort with the parent was not found', { runId });
221
+ return;
222
+ }
223
+ log.exception(error, 'Failed to abort child run', { runId });
224
+ }
225
+ }));
226
+ })();
227
+ // `Actor.exit()` waits for this without a timeout of its own.
228
+ await addTimeoutToPromise(async () => aborts, ABORT_WITH_PARENT_TIMEOUT_MILLIS, `Aborting the child runs with the parent timed out after ${ABORT_WITH_PARENT_TIMEOUT_MILLIS / 1000}s`).catch((error) => log.warning(error.message));
229
+ }
230
+ /**
231
+ * Waits while the active runs and the pending start requests are at the concurrency limit. Throws instead of
232
+ * waiting once this run is being aborted or is exiting.
233
+ */
234
+ async waitForSlot() {
235
+ const maxRuns = this.maxConcurrentRuns;
236
+ if (maxRuns === undefined)
237
+ return;
238
+ const isAtLimit = (activeRuns) => activeRuns + this.pendingStartRequests >= maxRuns;
239
+ const recordedActiveRuns = () => Object.values(this.registry.runs).filter(({ status }) => ACTIVE_STATUSES.includes(status)).length;
240
+ // The recorded active statuses are refreshed only when they would block, since a refresh can only lower them.
241
+ while (isAtLimit(recordedActiveRuns()) && isAtLimit(await this.countActiveRuns())) {
242
+ if (this.aborting) {
243
+ throw new Error('The child run was not started, because this run is being aborted or is exiting.');
244
+ }
245
+ // Unlike `sleep()` from `@crawlee/utils`, which uses `node:timers/promises`, a global timer can be faked.
246
+ await new Promise((resolve) => {
247
+ setTimeout(resolve, CONCURRENCY_POLL_INTERVAL_MILLIS);
248
+ });
249
+ }
250
+ }
251
+ /**
252
+ * Counts the recorded runs with an active status. A status older than {@link STATUS_MAX_AGE_MILLIS}, or recorded
253
+ * by an earlier process, is fetched from the API first.
254
+ */
255
+ async countActiveRuns() {
256
+ const active = await Promise.all(Object.entries(this.registry.runs).map(async ([key, recorded]) => {
257
+ if (!ACTIVE_STATUSES.includes(recorded.status))
258
+ return false;
259
+ if (Date.now() - (this.observedAt.get(key) ?? -Infinity) <= STATUS_MAX_AGE_MILLIS)
260
+ return true;
261
+ let run;
262
+ try {
263
+ run = await this.clientFor(key).run(recorded.runId).get();
264
+ }
265
+ catch (error) {
266
+ // E.g. a run started with another token in an earlier process, which would block the limit forever.
267
+ if (error instanceof ApifyApiError && [401, 403].includes(error.statusCode))
268
+ return false;
269
+ log.warning('Failed to refresh the status of a child run, counting it as active', {
270
+ runId: recorded.runId,
271
+ error: error.message,
272
+ });
273
+ this.observedAt.set(key, Date.now());
274
+ return true;
275
+ }
276
+ if (!run)
277
+ return false;
278
+ await this.record(key, { ...recorded, status: run.status });
279
+ return ACTIVE_STATUSES.includes(run.status);
280
+ }));
281
+ return active.filter(Boolean).length;
282
+ }
283
+ clientFor(key) {
284
+ return this.clients.get(key) ?? this.defaultClient;
285
+ }
286
+ /**
287
+ * Records `record` under `key`. Its status must be one just returned by the API.
288
+ */
289
+ async record(key, record) {
290
+ this.observedAt.set(key, Date.now());
291
+ if (isDeepStrictEqual(this.registry.runs[key], record))
292
+ return;
293
+ this.registry.runs[key] = record;
294
+ this.warnIfExcessive();
295
+ await this.persist();
296
+ }
297
+ /**
298
+ * Writes the registry once the write in progress finishes. The changes made until then are written together. A
299
+ * failed write is logged, not thrown, since the run is already started, and the next write saves the change too.
300
+ */
301
+ async persist() {
302
+ if (!this.queuedWrite) {
303
+ this.queuedWrite = this.lastWrite.then(async () => {
304
+ this.queuedWrite = undefined;
305
+ await withDirectStorageAccess(async () => {
306
+ const store = await KeyValueStore.open();
307
+ await store.setValue(CHILD_RUNS_KVS_KEY, this.registry);
308
+ }).catch((error) => log.exception(error, 'Failed to write the child run registry'));
309
+ });
310
+ this.lastWrite = this.queuedWrite;
311
+ }
312
+ await this.queuedWrite;
313
+ }
314
+ warnIfExcessive() {
315
+ if (!this.warnOnExcessiveRuns || this.warnedExcessiveRuns)
316
+ return;
317
+ const count = Object.keys(this.registry.runs).length;
318
+ if (count <= EXCESSIVE_CHILD_RUNS_THRESHOLD)
319
+ return;
320
+ this.warnedExcessiveRuns = true;
321
+ log.warning(`Too many child runs (${count}). Tracking them can cause performance issues and excessive key-value store ` +
322
+ 'usage. Turn child run tracking off with `trackChildRuns: false`, or mute this warning with ' +
323
+ '`disableExcessiveChildRunWarning: true`.');
324
+ }
325
+ assertEnabled(feature) {
326
+ if (this.enabled === undefined) {
327
+ throw new Error(`${feature} requires child run tracking, which starts in \`Actor.init()\`.`);
328
+ }
329
+ if (!this.enabled) {
330
+ throw new Error(`${feature} requires child run tracking, which is turned off with \`trackChildRuns: false\`.`);
331
+ }
238
332
  }
239
333
  }
@@ -175,7 +175,8 @@ export declare class ProxyConfiguration extends CoreProxyConfiguration {
175
175
  *
176
176
  * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
177
177
  * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
178
- * username and with it the proxy session.
178
+ * username and with it the proxy session. A custom one persisted without its password is handed to the base
179
+ * class, which looks the password up in `proxyUrls`.
179
180
  */
180
181
  newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
181
182
  /**
@@ -154,13 +154,14 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
154
154
  *
155
155
  * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
156
156
  * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
157
- * username and with it the proxy session.
157
+ * username and with it the proxy session. A custom one persisted without its password is handed to the base
158
+ * class, which looks the password up in `proxyUrls`.
158
159
  */
159
160
  async newProxyInfo(proxyInfo) {
160
161
  // Only Apify Proxy infos carry `groups` and a proxy session in the username.
161
162
  if (proxyInfo &&
162
163
  !(this.#usesApifyProxy && 'groups' in proxyInfo && SESSION_USERNAME_REGEX.test(proxyInfo.username ?? ''))) {
163
- return proxyInfo;
164
+ return super.newProxyInfo(proxyInfo);
164
165
  }
165
166
  const url = proxyInfo?.username ? this.composeUrl(proxyInfo.username) : await this.newUrl();
166
167
  if (!url)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.145",
3
+ "version": "4.0.0-beta.147",
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"
@@ -53,44 +53,44 @@
53
53
  ]
54
54
  },
55
55
  "dependencies": {
56
- "@apify/consts": "^3.1.0",
56
+ "@apify/consts": "^3.2.0",
57
57
  "@apify/datastructures": "^3.0.1",
58
- "@apify/input_secrets": "^2.0.11",
59
- "@apify/log": "^3.1.0",
60
- "@apify/pseudo_url": "^3.0.3",
58
+ "@apify/input_secrets": "^2.0.12",
59
+ "@apify/log": "^3.1.1",
60
+ "@apify/pseudo_url": "^3.0.4",
61
61
  "@apify/timeout": "^1.1.0",
62
- "@apify/utilities": "^3.2.1",
62
+ "@apify/utilities": "^3.2.2",
63
63
  "@apify/validations": "^1.1.4",
64
- "@crawlee/core": "4.0.0-beta.342",
65
- "@crawlee/fs-storage": "4.0.0-beta.342",
66
- "@crawlee/types": "4.0.0-beta.342",
67
- "@crawlee/utils": "4.0.0-beta.342",
64
+ "@crawlee/core": "4.0.0-beta.348",
65
+ "@crawlee/fs-storage": "4.0.0-beta.348",
66
+ "@crawlee/types": "4.0.0-beta.348",
67
+ "@crawlee/utils": "4.0.0-beta.348",
68
68
  "apify-client": "^3.0.0-rc.2",
69
- "minimatch": "^11.0.9",
69
+ "minimatch": "^11.0.10",
70
70
  "tslib": "^2.9.1",
71
- "ws": "^8.23.0",
71
+ "ws": "^8.23.1",
72
72
  "zod": "^4.6.7"
73
73
  },
74
74
  "devDependencies": {
75
- "@apify/oxlint-config": "^0.4.0",
75
+ "@apify/oxlint-config": "^0.4.1",
76
76
  "@apify/tsconfig": "^0.2.0",
77
- "@commitlint/config-conventional": "^21.2.4",
77
+ "@commitlint/config-conventional": "^21.3.0",
78
78
  "@playwright/browser-chromium": "^1.65.1",
79
- "@types/node": "^26.6.6",
79
+ "@types/node": "^26.6.11",
80
80
  "@types/ws": "^8.18.2",
81
- "commitlint": "^21.2.4",
82
- "crawlee": "4.0.0-beta.342",
81
+ "commitlint": "^21.3.0",
82
+ "crawlee": "4.0.0-beta.348",
83
83
  "husky": "^9.1.7",
84
- "lint-staged": "^17.6.1",
84
+ "lint-staged": "^17.6.3",
85
85
  "oxfmt": "0.81.0",
86
86
  "oxlint": "1.95.0",
87
87
  "oxlint-tsgolint": "7.0.2009",
88
88
  "playwright": "^1.65.1",
89
- "puppeteer": "^25.18.1",
89
+ "puppeteer": "^25.19.0",
90
90
  "rimraf": "^6.1.4",
91
91
  "tsx": "^4.23.15",
92
92
  "typescript": "~7.0.2",
93
- "vitest": "^5.1.1"
93
+ "vitest": "^5.1.2"
94
94
  },
95
95
  "devEngines": {
96
96
  "packageManager": {