apify 4.0.0-beta.146 → 4.0.0-beta.148
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 +53 -30
- package/dist/actor.js +63 -58
- package/dist/child_run_tracker.d.ts +84 -62
- package/dist/child_run_tracker.js +279 -185
- package/dist/proxy_configuration.d.ts +2 -1
- package/dist/proxy_configuration.js +3 -2
- package/package.json +7 -7
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
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
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
|
-
*
|
|
116
|
-
*
|
|
117
|
-
* the
|
|
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
|
-
*
|
|
451
|
-
*
|
|
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
|
|
474
|
+
* const childRuns = await Actor.childRuns();
|
|
475
|
+
* await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
|
|
455
476
|
* ```
|
|
456
477
|
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
1057
|
-
*
|
|
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
|
|
1082
|
+
* const childRuns = await Actor.childRuns();
|
|
1083
|
+
* await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
|
|
1061
1084
|
* ```
|
|
1062
1085
|
*
|
|
1063
|
-
*
|
|
1064
|
-
*
|
|
1065
|
-
*
|
|
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
|
|
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(
|
|
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,33 @@ 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,
|
|
449
|
+
const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
|
|
447
450
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
451
|
+
// Like `ActorClient.call()`, but the run is recorded before it is waited for.
|
|
452
|
+
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
|
|
453
|
+
const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
|
|
454
|
+
return this.#waitForChildRun(client, run, { log, waitSecs, timeoutSecs, signal });
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Waits for a child run to finish while its log is redirected, like `call()` of `apify-client`, and records the
|
|
458
|
+
* status it finished in.
|
|
459
|
+
*/
|
|
460
|
+
async #waitForChildRun(client, run, { log: toLog, ...waitOptions }) {
|
|
461
|
+
const runClient = client.run(run.id);
|
|
462
|
+
let streamedLog;
|
|
463
|
+
try {
|
|
464
|
+
streamedLog = await runClient.getStreamedLog({ toLog, signal: waitOptions.signal });
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
// An aborted call rejects with the reason of its signal, which the wait below takes care of.
|
|
468
|
+
if (!waitOptions.signal?.aborted) {
|
|
469
|
+
log.warning(`Waiting for run ${run.id} without log redirection, which could not be set up: ${error.message}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
457
472
|
streamedLog?.start();
|
|
458
473
|
try {
|
|
459
|
-
const finishedRun = await
|
|
460
|
-
await this.#childRunTracker.update(
|
|
474
|
+
const finishedRun = await runClient.waitForFinish(waitOptions);
|
|
475
|
+
await this.#childRunTracker.update(finishedRun);
|
|
461
476
|
return finishedRun;
|
|
462
477
|
}
|
|
463
478
|
finally {
|
|
@@ -489,15 +504,9 @@ export class Actor {
|
|
|
489
504
|
*/
|
|
490
505
|
async start(actorId, input, options = {}) {
|
|
491
506
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
492
|
-
const { token, timeout: _timeout,
|
|
507
|
+
const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
|
|
493
508
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
494
|
-
|
|
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;
|
|
509
|
+
return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.actor(actorId).start(input, { ...rest, runTimeoutSecs }));
|
|
501
510
|
}
|
|
502
511
|
/**
|
|
503
512
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -575,34 +584,30 @@ export class Actor {
|
|
|
575
584
|
*/
|
|
576
585
|
async callTask(taskId, input, options = {}) {
|
|
577
586
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
578
|
-
const { token, timeout: _timeout,
|
|
587
|
+
const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
|
|
579
588
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
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));
|
|
587
|
-
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
588
|
-
await this.#childRunTracker.update(runName, finishedRun);
|
|
589
|
-
return finishedRun;
|
|
589
|
+
// Like `TaskClient.call()`, but the run is recorded before it is waited for.
|
|
590
|
+
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...startOptions } = rest;
|
|
591
|
+
const run = await this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...startOptions, runTimeoutSecs, timeoutSecs, signal }));
|
|
592
|
+
return this.#waitForChildRun(client, run, { log, waitSecs, timeoutSecs, signal });
|
|
590
593
|
}
|
|
591
594
|
/**
|
|
592
|
-
*
|
|
593
|
-
*
|
|
595
|
+
* Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
|
|
596
|
+
* `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
|
|
597
|
+
* migration, reboot or resurrection of this run.
|
|
594
598
|
*
|
|
595
599
|
* ```js
|
|
596
|
-
* await Actor.childRuns
|
|
600
|
+
* const childRuns = await Actor.childRuns();
|
|
601
|
+
* await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
|
|
597
602
|
* ```
|
|
598
603
|
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
604
|
+
* The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
|
|
605
|
+
* started with a custom `token` uses that token, except for a run started before a migration, reboot or
|
|
606
|
+
* resurrection of this run, which uses the default client.
|
|
602
607
|
*/
|
|
603
|
-
|
|
608
|
+
async childRuns() {
|
|
604
609
|
this.ensureActorInit('childRuns');
|
|
605
|
-
return this.#childRunTracker.getRunClients(
|
|
610
|
+
return this.#childRunTracker.getRunClients();
|
|
606
611
|
}
|
|
607
612
|
/**
|
|
608
613
|
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
@@ -629,15 +634,9 @@ export class Actor {
|
|
|
629
634
|
*/
|
|
630
635
|
async startTask(taskId, input, options = {}) {
|
|
631
636
|
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
632
|
-
const { token, timeout: _timeout,
|
|
637
|
+
const { token, timeout: _timeout, abortWithParent = false, ...rest } = options;
|
|
633
638
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
634
|
-
|
|
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;
|
|
639
|
+
return this.#childRunTracker.startChildRun(client, abortWithParent, async () => client.task(taskId).start(input, { ...rest, runTimeoutSecs }));
|
|
641
640
|
}
|
|
642
641
|
/**
|
|
643
642
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
@@ -659,6 +658,8 @@ export class Actor {
|
|
|
659
658
|
}
|
|
660
659
|
const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
|
|
661
660
|
const runId = this.configuration.actorRunId;
|
|
661
|
+
// The target Actor would not know about a child run whose start is not recorded yet.
|
|
662
|
+
await this.#childRunTracker.waitForStartsInFlight();
|
|
662
663
|
await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
|
|
663
664
|
// Wait some time for container to be stopped.
|
|
664
665
|
await sleep(customAfterSleepMillis);
|
|
@@ -703,6 +704,8 @@ export class Actor {
|
|
|
703
704
|
]);
|
|
704
705
|
}, timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
|
|
705
706
|
const runId = this.configuration.actorRunId;
|
|
707
|
+
// The new container would not know about a child run whose start is not recorded yet.
|
|
708
|
+
await this.#childRunTracker.waitForStartsInFlight();
|
|
706
709
|
try {
|
|
707
710
|
await this.apifyClient.run(runId).reboot();
|
|
708
711
|
}
|
|
@@ -1508,19 +1511,21 @@ export class Actor {
|
|
|
1508
1511
|
return Actor.getDefaultInstance().start(actorId, input, options);
|
|
1509
1512
|
}
|
|
1510
1513
|
/**
|
|
1511
|
-
*
|
|
1512
|
-
*
|
|
1514
|
+
* Returns a client for each child run started by `Actor.start()`, `Actor.call()`, `Actor.startTask()` or
|
|
1515
|
+
* `Actor.callTask()` after `Actor.init()`, in the order they were recorded, including the runs started before a
|
|
1516
|
+
* migration, reboot or resurrection of this run.
|
|
1513
1517
|
*
|
|
1514
1518
|
* ```js
|
|
1515
|
-
* await Actor.childRuns
|
|
1519
|
+
* const childRuns = await Actor.childRuns();
|
|
1520
|
+
* await Promise.all(childRuns.filter((c) => c.abortWithParent).map((c) => c.waitForFinish()));
|
|
1516
1521
|
* ```
|
|
1517
1522
|
*
|
|
1518
|
-
*
|
|
1519
|
-
*
|
|
1520
|
-
*
|
|
1523
|
+
* The child runs are recorded in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A run
|
|
1524
|
+
* started with a custom `token` uses that token, except for a run started before a migration, reboot or
|
|
1525
|
+
* resurrection of this run, which uses the default client.
|
|
1521
1526
|
*/
|
|
1522
|
-
static
|
|
1523
|
-
return Actor.getDefaultInstance().childRuns;
|
|
1527
|
+
static async childRuns() {
|
|
1528
|
+
return Actor.getDefaultInstance().childRuns();
|
|
1524
1529
|
}
|
|
1525
1530
|
/**
|
|
1526
1531
|
* 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
|
|
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
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
44
|
+
configure({ trackChildRuns, disableExcessiveChildRunWarning, maxConcurrentChildRuns, }: Pick<InitOptions, 'trackChildRuns' | 'disableExcessiveChildRunWarning' | 'maxConcurrentChildRuns'>): void;
|
|
48
45
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
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
|
-
|
|
55
|
-
run: ActorRun;
|
|
56
|
-
resumed: boolean;
|
|
57
|
-
}>;
|
|
49
|
+
startChildRun(client: ApifyClient, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<ActorRun>;
|
|
58
50
|
/**
|
|
59
|
-
*
|
|
60
|
-
* history, with `replacedStatus` as its last known status.
|
|
51
|
+
* Records the latest observed status of a child run.
|
|
61
52
|
*/
|
|
62
|
-
|
|
53
|
+
update(run: ActorRun): Promise<void>;
|
|
63
54
|
/**
|
|
64
|
-
*
|
|
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
|
-
|
|
58
|
+
getRunClients(): Promise<ChildRunClient[]>;
|
|
67
59
|
/**
|
|
68
|
-
*
|
|
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
|
-
|
|
65
|
+
abortRunsWithParent(): Promise<void>;
|
|
71
66
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
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
|
-
|
|
70
|
+
resetAbort(): void;
|
|
76
71
|
/**
|
|
77
|
-
*
|
|
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
|
-
|
|
82
|
-
private getLock;
|
|
83
|
-
private persist;
|
|
74
|
+
waitForStartsInFlight(): Promise<void>;
|
|
84
75
|
/**
|
|
85
|
-
* Loads the
|
|
76
|
+
* Loads the registry from the default key-value store, once.
|
|
86
77
|
*/
|
|
87
|
-
load(): Promise<
|
|
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 {
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
2
|
import { KeyValueStore, withDirectStorageAccess } from '@crawlee/core';
|
|
3
|
-
import {
|
|
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
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
-
*
|
|
82
|
-
*
|
|
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
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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
|
-
*
|
|
127
|
-
* history, with `replacedStatus` as its last known status.
|
|
129
|
+
* Records the latest observed status of a child run.
|
|
128
130
|
*/
|
|
129
|
-
async
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
-
*
|
|
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
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
*
|
|
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
|
|
160
|
-
|
|
161
|
-
|
|
160
|
+
async abortRunsWithParent() {
|
|
161
|
+
if (!this.enabled)
|
|
162
|
+
return;
|
|
163
|
+
this.aborting ??= this.abortMarkedRuns();
|
|
164
|
+
await this.aborting;
|
|
162
165
|
}
|
|
163
166
|
/**
|
|
164
|
-
*
|
|
165
|
-
*
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
runName,
|
|
170
|
-
(this.clients.get(runName) ?? defaultClient).run(runId),
|
|
171
|
-
]));
|
|
170
|
+
resetAbort() {
|
|
171
|
+
this.aborting = undefined;
|
|
172
172
|
}
|
|
173
173
|
/**
|
|
174
|
-
*
|
|
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
|
|
179
|
-
this.
|
|
180
|
-
|
|
181
|
-
|
|
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
|
|
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 (
|
|
225
|
-
.then((
|
|
226
|
-
const parsed =
|
|
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.
|
|
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.
|
|
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.
|
|
3
|
+
"version": "4.0.0-beta.148",
|
|
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"
|
|
@@ -61,11 +61,11 @@
|
|
|
61
61
|
"@apify/timeout": "^1.1.0",
|
|
62
62
|
"@apify/utilities": "^3.2.2",
|
|
63
63
|
"@apify/validations": "^1.1.4",
|
|
64
|
-
"@crawlee/core": "4.0.0-beta.
|
|
65
|
-
"@crawlee/fs-storage": "4.0.0-beta.
|
|
66
|
-
"@crawlee/types": "4.0.0-beta.
|
|
67
|
-
"@crawlee/utils": "4.0.0-beta.
|
|
68
|
-
"apify-client": "
|
|
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
|
+
"apify-client": "3.0.0-beta.127",
|
|
69
69
|
"minimatch": "^11.0.10",
|
|
70
70
|
"tslib": "^2.9.1",
|
|
71
71
|
"ws": "^8.23.1",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"@types/node": "^26.6.11",
|
|
80
80
|
"@types/ws": "^8.18.2",
|
|
81
81
|
"commitlint": "^21.3.0",
|
|
82
|
-
"crawlee": "4.0.0-beta.
|
|
82
|
+
"crawlee": "4.0.0-beta.348",
|
|
83
83
|
"husky": "^9.1.7",
|
|
84
84
|
"lint-staged": "^17.6.3",
|
|
85
85
|
"oxfmt": "0.81.0",
|