@crawlee/basic 4.0.0-beta.99 → 4.0.0-rc.1
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/README.md +1 -1
- package/index.d.ts +11 -1
- package/index.js +11 -0
- package/internals/autoscaling/autoscaled_pool.d.ts +178 -0
- package/internals/autoscaling/autoscaled_pool.js +387 -0
- package/internals/autoscaling/concurrency_system.d.ts +235 -0
- package/internals/autoscaling/concurrency_system.js +357 -0
- package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
- package/internals/autoscaling/cpu_load_signal.js +46 -0
- package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/internals/autoscaling/event_loop_load_signal.js +60 -0
- package/internals/autoscaling/index.d.ts +9 -0
- package/internals/autoscaling/index.js +9 -0
- package/internals/autoscaling/load_signal.d.ts +98 -0
- package/internals/autoscaling/load_signal.js +103 -0
- package/internals/autoscaling/memory_load_signal.d.ts +45 -0
- package/internals/autoscaling/memory_load_signal.js +104 -0
- package/internals/autoscaling/snapshotter.d.ts +84 -0
- package/internals/autoscaling/snapshotter.js +67 -0
- package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/internals/autoscaling/storage_backend_load_signal.js +73 -0
- package/internals/autoscaling/system_status.d.ts +112 -0
- package/internals/autoscaling/system_status.js +139 -0
- package/internals/autoscaling/weighted_avg.d.ts +5 -0
- package/internals/autoscaling/weighted_avg.js +14 -0
- package/internals/basic-crawler.d.ts +185 -389
- package/internals/basic-crawler.js +982 -684
- package/internals/cookie_utils.d.ts +40 -0
- package/internals/cookie_utils.js +122 -0
- package/internals/crawler-run.d.ts +76 -0
- package/internals/crawler-run.js +142 -0
- package/internals/crawlers/context_pipeline.d.ts +75 -0
- package/internals/crawlers/context_pipeline.js +109 -0
- package/internals/crawlers/crawler_commons.d.ts +216 -0
- package/internals/crawlers/crawler_commons.js +1 -0
- package/internals/crawlers/error_snapshotter.d.ts +29 -0
- package/internals/crawlers/error_snapshotter.js +116 -0
- package/internals/crawlers/error_tracker.d.ts +51 -0
- package/internals/crawlers/error_tracker.js +316 -0
- package/internals/crawlers/index.d.ts +4 -0
- package/internals/crawlers/index.js +3 -0
- package/internals/crawlers/internals/types.d.ts +7 -0
- package/internals/crawlers/internals/types.js +1 -0
- package/internals/crawlers/statistics.d.ts +316 -0
- package/internals/crawlers/statistics.js +525 -0
- package/internals/crawling_request.d.ts +86 -0
- package/internals/crawling_request.js +127 -0
- package/internals/enqueue_links/enqueue_links.d.ts +152 -0
- package/internals/enqueue_links/enqueue_links.js +76 -0
- package/internals/enqueue_links/index.d.ts +3 -0
- package/internals/enqueue_links/index.js +3 -0
- package/internals/enqueue_links/shared.d.ts +106 -0
- package/internals/enqueue_links/shared.js +258 -0
- package/internals/errors.d.ts +68 -0
- package/internals/errors.js +83 -0
- package/internals/http.d.ts +9 -0
- package/internals/http.js +28 -0
- package/internals/request-timeout.d.ts +6 -0
- package/internals/request-timeout.js +27 -2
- package/internals/router.d.ts +299 -0
- package/internals/router.js +312 -0
- package/internals/send-request.d.ts +2 -1
- package/internals/send-request.js +1 -0
- package/internals/session_pool/consts.d.ts +1 -0
- package/internals/session_pool/consts.js +1 -0
- package/internals/session_pool/errors.d.ts +7 -0
- package/internals/session_pool/errors.js +11 -0
- package/internals/session_pool/fingerprint.d.ts +9 -0
- package/internals/session_pool/fingerprint.js +30 -0
- package/internals/session_pool/index.d.ts +4 -0
- package/internals/session_pool/index.js +4 -0
- package/internals/session_pool/session.d.ts +151 -0
- package/internals/session_pool/session.js +225 -0
- package/internals/session_pool/session_pool.d.ts +193 -0
- package/internals/session_pool/session_pool.js +453 -0
- package/internals/sitemap_request_loader.d.ts +158 -0
- package/internals/sitemap_request_loader.js +432 -0
- package/internals/throttling_request_manager.d.ts +229 -0
- package/internals/throttling_request_manager.js +843 -0
- package/package.json +17 -14
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
|
|
|
34
34
|
|
|
35
35
|
We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
|
|
36
36
|
|
|
37
|
-
> Crawlee requires **Node.js
|
|
37
|
+
> Crawlee requires **Node.js 22.13 or higher**.
|
|
38
38
|
|
|
39
39
|
### With Crawlee CLI
|
|
40
40
|
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
1
|
export * from '@crawlee/core';
|
|
2
|
+
export * from './internals/autoscaling/index.js';
|
|
2
3
|
export * from './internals/basic-crawler.js';
|
|
3
|
-
export
|
|
4
|
+
export * from './internals/cookie_utils.js';
|
|
5
|
+
export * from './internals/crawlers/index.js';
|
|
6
|
+
export * from './internals/crawling_request.js';
|
|
7
|
+
export * from './internals/enqueue_links/index.js';
|
|
8
|
+
export * from './internals/errors.js';
|
|
9
|
+
export * from './internals/http.js';
|
|
10
|
+
export * from './internals/router.js';
|
|
11
|
+
export * from './internals/session_pool/index.js';
|
|
12
|
+
export * from './internals/sitemap_request_loader.js';
|
|
13
|
+
export * from './internals/throttling_request_manager.js';
|
package/index.js
CHANGED
|
@@ -1,2 +1,13 @@
|
|
|
1
1
|
export * from '@crawlee/core';
|
|
2
|
+
export * from './internals/autoscaling/index.js';
|
|
2
3
|
export * from './internals/basic-crawler.js';
|
|
4
|
+
export * from './internals/cookie_utils.js';
|
|
5
|
+
export * from './internals/crawlers/index.js';
|
|
6
|
+
export * from './internals/crawling_request.js';
|
|
7
|
+
export * from './internals/enqueue_links/index.js';
|
|
8
|
+
export * from './internals/errors.js';
|
|
9
|
+
export * from './internals/http.js';
|
|
10
|
+
export * from './internals/router.js';
|
|
11
|
+
export * from './internals/session_pool/index.js';
|
|
12
|
+
export * from './internals/sitemap_request_loader.js';
|
|
13
|
+
export * from './internals/throttling_request_manager.js';
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import type { CrawleeLogger } from '@crawlee/core';
|
|
2
|
+
import type { ConcurrencyConsumer, IConcurrencySystem } from './concurrency_system.js';
|
|
3
|
+
/**
|
|
4
|
+
* The two predicates that steer a task loop: *is there work ready?* and *are we done?* These are the parts of the loop
|
|
5
|
+
* a caller legitimately overrides, as opposed to the task itself (`runTaskFunction`), which the loop's driver owns.
|
|
6
|
+
*/
|
|
7
|
+
export interface TaskLoopPredicates {
|
|
8
|
+
/**
|
|
9
|
+
* A function that indicates whether `runTaskFunction` should be called.
|
|
10
|
+
* This function is called every time there is free capacity for a new task and it should
|
|
11
|
+
* indicate whether it should start a new task or not by resolving to either `true` or `false`.
|
|
12
|
+
* Besides its obvious use, it is also useful for task throttling to save resources.
|
|
13
|
+
*/
|
|
14
|
+
isTaskReadyFunction?: () => Promise<boolean>;
|
|
15
|
+
/**
|
|
16
|
+
* A function that is called only when there are no tasks to be processed.
|
|
17
|
+
* If it resolves to `true` then the run finishes. Being called only
|
|
18
|
+
* when there are no tasks being processed means that as long as `isTaskReadyFunction()`
|
|
19
|
+
* keeps resolving to `true`, `isFinishedFunction()` will never be called.
|
|
20
|
+
*/
|
|
21
|
+
isFinishedFunction?: () => Promise<boolean>;
|
|
22
|
+
}
|
|
23
|
+
export interface TaskLoopOptions extends TaskLoopPredicates {
|
|
24
|
+
/**
|
|
25
|
+
* How often the pool should check if a new task is ready, in seconds.
|
|
26
|
+
* @default 0.5
|
|
27
|
+
*/
|
|
28
|
+
maybeRunIntervalSecs?: number;
|
|
29
|
+
}
|
|
30
|
+
/** @internal */
|
|
31
|
+
export interface AutoscaledPoolOptions extends TaskLoopOptions {
|
|
32
|
+
/**
|
|
33
|
+
* The governor that decides whether there is free compute for one more task. Typically a
|
|
34
|
+
* {@link ConcurrencySystem}, but any {@link IConcurrencySystem} works. Share a single instance across
|
|
35
|
+
* multiple pools (and therefore multiple crawlers) to cap their *combined* concurrency against one budget.
|
|
36
|
+
*
|
|
37
|
+
* All concurrency/scaling/snapshotter configuration lives on the governor — the pool only owns the task loop and
|
|
38
|
+
* its cadence.
|
|
39
|
+
*/
|
|
40
|
+
concurrencySystem: IConcurrencySystem;
|
|
41
|
+
/**
|
|
42
|
+
* Who this pool is, presented to the governor on every capacity query and booking so that a shared one can tell
|
|
43
|
+
* several pools apart. Worth naming meaningfully — a governor that allocates per consumer reports this `id`.
|
|
44
|
+
*/
|
|
45
|
+
consumer: ConcurrencyConsumer;
|
|
46
|
+
/**
|
|
47
|
+
* A function that performs an asynchronous resource-intensive task.
|
|
48
|
+
* The function must either be labeled `async` or return a promise.
|
|
49
|
+
* @param taskId The id the task is {@link IConcurrencySystem.tryRegisterTaskStart|booked} under, so work done
|
|
50
|
+
* inside can be correlated with what the governor sees.
|
|
51
|
+
*/
|
|
52
|
+
runTaskFunction?: (taskId: string) => Promise<unknown>;
|
|
53
|
+
/**
|
|
54
|
+
* Timeout in which the `runTaskFunction` needs to finish, given in seconds.
|
|
55
|
+
* @default 0
|
|
56
|
+
*/
|
|
57
|
+
taskTimeoutSecs?: number;
|
|
58
|
+
log?: CrawleeLogger;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
|
|
62
|
+
* The pool only starts new tasks while its {@link IConcurrencySystem|concurrency system} reports free capacity —
|
|
63
|
+
* that governor is what monitors CPU, memory and event loop load and autoscales the concurrency budget.
|
|
64
|
+
*
|
|
65
|
+
* Before running the pool, you need to implement the following three functions:
|
|
66
|
+
* {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`},
|
|
67
|
+
* {@link TaskLoopPredicates.isTaskReadyFunction|`isTaskReadyFunction`} and
|
|
68
|
+
* {@link TaskLoopPredicates.isFinishedFunction|`isFinishedFunction`}.
|
|
69
|
+
*
|
|
70
|
+
* The auto-scaled pool is started by calling the {@link AutoscaledPool.run} function.
|
|
71
|
+
* The pool periodically queries `isTaskReadyFunction` for more tasks, managing optimal concurrency, until the function
|
|
72
|
+
* resolves to `false`. The pool then queries `isFinishedFunction`. If it resolves to `true`, the run finishes after all
|
|
73
|
+
* running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps
|
|
74
|
+
* periodically querying for tasks.
|
|
75
|
+
* If any of the tasks throws then the {@link AutoscaledPool.run} function rejects the promise with an error.
|
|
76
|
+
*
|
|
77
|
+
* The pool evaluates whether it should start a new task every time one of the tasks finishes
|
|
78
|
+
* and also in the interval set by the `options.maybeRunIntervalSecs` parameter.
|
|
79
|
+
*
|
|
80
|
+
* **Example usage:**
|
|
81
|
+
*
|
|
82
|
+
* ```javascript
|
|
83
|
+
* const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
|
|
84
|
+
* await concurrencySystem.start();
|
|
85
|
+
*
|
|
86
|
+
* const pool = new AutoscaledPool({
|
|
87
|
+
* concurrencySystem,
|
|
88
|
+
* consumer: { id: 'my-pool' },
|
|
89
|
+
* runTaskFunction: async () => {
|
|
90
|
+
* // Run some resource-intensive asynchronous operation here.
|
|
91
|
+
* },
|
|
92
|
+
* isTaskReadyFunction: async () => {
|
|
93
|
+
* // Tell the pool whether more tasks are ready to be processed.
|
|
94
|
+
* // Return true or false
|
|
95
|
+
* },
|
|
96
|
+
* isFinishedFunction: async () => {
|
|
97
|
+
* // Tell the pool whether it should finish
|
|
98
|
+
* // or wait for more tasks to become available.
|
|
99
|
+
* // Return true or false
|
|
100
|
+
* }
|
|
101
|
+
* });
|
|
102
|
+
*
|
|
103
|
+
* try {
|
|
104
|
+
* await pool.run();
|
|
105
|
+
* } finally {
|
|
106
|
+
* await concurrencySystem.stop();
|
|
107
|
+
* }
|
|
108
|
+
* ```
|
|
109
|
+
*
|
|
110
|
+
* @internal
|
|
111
|
+
*/
|
|
112
|
+
export declare class AutoscaledPool {
|
|
113
|
+
#private;
|
|
114
|
+
constructor(options: AutoscaledPoolOptions);
|
|
115
|
+
/**
|
|
116
|
+
* The governor backing this pool, as supplied to the constructor — exposed as the read-only
|
|
117
|
+
* {@link IConcurrencySystem} contract.
|
|
118
|
+
*
|
|
119
|
+
* This and the two getters below are telemetry only: concurrency is configured and tuned on the concrete
|
|
120
|
+
* {@link ConcurrencySystem} its owner holds, never through the pool.
|
|
121
|
+
*/
|
|
122
|
+
get system(): IConcurrencySystem;
|
|
123
|
+
/** The estimated number of parallel tasks the governor can currently support. */
|
|
124
|
+
get desiredConcurrency(): number;
|
|
125
|
+
/**
|
|
126
|
+
* The number of parallel tasks currently booked against the governor. When it is shared, this counts every
|
|
127
|
+
* borrowing pool's tasks, not just this one's.
|
|
128
|
+
*/
|
|
129
|
+
get currentConcurrency(): number;
|
|
130
|
+
/**
|
|
131
|
+
* Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once
|
|
132
|
+
* all the tasks are finished or one of them fails.
|
|
133
|
+
*
|
|
134
|
+
* Throws if the {@link IConcurrencySystem|concurrency system} it borrows was never started — the pool assumes
|
|
135
|
+
* a running governor and cannot start one it does not own.
|
|
136
|
+
*/
|
|
137
|
+
run(): Promise<void>;
|
|
138
|
+
/**
|
|
139
|
+
* Aborts the run of the auto-scaled pool and destroys it. The promise returned from
|
|
140
|
+
* the {@link AutoscaledPool.run} function will immediately resolve, no more new tasks
|
|
141
|
+
* will be spawned and all running tasks will be left in their current state.
|
|
142
|
+
*
|
|
143
|
+
* Due to the nature of the tasks, auto-scaled pool cannot reliably guarantee abortion
|
|
144
|
+
* of all the running tasks, therefore, no abortion is attempted and some of the tasks
|
|
145
|
+
* may finish, while others may not. Essentially, auto-scaled pool doesn't care about
|
|
146
|
+
* their state after the invocation of `.abort()`, but that does not mean that some
|
|
147
|
+
* parts of their asynchronous chains of commands will not execute.
|
|
148
|
+
*/
|
|
149
|
+
abort(): Promise<void>;
|
|
150
|
+
/**
|
|
151
|
+
* Prevents the auto-scaled pool from starting new tasks, but allows the running ones to finish
|
|
152
|
+
* (unlike abort, which terminates them). Used together with {@link AutoscaledPool.resume}
|
|
153
|
+
*
|
|
154
|
+
* The function's promise will resolve once all running tasks have completed and the pool
|
|
155
|
+
* is effectively idle. If the `timeoutSecs` argument is provided, the promise will reject
|
|
156
|
+
* with a timeout error after the `timeoutSecs` seconds.
|
|
157
|
+
*
|
|
158
|
+
* The promise returned from the {@link AutoscaledPool.run} function will not resolve
|
|
159
|
+
* when `.pause()` is invoked (unlike abort, which resolves it).
|
|
160
|
+
*
|
|
161
|
+
* > *NOTE:* Pausing the pool does not suspend the (possibly shared) {@link ConcurrencySystem} — its
|
|
162
|
+
* autoscaling and resource monitoring keep running, since other pools borrowing it may still be active. To silence
|
|
163
|
+
* it during a long pause, its owner can `stop()` and `start()` it again.
|
|
164
|
+
*/
|
|
165
|
+
pause(timeoutSecs?: number): Promise<void>;
|
|
166
|
+
/**
|
|
167
|
+
* Resumes the operation of the autoscaled-pool by allowing more tasks to be run.
|
|
168
|
+
* Used together with {@link AutoscaledPool.pause}
|
|
169
|
+
*
|
|
170
|
+
* Tasks will automatically start running again in `options.maybeRunIntervalSecs`.
|
|
171
|
+
*/
|
|
172
|
+
resume(): void;
|
|
173
|
+
/**
|
|
174
|
+
* Explicitly check the queue for new tasks. The AutoscaledPool checks the queue for new tasks periodically,
|
|
175
|
+
* every `maybeRunIntervalSecs` seconds. If you want to trigger the processing immediately, use this method.
|
|
176
|
+
*/
|
|
177
|
+
notify(): Promise<void>;
|
|
178
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { CriticalError, serviceLocator, validators } from '@crawlee/core';
|
|
2
|
+
import { parseArgument, schemas } from '@crawlee/utils/internal';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { addTimeoutToPromise } from '@apify/timeout';
|
|
5
|
+
import { betterClearInterval, betterSetInterval } from '@apify/utilities';
|
|
6
|
+
// `schemas.anyObject` and `objectWithKeys`-based validators pass values through by reference
|
|
7
|
+
// (object schemas return a pruned plain copy), so class instances like loggers and the
|
|
8
|
+
// concurrency system keep their prototype.
|
|
9
|
+
const autoscaledPoolOptionsSchema = z.strictObject({
|
|
10
|
+
runTaskFunction: schemas.anyFunction,
|
|
11
|
+
isFinishedFunction: schemas.anyFunction,
|
|
12
|
+
isTaskReadyFunction: schemas.anyFunction,
|
|
13
|
+
maybeRunIntervalSecs: schemas.anyNumber
|
|
14
|
+
.refine((value) => value > 0, 'Expected a number greater than 0')
|
|
15
|
+
.default(0.5),
|
|
16
|
+
taskTimeoutSecs: schemas.anyNumber
|
|
17
|
+
.refine((value) => value >= 0, 'Expected a number greater than or equal to 0')
|
|
18
|
+
.default(0),
|
|
19
|
+
log: validators.logger.default(() => serviceLocator.getLogger()),
|
|
20
|
+
concurrencySystem: schemas.anyObject,
|
|
21
|
+
consumer: schemas.anyObject.refine((value) => typeof value?.id === 'string' && value.id.length > 0, "Expected an object with a non-empty string 'id'"),
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
|
|
25
|
+
* The pool only starts new tasks while its {@link IConcurrencySystem|concurrency system} reports free capacity —
|
|
26
|
+
* that governor is what monitors CPU, memory and event loop load and autoscales the concurrency budget.
|
|
27
|
+
*
|
|
28
|
+
* Before running the pool, you need to implement the following three functions:
|
|
29
|
+
* {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`},
|
|
30
|
+
* {@link TaskLoopPredicates.isTaskReadyFunction|`isTaskReadyFunction`} and
|
|
31
|
+
* {@link TaskLoopPredicates.isFinishedFunction|`isFinishedFunction`}.
|
|
32
|
+
*
|
|
33
|
+
* The auto-scaled pool is started by calling the {@link AutoscaledPool.run} function.
|
|
34
|
+
* The pool periodically queries `isTaskReadyFunction` for more tasks, managing optimal concurrency, until the function
|
|
35
|
+
* resolves to `false`. The pool then queries `isFinishedFunction`. If it resolves to `true`, the run finishes after all
|
|
36
|
+
* running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps
|
|
37
|
+
* periodically querying for tasks.
|
|
38
|
+
* If any of the tasks throws then the {@link AutoscaledPool.run} function rejects the promise with an error.
|
|
39
|
+
*
|
|
40
|
+
* The pool evaluates whether it should start a new task every time one of the tasks finishes
|
|
41
|
+
* and also in the interval set by the `options.maybeRunIntervalSecs` parameter.
|
|
42
|
+
*
|
|
43
|
+
* **Example usage:**
|
|
44
|
+
*
|
|
45
|
+
* ```javascript
|
|
46
|
+
* const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
|
|
47
|
+
* await concurrencySystem.start();
|
|
48
|
+
*
|
|
49
|
+
* const pool = new AutoscaledPool({
|
|
50
|
+
* concurrencySystem,
|
|
51
|
+
* consumer: { id: 'my-pool' },
|
|
52
|
+
* runTaskFunction: async () => {
|
|
53
|
+
* // Run some resource-intensive asynchronous operation here.
|
|
54
|
+
* },
|
|
55
|
+
* isTaskReadyFunction: async () => {
|
|
56
|
+
* // Tell the pool whether more tasks are ready to be processed.
|
|
57
|
+
* // Return true or false
|
|
58
|
+
* },
|
|
59
|
+
* isFinishedFunction: async () => {
|
|
60
|
+
* // Tell the pool whether it should finish
|
|
61
|
+
* // or wait for more tasks to become available.
|
|
62
|
+
* // Return true or false
|
|
63
|
+
* }
|
|
64
|
+
* });
|
|
65
|
+
*
|
|
66
|
+
* try {
|
|
67
|
+
* await pool.run();
|
|
68
|
+
* } finally {
|
|
69
|
+
* await concurrencySystem.stop();
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* @internal
|
|
74
|
+
*/
|
|
75
|
+
export class AutoscaledPool {
|
|
76
|
+
#log;
|
|
77
|
+
// Configurable properties.
|
|
78
|
+
#maybeRunIntervalMillis;
|
|
79
|
+
#taskTimeoutMillis;
|
|
80
|
+
#runTaskFunction;
|
|
81
|
+
#isFinishedFunction;
|
|
82
|
+
#isTaskReadyFunction;
|
|
83
|
+
#concurrencySystem;
|
|
84
|
+
#consumer;
|
|
85
|
+
// Internal properties.
|
|
86
|
+
#isStopped = false;
|
|
87
|
+
#resolve = null;
|
|
88
|
+
#reject = null;
|
|
89
|
+
#maybeRunInterval;
|
|
90
|
+
#queryingIsTaskReady;
|
|
91
|
+
#queryingIsFinished;
|
|
92
|
+
/**
|
|
93
|
+
* This pool's *own* in-flight task count, as opposed to {@link AutoscaledPool.currentConcurrency}, which is the
|
|
94
|
+
* (possibly shared) governor's total. `pause()` and `maybeFinish()` care only about this pool draining.
|
|
95
|
+
*/
|
|
96
|
+
#ownConcurrency = 0;
|
|
97
|
+
/** Source of the ids that pair a booking with the release of the same task. */
|
|
98
|
+
#nextTaskId = 0;
|
|
99
|
+
constructor(options) {
|
|
100
|
+
const { runTaskFunction, isFinishedFunction, isTaskReadyFunction, maybeRunIntervalSecs, taskTimeoutSecs, log, concurrencySystem, consumer, } = parseArgument(options, autoscaledPoolOptionsSchema, 'AutoscaledPoolOptions');
|
|
101
|
+
this.#log = log.child({ prefix: 'AutoscaledPool' });
|
|
102
|
+
// Configurable properties.
|
|
103
|
+
this.#maybeRunIntervalMillis = maybeRunIntervalSecs * 1000;
|
|
104
|
+
this.#taskTimeoutMillis = taskTimeoutSecs * 1000;
|
|
105
|
+
this.#runTaskFunction = runTaskFunction;
|
|
106
|
+
this.#isFinishedFunction = isFinishedFunction;
|
|
107
|
+
this.#isTaskReadyFunction = isTaskReadyFunction;
|
|
108
|
+
this.#concurrencySystem = concurrencySystem;
|
|
109
|
+
this.#consumer = consumer;
|
|
110
|
+
// Internal properties.
|
|
111
|
+
this.#isStopped = false;
|
|
112
|
+
this.#resolve = null;
|
|
113
|
+
this.#reject = null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The governor backing this pool, as supplied to the constructor — exposed as the read-only
|
|
117
|
+
* {@link IConcurrencySystem} contract.
|
|
118
|
+
*
|
|
119
|
+
* This and the two getters below are telemetry only: concurrency is configured and tuned on the concrete
|
|
120
|
+
* {@link ConcurrencySystem} its owner holds, never through the pool.
|
|
121
|
+
*/
|
|
122
|
+
get system() {
|
|
123
|
+
return this.#concurrencySystem;
|
|
124
|
+
}
|
|
125
|
+
/** The estimated number of parallel tasks the governor can currently support. */
|
|
126
|
+
get desiredConcurrency() {
|
|
127
|
+
return this.#concurrencySystem.desiredConcurrency;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The number of parallel tasks currently booked against the governor. When it is shared, this counts every
|
|
131
|
+
* borrowing pool's tasks, not just this one's.
|
|
132
|
+
*/
|
|
133
|
+
get currentConcurrency() {
|
|
134
|
+
return this.#concurrencySystem.currentConcurrency;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once
|
|
138
|
+
* all the tasks are finished or one of them fails.
|
|
139
|
+
*
|
|
140
|
+
* Throws if the {@link IConcurrencySystem|concurrency system} it borrows was never started — the pool assumes
|
|
141
|
+
* a running governor and cannot start one it does not own.
|
|
142
|
+
*/
|
|
143
|
+
async run() {
|
|
144
|
+
// Checked here, on an awaited path — the capacity queries inside the task loop run from intervals and
|
|
145
|
+
// `setImmediate`, where a throw would become an unhandled rejection and hang `run()` forever.
|
|
146
|
+
if (!this.#concurrencySystem.isRunning) {
|
|
147
|
+
throw new CriticalError('The ConcurrencySystem this AutoscaledPool borrows has not been started, so system load would not be ' +
|
|
148
|
+
'monitored and the concurrency would never be adjusted. Whoever creates a ConcurrencySystem owns ' +
|
|
149
|
+
'its lifecycle: call `await concurrencySystem.start()` before running the pools or crawlers that ' +
|
|
150
|
+
'use it, and `await concurrencySystem.stop()` once they are all done.');
|
|
151
|
+
}
|
|
152
|
+
const poolPromise = new Promise((resolve, reject) => {
|
|
153
|
+
this.#resolve = resolve;
|
|
154
|
+
this.#reject = reject;
|
|
155
|
+
});
|
|
156
|
+
// This is here because if we scale down to let's say 1, then after each promise is finished
|
|
157
|
+
// this.maybeRunTask() doesn't trigger another one. So if that 1 instance gets stuck it results
|
|
158
|
+
// in the crawler getting stuck and even after scaling up it never triggers another promise.
|
|
159
|
+
this.#maybeRunInterval = betterSetInterval((cb) => this.#maybeRunTask(cb), this.#maybeRunIntervalMillis);
|
|
160
|
+
try {
|
|
161
|
+
await poolPromise;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
// If resolve is null, the pool is already destroyed.
|
|
165
|
+
if (this.#resolve)
|
|
166
|
+
await this.#destroy();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Aborts the run of the auto-scaled pool and destroys it. The promise returned from
|
|
171
|
+
* the {@link AutoscaledPool.run} function will immediately resolve, no more new tasks
|
|
172
|
+
* will be spawned and all running tasks will be left in their current state.
|
|
173
|
+
*
|
|
174
|
+
* Due to the nature of the tasks, auto-scaled pool cannot reliably guarantee abortion
|
|
175
|
+
* of all the running tasks, therefore, no abortion is attempted and some of the tasks
|
|
176
|
+
* may finish, while others may not. Essentially, auto-scaled pool doesn't care about
|
|
177
|
+
* their state after the invocation of `.abort()`, but that does not mean that some
|
|
178
|
+
* parts of their asynchronous chains of commands will not execute.
|
|
179
|
+
*/
|
|
180
|
+
async abort() {
|
|
181
|
+
this.#isStopped = true;
|
|
182
|
+
if (this.#resolve) {
|
|
183
|
+
this.#resolve();
|
|
184
|
+
await this.#destroy();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Prevents the auto-scaled pool from starting new tasks, but allows the running ones to finish
|
|
189
|
+
* (unlike abort, which terminates them). Used together with {@link AutoscaledPool.resume}
|
|
190
|
+
*
|
|
191
|
+
* The function's promise will resolve once all running tasks have completed and the pool
|
|
192
|
+
* is effectively idle. If the `timeoutSecs` argument is provided, the promise will reject
|
|
193
|
+
* with a timeout error after the `timeoutSecs` seconds.
|
|
194
|
+
*
|
|
195
|
+
* The promise returned from the {@link AutoscaledPool.run} function will not resolve
|
|
196
|
+
* when `.pause()` is invoked (unlike abort, which resolves it).
|
|
197
|
+
*
|
|
198
|
+
* > *NOTE:* Pausing the pool does not suspend the (possibly shared) {@link ConcurrencySystem} — its
|
|
199
|
+
* autoscaling and resource monitoring keep running, since other pools borrowing it may still be active. To silence
|
|
200
|
+
* it during a long pause, its owner can `stop()` and `start()` it again.
|
|
201
|
+
*/
|
|
202
|
+
async pause(timeoutSecs) {
|
|
203
|
+
if (this.#isStopped)
|
|
204
|
+
return;
|
|
205
|
+
this.#isStopped = true;
|
|
206
|
+
await new Promise((resolve, reject) => {
|
|
207
|
+
let timeout;
|
|
208
|
+
let interval;
|
|
209
|
+
if (timeoutSecs) {
|
|
210
|
+
timeout = setTimeout(() => {
|
|
211
|
+
// Clean up the polling interval to prevent it from leaking on timeout.
|
|
212
|
+
clearInterval(interval);
|
|
213
|
+
const err = new Error("The pool's running tasks did not finish" +
|
|
214
|
+
`in ${timeoutSecs} secs after pool.pause() invocation.`);
|
|
215
|
+
reject(err);
|
|
216
|
+
}, timeoutSecs);
|
|
217
|
+
}
|
|
218
|
+
interval = setInterval(() => {
|
|
219
|
+
if (this.#ownConcurrency <= 0) {
|
|
220
|
+
// Clean up timeout and interval to prevent process hanging.
|
|
221
|
+
if (timeout)
|
|
222
|
+
clearTimeout(timeout);
|
|
223
|
+
clearInterval(interval);
|
|
224
|
+
resolve();
|
|
225
|
+
}
|
|
226
|
+
}, this.#maybeRunIntervalMillis);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Resumes the operation of the autoscaled-pool by allowing more tasks to be run.
|
|
231
|
+
* Used together with {@link AutoscaledPool.pause}
|
|
232
|
+
*
|
|
233
|
+
* Tasks will automatically start running again in `options.maybeRunIntervalSecs`.
|
|
234
|
+
*/
|
|
235
|
+
resume() {
|
|
236
|
+
this.#isStopped = false;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Explicitly check the queue for new tasks. The AutoscaledPool checks the queue for new tasks periodically,
|
|
240
|
+
* every `maybeRunIntervalSecs` seconds. If you want to trigger the processing immediately, use this method.
|
|
241
|
+
*/
|
|
242
|
+
async notify() {
|
|
243
|
+
setImmediate(() => this.#maybeRunTask());
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Starts a new task
|
|
247
|
+
* if the number of running tasks (current concurrency) is lower than desired concurrency
|
|
248
|
+
* and the system is not currently overloaded
|
|
249
|
+
* and `isTaskReadyFunction()` returns true.
|
|
250
|
+
*
|
|
251
|
+
* It doesn't allow multiple concurrent runs of this method.
|
|
252
|
+
*/
|
|
253
|
+
async #maybeRunTask(intervalCallback) {
|
|
254
|
+
this.#log.perf('Attempting to run a task.');
|
|
255
|
+
// Check if the function was invoked by the maybeRunInterval and use an empty function if not.
|
|
256
|
+
const done = intervalCallback || (() => { });
|
|
257
|
+
// Prevent starting a new task if:
|
|
258
|
+
// - the pool is paused or aborted
|
|
259
|
+
if (this.#isStopped) {
|
|
260
|
+
this.#log.perf('Task will not run. AutoscaledPool is stopped.');
|
|
261
|
+
return done();
|
|
262
|
+
}
|
|
263
|
+
// - we are already querying for a task.
|
|
264
|
+
if (this.#queryingIsTaskReady) {
|
|
265
|
+
this.#log.perf('Task will not run. Waiting for a ready task.');
|
|
266
|
+
return done();
|
|
267
|
+
}
|
|
268
|
+
// - the budget has room for us.
|
|
269
|
+
if (!this.#concurrencySystem.hasCapacityForTask(this.#consumer)) {
|
|
270
|
+
done();
|
|
271
|
+
// A shared governor's budget can stay saturated by another pool indefinitely, so we still have to be able
|
|
272
|
+
// to notice that *this* pool has run out of work — `maybeFinish()` is the only thing that ever resolves
|
|
273
|
+
// `run()`. It no-ops while this pool has tasks of its own in flight, which is every case in which an
|
|
274
|
+
// unshared governor reports no capacity.
|
|
275
|
+
return this.#maybeFinish();
|
|
276
|
+
}
|
|
277
|
+
// - a task is ready.
|
|
278
|
+
this.#queryingIsTaskReady = true;
|
|
279
|
+
let isTaskReady;
|
|
280
|
+
try {
|
|
281
|
+
this.#log.perf('Checking for ready tasks.');
|
|
282
|
+
isTaskReady = await this.#isTaskReadyFunction();
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
const err = e;
|
|
286
|
+
this.#log.perf('Checking for ready tasks failed.');
|
|
287
|
+
// We might have already rejected this promise.
|
|
288
|
+
if (this.#reject) {
|
|
289
|
+
// No need to log all concurrent errors.
|
|
290
|
+
this.#log.exception(err, 'isTaskReadyFunction failed');
|
|
291
|
+
this.#reject(err);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
this.#queryingIsTaskReady = false;
|
|
296
|
+
}
|
|
297
|
+
if (!isTaskReady) {
|
|
298
|
+
this.#log.perf('Task will not run. No tasks are ready.');
|
|
299
|
+
done();
|
|
300
|
+
// No tasks could mean that we're finished with all tasks.
|
|
301
|
+
return this.#maybeFinish();
|
|
302
|
+
}
|
|
303
|
+
const taskId = String(this.#nextTaskId++);
|
|
304
|
+
// - the budget still has room. Re-checked atomically, because another pool sharing the governor may have taken
|
|
305
|
+
// the last free slot while we awaited `isTaskReadyFunction` above.
|
|
306
|
+
if (!this.#concurrencySystem.tryRegisterTaskStart(this.#consumer, taskId)) {
|
|
307
|
+
return done();
|
|
308
|
+
}
|
|
309
|
+
this.#ownConcurrency++;
|
|
310
|
+
try {
|
|
311
|
+
// Everything's fine. Run task.
|
|
312
|
+
// Try to run next task to build up concurrency,
|
|
313
|
+
// but defer it so it doesn't create a cycle.
|
|
314
|
+
setImmediate(() => this.#maybeRunTask());
|
|
315
|
+
// We need to restart interval here, so that it doesn't get blocked by a stalled task.
|
|
316
|
+
done();
|
|
317
|
+
// Execute the current task.
|
|
318
|
+
this.#log.perf('Running a task.');
|
|
319
|
+
if (this.#taskTimeoutMillis > 0) {
|
|
320
|
+
await addTimeoutToPromise(async () => this.#runTaskFunction(taskId), this.#taskTimeoutMillis, `runTaskFunction timed out after ${this.#taskTimeoutMillis / 1000} seconds.`);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
await this.#runTaskFunction(taskId);
|
|
324
|
+
}
|
|
325
|
+
this.#log.perf('Task finished.');
|
|
326
|
+
// Run task after the previous one finished. Only on success: a failed task rejects the pool, and
|
|
327
|
+
// nudging the loop afterwards could start work on an already destroyed pool.
|
|
328
|
+
setImmediate(() => this.#maybeRunTask());
|
|
329
|
+
}
|
|
330
|
+
catch (e) {
|
|
331
|
+
const err = e;
|
|
332
|
+
this.#log.perf('Running a task failed.');
|
|
333
|
+
// We might have already rejected this promise.
|
|
334
|
+
if (this.#reject) {
|
|
335
|
+
// No need to log all concurrent errors.
|
|
336
|
+
if (
|
|
337
|
+
// avoid reprinting the same critical error multiple times, as it will be printed by Nodejs at the end anyway
|
|
338
|
+
!(e instanceof CriticalError)) {
|
|
339
|
+
this.#log.exception(err, 'runTaskFunction failed.');
|
|
340
|
+
}
|
|
341
|
+
this.#reject(err);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
this.#concurrencySystem.registerTaskEnd(this.#consumer, taskId);
|
|
346
|
+
this.#ownConcurrency--;
|
|
347
|
+
}
|
|
348
|
+
return undefined;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* If there are no running tasks and `isFinishedFunction()` returns true then closes
|
|
352
|
+
* the pool and resolves the pool's promise returned by the run() method.
|
|
353
|
+
*
|
|
354
|
+
* It doesn't allow multiple concurrent runs of this method.
|
|
355
|
+
*/
|
|
356
|
+
async #maybeFinish() {
|
|
357
|
+
if (this.#queryingIsFinished)
|
|
358
|
+
return;
|
|
359
|
+
if (this.#ownConcurrency > 0)
|
|
360
|
+
return;
|
|
361
|
+
this.#queryingIsFinished = true;
|
|
362
|
+
try {
|
|
363
|
+
const isFinished = await this.#isFinishedFunction();
|
|
364
|
+
if (isFinished && this.#resolve)
|
|
365
|
+
this.#resolve();
|
|
366
|
+
}
|
|
367
|
+
catch (e) {
|
|
368
|
+
const err = e;
|
|
369
|
+
if (this.#reject) {
|
|
370
|
+
// No need to log all concurrent errors.
|
|
371
|
+
this.#log.exception(err, 'isFinishedFunction failed.');
|
|
372
|
+
this.#reject(err);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
this.#queryingIsFinished = false;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Cleans up resources.
|
|
381
|
+
*/
|
|
382
|
+
async #destroy() {
|
|
383
|
+
this.#resolve = null;
|
|
384
|
+
this.#reject = null;
|
|
385
|
+
betterClearInterval(this.#maybeRunInterval);
|
|
386
|
+
}
|
|
387
|
+
}
|