@crawlee/core 4.0.0-rc.0 → 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.
Files changed (122) hide show
  1. package/README.md +1 -1
  2. package/configuration.d.ts +15 -46
  3. package/configuration.js +8 -20
  4. package/errors.d.ts +12 -53
  5. package/errors.js +13 -66
  6. package/events/index.d.ts +1 -0
  7. package/events/local_event_manager.d.ts +0 -7
  8. package/events/local_event_manager.js +8 -8
  9. package/events/system_info.d.ts +38 -0
  10. package/index.d.ts +2 -8
  11. package/index.js +4 -8
  12. package/internal.d.ts +8 -0
  13. package/internal.js +9 -0
  14. package/log.d.ts +10 -11
  15. package/log.js +53 -25
  16. package/memory-storage/memory-storage.d.ts +12 -7
  17. package/memory-storage/memory-storage.js +45 -17
  18. package/memory-storage/resource-clients/dataset.d.ts +0 -5
  19. package/memory-storage/resource-clients/dataset.js +17 -20
  20. package/memory-storage/resource-clients/key-value-store.d.ts +0 -9
  21. package/memory-storage/resource-clients/key-value-store.js +11 -33
  22. package/memory-storage/resource-clients/request-queue.d.ts +0 -22
  23. package/memory-storage/resource-clients/request-queue.js +57 -53
  24. package/package.json +16 -18
  25. package/proxy_configuration.d.ts +20 -23
  26. package/proxy_configuration.js +18 -12
  27. package/recoverable_state.d.ts +28 -6
  28. package/recoverable_state.js +51 -14
  29. package/request.d.ts +18 -104
  30. package/request.js +41 -220
  31. package/serialization.js +3 -3
  32. package/service_locator.d.ts +3 -0
  33. package/service_locator.js +2 -0
  34. package/storages/dataset.d.ts +9 -15
  35. package/storages/dataset.js +22 -14
  36. package/storages/index.d.ts +3 -4
  37. package/storages/index.js +1 -4
  38. package/storages/key_value_store.d.ts +12 -46
  39. package/storages/key_value_store.js +31 -47
  40. package/storages/key_value_store_codec.js +6 -11
  41. package/storages/request_dedup_cache.d.ts +0 -2
  42. package/storages/request_dedup_cache.js +8 -8
  43. package/storages/request_list.d.ts +6 -82
  44. package/storages/request_list.js +175 -179
  45. package/storages/request_loader.d.ts +48 -22
  46. package/storages/request_loader.js +36 -1
  47. package/storages/request_manager.d.ts +86 -0
  48. package/storages/request_manager_tandem.d.ts +13 -28
  49. package/storages/request_manager_tandem.js +46 -43
  50. package/storages/request_queue.d.ts +19 -49
  51. package/storages/request_queue.js +92 -88
  52. package/storages/storage_instance_manager.d.ts +1 -2
  53. package/storages/storage_instance_manager.js +4 -4
  54. package/storages/transaction.d.ts +27 -9
  55. package/storages/transaction.js +56 -11
  56. package/storages/utils.d.ts +2 -2
  57. package/validators.d.ts +3 -2
  58. package/validators.js +3 -2
  59. package/autoscaling/autoscaled_pool.d.ts +0 -195
  60. package/autoscaling/autoscaled_pool.js +0 -386
  61. package/autoscaling/concurrency_system.d.ts +0 -268
  62. package/autoscaling/concurrency_system.js +0 -362
  63. package/autoscaling/cpu_load_signal.d.ts +0 -43
  64. package/autoscaling/cpu_load_signal.js +0 -47
  65. package/autoscaling/event_loop_load_signal.d.ts +0 -51
  66. package/autoscaling/event_loop_load_signal.js +0 -60
  67. package/autoscaling/index.d.ts +0 -9
  68. package/autoscaling/index.js +0 -9
  69. package/autoscaling/load_signal.d.ts +0 -100
  70. package/autoscaling/load_signal.js +0 -105
  71. package/autoscaling/memory_load_signal.d.ts +0 -47
  72. package/autoscaling/memory_load_signal.js +0 -106
  73. package/autoscaling/snapshotter.d.ts +0 -84
  74. package/autoscaling/snapshotter.js +0 -67
  75. package/autoscaling/storage_backend_load_signal.d.ts +0 -56
  76. package/autoscaling/storage_backend_load_signal.js +0 -73
  77. package/autoscaling/system_status.d.ts +0 -159
  78. package/autoscaling/system_status.js +0 -139
  79. package/autoscaling/weighted_avg.d.ts +0 -5
  80. package/autoscaling/weighted_avg.js +0 -14
  81. package/cookie_utils.d.ts +0 -44
  82. package/cookie_utils.js +0 -122
  83. package/crawlers/context_pipeline.d.ts +0 -70
  84. package/crawlers/context_pipeline.js +0 -122
  85. package/crawlers/crawler_commons.d.ts +0 -159
  86. package/crawlers/error_snapshotter.d.ts +0 -57
  87. package/crawlers/error_snapshotter.js +0 -117
  88. package/crawlers/error_tracker.d.ts +0 -54
  89. package/crawlers/error_tracker.js +0 -308
  90. package/crawlers/index.d.ts +0 -5
  91. package/crawlers/index.js +0 -4
  92. package/crawlers/internals/types.d.ts +0 -7
  93. package/crawlers/internals/types.js +0 -1
  94. package/crawlers/statistics.d.ts +0 -328
  95. package/crawlers/statistics.js +0 -536
  96. package/enqueue_links/enqueue_links.d.ts +0 -156
  97. package/enqueue_links/enqueue_links.js +0 -78
  98. package/enqueue_links/index.d.ts +0 -2
  99. package/enqueue_links/index.js +0 -2
  100. package/enqueue_links/shared.d.ts +0 -93
  101. package/enqueue_links/shared.js +0 -239
  102. package/http.d.ts +0 -9
  103. package/http.js +0 -28
  104. package/router.d.ts +0 -306
  105. package/router.js +0 -309
  106. package/session_pool/consts.d.ts +0 -3
  107. package/session_pool/consts.js +0 -3
  108. package/session_pool/errors.d.ts +0 -7
  109. package/session_pool/errors.js +0 -11
  110. package/session_pool/fingerprint.d.ts +0 -9
  111. package/session_pool/fingerprint.js +0 -30
  112. package/session_pool/index.d.ts +0 -4
  113. package/session_pool/index.js +0 -4
  114. package/session_pool/session.d.ts +0 -150
  115. package/session_pool/session.js +0 -220
  116. package/session_pool/session_pool.d.ts +0 -240
  117. package/session_pool/session_pool.js +0 -394
  118. package/storages/sitemap_request_loader.d.ts +0 -201
  119. package/storages/sitemap_request_loader.js +0 -438
  120. package/storages/throttling_request_manager.d.ts +0 -239
  121. package/storages/throttling_request_manager.js +0 -646
  122. /package/{crawlers/crawler_commons.js → events/system_info.js} +0 -0
@@ -1,386 +0,0 @@
1
- import { z } from 'zod';
2
- import { addTimeoutToPromise } from '@apify/timeout';
3
- import { betterClearInterval, betterSetInterval } from '@apify/utilities';
4
- import { CriticalError } from '../errors.js';
5
- import { serviceLocator } from '../service_locator.js';
6
- import { parseArgument, schemas, validators } from '../validators.js';
7
- // `schemas.anyObject` and `objectWithKeys`-based validators pass values through by reference
8
- // (object schemas return a pruned plain copy), so class instances like loggers and the
9
- // concurrency system keep their prototype.
10
- const autoscaledPoolOptionsSchema = z.strictObject({
11
- runTaskFunction: schemas.anyFunction,
12
- isFinishedFunction: schemas.anyFunction,
13
- isTaskReadyFunction: schemas.anyFunction,
14
- maybeRunIntervalSecs: schemas.anyNumber
15
- .refine((value) => value > 0, 'Expected a number greater than 0')
16
- .default(0.5),
17
- taskTimeoutSecs: schemas.anyNumber
18
- .refine((value) => value >= 0, 'Expected a number greater than or equal to 0')
19
- .default(0),
20
- log: validators.logger.default(() => serviceLocator.getLogger()),
21
- concurrencySystem: schemas.anyObject,
22
- consumer: schemas.anyObject.refine((value) => typeof value.id === 'string' && value.id.length > 0, "Expected an object with a non-empty string 'id'"),
23
- });
24
- /**
25
- * Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
26
- * The pool only starts new tasks while its {@link IConcurrencySystem|concurrency system} reports free capacity —
27
- * that governor is what monitors CPU, memory and event loop load and autoscales the concurrency budget.
28
- *
29
- * Before running the pool, you need to implement the following three functions:
30
- * {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`},
31
- * {@link TaskLoopPredicates.isTaskReadyFunction|`isTaskReadyFunction`} and
32
- * {@link TaskLoopPredicates.isFinishedFunction|`isFinishedFunction`}.
33
- *
34
- * The auto-scaled pool is started by calling the {@link AutoscaledPool.run} function.
35
- * The pool periodically queries `isTaskReadyFunction` for more tasks, managing optimal concurrency, until the function
36
- * resolves to `false`. The pool then queries `isFinishedFunction`. If it resolves to `true`, the run finishes after all
37
- * running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps
38
- * periodically querying for tasks.
39
- * If any of the tasks throws then the {@link AutoscaledPool.run} function rejects the promise with an error.
40
- *
41
- * The pool evaluates whether it should start a new task every time one of the tasks finishes
42
- * and also in the interval set by the `options.maybeRunIntervalSecs` parameter.
43
- *
44
- * **Example usage:**
45
- *
46
- * ```javascript
47
- * const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
48
- * await concurrencySystem.start();
49
- *
50
- * const pool = new AutoscaledPool({
51
- * concurrencySystem,
52
- * consumer: { id: 'my-pool' },
53
- * runTaskFunction: async () => {
54
- * // Run some resource-intensive asynchronous operation here.
55
- * },
56
- * isTaskReadyFunction: async () => {
57
- * // Tell the pool whether more tasks are ready to be processed.
58
- * // Return true or false
59
- * },
60
- * isFinishedFunction: async () => {
61
- * // Tell the pool whether it should finish
62
- * // or wait for more tasks to become available.
63
- * // Return true or false
64
- * }
65
- * });
66
- *
67
- * try {
68
- * await pool.run();
69
- * } finally {
70
- * await concurrencySystem.stop();
71
- * }
72
- * ```
73
- *
74
- * @internal
75
- */
76
- export class AutoscaledPool {
77
- #log;
78
- // Configurable properties.
79
- #maybeRunIntervalMillis;
80
- #taskTimeoutMillis;
81
- #runTaskFunction;
82
- #isFinishedFunction;
83
- #isTaskReadyFunction;
84
- #concurrencySystem;
85
- #consumer;
86
- // Internal properties.
87
- #isStopped = false;
88
- #resolve = null;
89
- #reject = null;
90
- #maybeRunInterval;
91
- #queryingIsTaskReady;
92
- #queryingIsFinished;
93
- /**
94
- * This pool's *own* in-flight task count, as opposed to {@link AutoscaledPool.currentConcurrency}, which is the
95
- * (possibly shared) governor's total. `pause()` and `maybeFinish()` care only about this pool draining.
96
- */
97
- #ownConcurrency = 0;
98
- constructor(options) {
99
- const { runTaskFunction, isFinishedFunction, isTaskReadyFunction, maybeRunIntervalSecs, taskTimeoutSecs, log, concurrencySystem, consumer, } = parseArgument(options, autoscaledPoolOptionsSchema, 'AutoscaledPoolOptions');
100
- this.#log = log.child({ prefix: 'AutoscaledPool' });
101
- // Configurable properties.
102
- this.#maybeRunIntervalMillis = maybeRunIntervalSecs * 1000;
103
- this.#taskTimeoutMillis = taskTimeoutSecs * 1000;
104
- this.#runTaskFunction = runTaskFunction;
105
- this.#isFinishedFunction = isFinishedFunction;
106
- this.#isTaskReadyFunction = isTaskReadyFunction;
107
- this.#concurrencySystem = concurrencySystem;
108
- this.#consumer = consumer;
109
- // Internal properties.
110
- this.#isStopped = false;
111
- this.#resolve = null;
112
- this.#reject = null;
113
- this.maybeRunTask = this.maybeRunTask.bind(this);
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(this.maybeRunTask, 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
- // - the budget still has room. Re-checked atomically, because another pool sharing the governor may have taken
304
- // the last free slot while we awaited `isTaskReadyFunction` above.
305
- if (!this.#concurrencySystem.tryRegisterTaskStart(this.#consumer)) {
306
- return done();
307
- }
308
- this.#ownConcurrency++;
309
- try {
310
- // Everything's fine. Run task.
311
- // Try to run next task to build up concurrency,
312
- // but defer it so it doesn't create a cycle.
313
- setImmediate(this.maybeRunTask);
314
- // We need to restart interval here, so that it doesn't get blocked by a stalled task.
315
- done();
316
- // Execute the current task.
317
- this.#log.perf('Running a task.');
318
- if (this.#taskTimeoutMillis > 0) {
319
- await addTimeoutToPromise(async () => this.#runTaskFunction(), this.#taskTimeoutMillis, `runTaskFunction timed out after ${this.#taskTimeoutMillis / 1000} seconds.`);
320
- }
321
- else {
322
- await this.#runTaskFunction();
323
- }
324
- this.#log.perf('Task finished.');
325
- // Run task after the previous one finished. Only on success: a failed task rejects the pool, and
326
- // nudging the loop afterwards could start work on an already destroyed pool.
327
- setImmediate(this.maybeRunTask);
328
- }
329
- catch (e) {
330
- const err = e;
331
- this.#log.perf('Running a task failed.');
332
- // We might have already rejected this promise.
333
- if (this.#reject) {
334
- // No need to log all concurrent errors.
335
- if (
336
- // avoid reprinting the same critical error multiple times, as it will be printed by Nodejs at the end anyway
337
- !(e instanceof CriticalError)) {
338
- this.#log.exception(err, 'runTaskFunction failed.');
339
- }
340
- this.#reject(err);
341
- }
342
- }
343
- finally {
344
- this.#concurrencySystem.registerTaskEnd(this.#consumer);
345
- this.#ownConcurrency--;
346
- }
347
- return undefined;
348
- }
349
- /**
350
- * If there are no running tasks and `isFinishedFunction()` returns true then closes
351
- * the pool and resolves the pool's promise returned by the run() method.
352
- *
353
- * It doesn't allow multiple concurrent runs of this method.
354
- */
355
- async maybeFinish() {
356
- if (this.#queryingIsFinished)
357
- return;
358
- if (this.#ownConcurrency > 0)
359
- return;
360
- this.#queryingIsFinished = true;
361
- try {
362
- const isFinished = await this.#isFinishedFunction();
363
- if (isFinished && this.#resolve)
364
- this.#resolve();
365
- }
366
- catch (e) {
367
- const err = e;
368
- if (this.#reject) {
369
- // No need to log all concurrent errors.
370
- this.#log.exception(err, 'isFinishedFunction failed.');
371
- this.#reject(err);
372
- }
373
- }
374
- finally {
375
- this.#queryingIsFinished = false;
376
- }
377
- }
378
- /**
379
- * Cleans up resources.
380
- */
381
- async destroy() {
382
- this.#resolve = null;
383
- this.#reject = null;
384
- betterClearInterval(this.#maybeRunInterval);
385
- }
386
- }
@@ -1,268 +0,0 @@
1
- import type { CrawleeLogger } from '../log.js';
2
- import type { LoadSignalsOptions } from './snapshotter.js';
3
- import type { SystemInfo } from './system_status.js';
4
- export interface ConcurrencySystemOptions {
5
- /**
6
- * The minimum number of tasks running in parallel.
7
- *
8
- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
9
- * If you're not sure, just keep the default value and the concurrency will scale up automatically.
10
- * @default 1
11
- */
12
- minConcurrency?: number;
13
- /**
14
- * The maximum number of tasks running in parallel.
15
- * @default 200
16
- */
17
- maxConcurrency?: number;
18
- /**
19
- * The desired number of tasks that should be running parallel on the start of the pool,
20
- * if there is a large enough supply of them.
21
- * By default, it is `minConcurrency`.
22
- */
23
- desiredConcurrency?: number;
24
- /**
25
- * Minimum level of desired concurrency to reach before more scaling up is allowed.
26
- * @default 0.90
27
- */
28
- desiredConcurrencyRatio?: number;
29
- /**
30
- * Defines the fractional amount of desired concurrency to be added with each scaling up.
31
- * The minimum scaling step is one.
32
- * @default 0.05
33
- */
34
- scaleUpStepRatio?: number;
35
- /**
36
- * Defines the amount of desired concurrency to be subtracted with each scaling down.
37
- * The minimum scaling step is one.
38
- * @default 0.05
39
- */
40
- scaleDownStepRatio?: number;
41
- /**
42
- * Specifies a period in which the instance logs its state, in seconds.
43
- * Set to `null` to disable periodic logging.
44
- * @default 60
45
- */
46
- loggingIntervalSecs?: number | null;
47
- /**
48
- * Defines in seconds how often the system should attempt to adjust the desired concurrency
49
- * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.
50
- * We suggest using a value from 5 to 20.
51
- * @default 10
52
- */
53
- autoscaleIntervalSecs?: number;
54
- /**
55
- * The signals that tell the system whether the machine is overloaded: per-resource tuning for the built-in four
56
- * (memory, event loop, CPU, storage backend) plus any {@link LoadSignalsOptions.custom|`custom`}
57
- * implementations of your own. See {@link LoadSignalsOptions}.
58
- */
59
- loadSignals?: LoadSignalsOptions;
60
- /**
61
- * How far back the **autoscaling** decisions look, in seconds — the window the historical system status is
62
- * evaluated over, and therefore how much history the signals retain (the memory cost of raising it).
63
- * @default 30
64
- */
65
- snapshotHistorySecs?: number;
66
- /**
67
- * How far back the **task-gating** decision looks, in seconds — the window used to judge whether the system is
68
- * overloaded *right now*, before dispatching one more task. Deliberately shorter than
69
- * {@link ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`}, so that dispatch reacts to
70
- * spikes quickly while scaling stays stable.
71
- * @default 5
72
- */
73
- currentHistorySecs?: number;
74
- /**
75
- * The maximum number of tasks per minute the system can run.
76
- * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.
77
- */
78
- maxTasksPerMinute?: number;
79
- log?: CrawleeLogger;
80
- }
81
- /**
82
- * Identifies *who* is asking a governor for capacity: one {@link AutoscaledPool}, or the crawler driving it. The
83
- * same object is passed on every call a pool makes, so per-consumer state can be keyed off it or off its `id`.
84
- * @category Scaling
85
- */
86
- export interface ConcurrencyConsumer {
87
- /** Process-unique and human-readable — a crawler's is its {@link BasicCrawlerOptions.id|`id`} option. */
88
- readonly id: string;
89
- }
90
- /**
91
- * The contract between an {@link AutoscaledPool} and its concurrency "governor" — the object that answers *is
92
- * there free compute for one more task?* and tracks the budget that tasks are booked against.
93
- * {@link ConcurrencySystem} is the canonical implementation; the interface lets alternate governors be substituted
94
- * without depending on its internals.
95
- *
96
- * Every allocation method is told which {@link ConcurrencyConsumer|consumer} is asking, so an implementation can
97
- * allocate per consumer. {@link ConcurrencySystem} does not: it serves whoever asks first, which can starve a pool
98
- * that joins a saturated system late.
99
- * @category Scaling
100
- */
101
- export interface IConcurrencySystem {
102
- /**
103
- * The number of tasks that should currently be running in parallel, assuming a sufficient supply of them. How it
104
- * is derived is up to the implementation, hence read-only here — but it must always be at least `1`, or a pool
105
- * could never start the first task.
106
- */
107
- readonly desiredConcurrency: number;
108
- /** The number of parallel tasks currently booked against this governor, regardless of which pool booked them. */
109
- readonly currentConcurrency: number;
110
- /**
111
- * Whether the governor is ready to be booked against. {@link AutoscaledPool.run|`pool.run()`} refuses to run
112
- * when this is `false`. An implementation with no startup lifecycle simply reports `true`.
113
- */
114
- readonly isRunning: boolean;
115
- /**
116
- * May **one more** task start right now, on behalf of `consumer`? A cheap pre-check the pool consults before
117
- * querying task readiness.
118
- *
119
- * Must **not** enforce rate limits that only make sense for ready tasks (e.g. a per-minute task cap): the pool
120
- * calls this before knowing whether any task is ready, so refusing here would stall an already-empty queue.
121
- *
122
- * Must also return `true` whenever `consumer` has nothing in flight of its own. A `false` sends that pool straight
123
- * to its finished-check **without** consulting `isTaskReadyFunction`, so a governor that starves an idle pool can
124
- * make its `run()` resolve while work is still pending. Tracking bookings per consumer answers that directly;
125
- * {@link ConcurrencySystem}, which does not, instead never refuses while
126
- * {@link IConcurrencySystem.currentConcurrency|`currentConcurrency`} is `0`.
127
- */
128
- hasCapacityForTask(consumer: ConcurrencyConsumer): boolean;
129
- /**
130
- * Books a task against the budget for `consumer`, returning `false` (without booking) when there is no room — the
131
- * budget is spent, the consumer is over its share, or an implementation-specific rate limit was reached.
132
- *
133
- * Must be an *atomic* (synchronous) check-and-book: several pools may share one governor, and a check separated
134
- * from the booking by an `await` lets two of them claim the last free slot at once.
135
- */
136
- tryRegisterTaskStart(consumer: ConcurrencyConsumer): boolean;
137
- /** Returns a task's slot to `consumer`'s budget. Called once the task settles (resolve or reject). */
138
- registerTaskEnd(consumer: ConcurrencyConsumer): void;
139
- }
140
- /**
141
- * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
142
- * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
143
- * over time.
144
- *
145
- * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
146
- * of letting each scale independently and oversubscribe the machine.
147
- *
148
- * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
149
- * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
150
- * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
151
- * system down for every borrower.
152
- * @category Scaling
153
- */
154
- export declare class ConcurrencySystem implements IConcurrencySystem {
155
- #private;
156
- private readonly log;
157
- private readonly desiredConcurrencyRatio;
158
- private readonly scaleUpStepRatio;
159
- private readonly scaleDownStepRatio;
160
- private readonly maxTasksPerMinute;
161
- private _currentConcurrency;
162
- private readonly snapshotter;
163
- private readonly systemStatus;
164
- constructor(options?: ConcurrencySystemOptions);
165
- /**
166
- * Gets the minimum number of tasks running in parallel.
167
- */
168
- get minConcurrency(): number;
169
- /**
170
- * Sets the minimum number of tasks running in parallel.
171
- *
172
- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
173
- * If you're not sure, just keep the default value and the concurrency will scale up automatically.
174
- */
175
- set minConcurrency(value: number);
176
- /**
177
- * Gets the maximum number of tasks running in parallel.
178
- */
179
- get maxConcurrency(): number;
180
- /**
181
- * Sets the maximum number of tasks running in parallel. Lowering it below the current
182
- * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
183
- * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
184
- * limit as they settle).
185
- */
186
- set maxConcurrency(value: number);
187
- /**
188
- * Gets the desired concurrency for the system,
189
- * which is an estimated number of parallel tasks that the system can currently support.
190
- */
191
- get desiredConcurrency(): number;
192
- /**
193
- * Sets the desired concurrency for the system, i.e. the number of tasks that should be running
194
- * in parallel if there's large enough supply of tasks.
195
- */
196
- set desiredConcurrency(value: number);
197
- /**
198
- * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
199
- * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
200
- * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
201
- * that is the limit callers set in order to protect something.
202
- */
203
- private clampDesiredConcurrency;
204
- get currentConcurrency(): number;
205
- /** Whether the system is currently monitoring load and autoscaling the budget. */
206
- get isRunning(): boolean;
207
- /**
208
- * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
209
- * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
210
- * signal fails to start.
211
- */
212
- start(): Promise<void>;
213
- private boot;
214
- /**
215
- * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
216
- */
217
- stop(): Promise<void>;
218
- private shutDown;
219
- /**
220
- * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
221
- * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
222
- * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
223
- * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
224
- */
225
- private warnIfNotRunning;
226
- /**
227
- * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
228
- * reached) or when the machine is overloaded past `minConcurrency`.
229
- *
230
- * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
231
- * interface, letting the answer be queried directly.
232
- */
233
- hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean;
234
- /** Whether the per-minute task cap has been reached. */
235
- private get isOverMaxRequestLimit();
236
- /**
237
- * Atomically books a task against the shared budget: re-checks
238
- * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
239
- * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
240
- * room. Call right before the task actually runs.
241
- *
242
- * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
243
- * extra minute.
244
- */
245
- tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean;
246
- /** Returns a slot to the shared budget, whoever booked it. */
247
- registerTaskEnd(_consumer?: ConcurrencyConsumer): void;
248
- /**
249
- * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
250
- * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
251
- * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
252
- */
253
- getCurrentStatus(): SystemInfo;
254
- /**
255
- * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
256
- * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
257
- */
258
- private autoscale;
259
- /**
260
- * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
261
- */
262
- private scaleUp;
263
- /**
264
- * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
265
- */
266
- private scaleDown;
267
- private incrementTasksDonePerSecond;
268
- }