@crawlee/basic 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 (78) hide show
  1. package/README.md +1 -1
  2. package/index.d.ts +11 -1
  3. package/index.js +11 -0
  4. package/internals/autoscaling/autoscaled_pool.d.ts +178 -0
  5. package/internals/autoscaling/autoscaled_pool.js +387 -0
  6. package/internals/autoscaling/concurrency_system.d.ts +235 -0
  7. package/internals/autoscaling/concurrency_system.js +357 -0
  8. package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/internals/autoscaling/cpu_load_signal.js +46 -0
  10. package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/internals/autoscaling/event_loop_load_signal.js +60 -0
  12. package/internals/autoscaling/index.d.ts +9 -0
  13. package/internals/autoscaling/index.js +9 -0
  14. package/internals/autoscaling/load_signal.d.ts +98 -0
  15. package/internals/autoscaling/load_signal.js +103 -0
  16. package/internals/autoscaling/memory_load_signal.d.ts +45 -0
  17. package/internals/autoscaling/memory_load_signal.js +104 -0
  18. package/internals/autoscaling/snapshotter.d.ts +84 -0
  19. package/internals/autoscaling/snapshotter.js +67 -0
  20. package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
  21. package/internals/autoscaling/storage_backend_load_signal.js +73 -0
  22. package/internals/autoscaling/system_status.d.ts +112 -0
  23. package/internals/autoscaling/system_status.js +139 -0
  24. package/internals/autoscaling/weighted_avg.d.ts +5 -0
  25. package/internals/autoscaling/weighted_avg.js +14 -0
  26. package/internals/basic-crawler.d.ts +77 -310
  27. package/internals/basic-crawler.js +680 -564
  28. package/internals/cookie_utils.d.ts +40 -0
  29. package/internals/cookie_utils.js +122 -0
  30. package/internals/crawler-run.d.ts +76 -0
  31. package/internals/crawler-run.js +142 -0
  32. package/internals/crawlers/context_pipeline.d.ts +75 -0
  33. package/internals/crawlers/context_pipeline.js +109 -0
  34. package/internals/crawlers/crawler_commons.d.ts +216 -0
  35. package/internals/crawlers/crawler_commons.js +1 -0
  36. package/internals/crawlers/error_snapshotter.d.ts +29 -0
  37. package/internals/crawlers/error_snapshotter.js +116 -0
  38. package/internals/crawlers/error_tracker.d.ts +51 -0
  39. package/internals/crawlers/error_tracker.js +316 -0
  40. package/internals/crawlers/index.d.ts +4 -0
  41. package/internals/crawlers/index.js +3 -0
  42. package/internals/crawlers/internals/types.d.ts +7 -0
  43. package/internals/crawlers/internals/types.js +1 -0
  44. package/internals/crawlers/statistics.d.ts +316 -0
  45. package/internals/crawlers/statistics.js +525 -0
  46. package/internals/crawling_request.d.ts +86 -0
  47. package/internals/crawling_request.js +127 -0
  48. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  49. package/internals/enqueue_links/enqueue_links.js +76 -0
  50. package/internals/enqueue_links/index.d.ts +3 -0
  51. package/internals/enqueue_links/index.js +3 -0
  52. package/internals/enqueue_links/shared.d.ts +106 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +68 -0
  55. package/internals/errors.js +83 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +6 -0
  59. package/internals/request-timeout.js +27 -2
  60. package/internals/router.d.ts +299 -0
  61. package/internals/router.js +312 -0
  62. package/internals/session_pool/consts.d.ts +1 -0
  63. package/internals/session_pool/consts.js +1 -0
  64. package/internals/session_pool/errors.d.ts +7 -0
  65. package/internals/session_pool/errors.js +11 -0
  66. package/internals/session_pool/fingerprint.d.ts +9 -0
  67. package/internals/session_pool/fingerprint.js +30 -0
  68. package/internals/session_pool/index.d.ts +4 -0
  69. package/internals/session_pool/index.js +4 -0
  70. package/internals/session_pool/session.d.ts +151 -0
  71. package/internals/session_pool/session.js +225 -0
  72. package/internals/session_pool/session_pool.d.ts +193 -0
  73. package/internals/session_pool/session_pool.js +453 -0
  74. package/internals/sitemap_request_loader.d.ts +158 -0
  75. package/internals/sitemap_request_loader.js +432 -0
  76. package/internals/throttling_request_manager.d.ts +229 -0
  77. package/internals/throttling_request_manager.js +843 -0
  78. package/package.json +16 -12
@@ -0,0 +1,235 @@
1
+ import type { CrawleeLogger, SystemInfo } from '@crawlee/core';
2
+ import type { LoadSignalsOptions } from './snapshotter.js';
3
+ export interface ConcurrencySystemOptions {
4
+ /**
5
+ * The minimum number of tasks running in parallel.
6
+ *
7
+ * *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.
8
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
9
+ * @default 1
10
+ */
11
+ minConcurrency?: number;
12
+ /**
13
+ * The maximum number of tasks running in parallel.
14
+ * @default 200
15
+ */
16
+ maxConcurrency?: number;
17
+ /**
18
+ * The desired number of tasks that should be running parallel on the start of the pool,
19
+ * if there is a large enough supply of them.
20
+ * By default, it is `minConcurrency`.
21
+ */
22
+ desiredConcurrency?: number;
23
+ /**
24
+ * Minimum level of desired concurrency to reach before more scaling up is allowed.
25
+ * @default 0.90
26
+ */
27
+ desiredConcurrencyRatio?: number;
28
+ /**
29
+ * Defines the fractional amount of desired concurrency to be added with each scaling up.
30
+ * The minimum scaling step is one.
31
+ * @default 0.05
32
+ */
33
+ scaleUpStepRatio?: number;
34
+ /**
35
+ * Defines the amount of desired concurrency to be subtracted with each scaling down.
36
+ * The minimum scaling step is one.
37
+ * @default 0.05
38
+ */
39
+ scaleDownStepRatio?: number;
40
+ /**
41
+ * Specifies a period in which the instance logs its state, in seconds.
42
+ * Set to `null` to disable periodic logging.
43
+ * @default 60
44
+ */
45
+ loggingIntervalSecs?: number | null;
46
+ /**
47
+ * Defines in seconds how often the system should attempt to adjust the desired concurrency
48
+ * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.
49
+ * We suggest using a value from 5 to 20.
50
+ * @default 10
51
+ */
52
+ autoscaleIntervalSecs?: number;
53
+ /**
54
+ * The signals that tell the system whether the machine is overloaded: per-resource tuning for the built-in four
55
+ * (memory, event loop, CPU, storage backend) plus any {@link LoadSignalsOptions.custom|`custom`}
56
+ * implementations of your own. See {@link LoadSignalsOptions}.
57
+ */
58
+ loadSignals?: LoadSignalsOptions;
59
+ /**
60
+ * How far back the **autoscaling** decisions look, in seconds — the window the historical system status is
61
+ * evaluated over, and therefore how much history the signals retain (the memory cost of raising it).
62
+ * @default 30
63
+ */
64
+ snapshotHistorySecs?: number;
65
+ /**
66
+ * How far back the **task-gating** decision looks, in seconds — the window used to judge whether the system is
67
+ * overloaded *right now*, before dispatching one more task. Deliberately shorter than
68
+ * {@link ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`}, so that dispatch reacts to
69
+ * spikes quickly while scaling stays stable.
70
+ * @default 5
71
+ */
72
+ currentHistorySecs?: number;
73
+ /**
74
+ * The maximum number of tasks per minute the system can run.
75
+ * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.
76
+ */
77
+ maxTasksPerMinute?: number;
78
+ log?: CrawleeLogger;
79
+ }
80
+ /**
81
+ * Identifies *who* is asking a governor for capacity: one {@link AutoscaledPool}, or the crawler driving it. The
82
+ * same object is passed on every call a pool makes, so per-consumer state can be keyed off it or off its `id`.
83
+ * @category Scaling
84
+ */
85
+ export interface ConcurrencyConsumer {
86
+ /** Process-unique and human-readable — a crawler's is its {@link BasicCrawlerOptions.id|`id`} option. */
87
+ readonly id: string;
88
+ }
89
+ /**
90
+ * The contract between an {@link AutoscaledPool} and its concurrency "governor" — the object that answers *is
91
+ * there free compute for one more task?* and tracks the budget that tasks are booked against.
92
+ * {@link ConcurrencySystem} is the canonical implementation; the interface lets alternate governors be substituted
93
+ * without depending on its internals.
94
+ *
95
+ * Every allocation method is told which {@link ConcurrencyConsumer|consumer} is asking, so an implementation can
96
+ * allocate per consumer. {@link ConcurrencySystem} does not: it serves whoever asks first, which can starve a pool
97
+ * that joins a saturated system late.
98
+ * @category Scaling
99
+ */
100
+ export interface IConcurrencySystem {
101
+ /**
102
+ * The number of tasks that should currently be running in parallel, assuming a sufficient supply of them. How it
103
+ * is derived is up to the implementation, hence read-only here — but it must always be at least `1`, or a pool
104
+ * could never start the first task.
105
+ */
106
+ readonly desiredConcurrency: number;
107
+ /** The number of parallel tasks currently booked against this governor, regardless of which pool booked them. */
108
+ readonly currentConcurrency: number;
109
+ /**
110
+ * Whether the governor is ready to be booked against. {@link AutoscaledPool.run|`pool.run()`} refuses to run
111
+ * when this is `false`. An implementation with no startup lifecycle simply reports `true`.
112
+ */
113
+ readonly isRunning: boolean;
114
+ /**
115
+ * May **one more** task start right now, on behalf of `consumer`? A cheap pre-check the pool consults before
116
+ * querying task readiness.
117
+ *
118
+ * Must **not** enforce rate limits that only make sense for ready tasks (e.g. a per-minute task cap): the pool
119
+ * calls this before knowing whether any task is ready, so refusing here would stall an already-empty queue.
120
+ *
121
+ * Must also return `true` whenever `consumer` has nothing in flight of its own. A `false` sends that pool straight
122
+ * to its finished-check **without** consulting `isTaskReadyFunction`, so a governor that starves an idle pool can
123
+ * make its `run()` resolve while work is still pending. Tracking bookings per consumer answers that directly;
124
+ * {@link ConcurrencySystem}, which does not, instead never refuses while
125
+ * {@link IConcurrencySystem.currentConcurrency|`currentConcurrency`} is `0`.
126
+ */
127
+ hasCapacityForTask(consumer: ConcurrencyConsumer): boolean;
128
+ /**
129
+ * Books a task against the budget for `consumer`, returning `false` (without booking) when there is no room — the
130
+ * budget is spent, the consumer is over its share, or an implementation-specific rate limit was reached.
131
+ *
132
+ * Must be an *atomic* (synchronous) check-and-book: several pools may share one governor, and a check separated
133
+ * from the booking by an `await` lets two of them claim the last free slot at once.
134
+ * @param taskId Identifies the booked task among the ones `consumer` has in flight, and is repeated by the
135
+ * {@link IConcurrencySystem.registerTaskEnd|release} — pairing the two is what lets an implementation time a
136
+ * task or tell which ones are still running. Nothing beyond that is promised: another consumer may be using the
137
+ * same id at the same time, and an id may come back around once its task has ended.
138
+ */
139
+ tryRegisterTaskStart(consumer: ConcurrencyConsumer, taskId: string): boolean;
140
+ /**
141
+ * Returns a task's slot to `consumer`'s budget. Called once the task settles (resolve or reject).
142
+ * @param taskId The id the task was {@link IConcurrencySystem.tryRegisterTaskStart|booked} under.
143
+ */
144
+ registerTaskEnd(consumer: ConcurrencyConsumer, taskId: string): void;
145
+ }
146
+ /**
147
+ * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
148
+ * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
149
+ * over time.
150
+ *
151
+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
152
+ * of letting each scale independently and oversubscribe the machine.
153
+ *
154
+ * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
155
+ * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
156
+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
157
+ * system down for every borrower.
158
+ * @category Scaling
159
+ */
160
+ export declare class ConcurrencySystem implements IConcurrencySystem {
161
+ #private;
162
+ /** The cap on tasks started per minute, or `Infinity` when uncapped. */
163
+ readonly maxTasksPerMinute: number;
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
+ * Read-only: the value is owned by the autoscaler, which recomputes it from the load signals on every tick.
192
+ * Tune the budget through `minConcurrency`/`maxConcurrency` instead.
193
+ */
194
+ get desiredConcurrency(): number;
195
+ get currentConcurrency(): number;
196
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
197
+ get isRunning(): boolean;
198
+ /**
199
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
200
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
201
+ * signal fails to start.
202
+ */
203
+ start(): Promise<void>;
204
+ [Symbol.asyncDispose](): Promise<void>;
205
+ /**
206
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
207
+ */
208
+ stop(): Promise<void>;
209
+ /**
210
+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
211
+ * reached) or when the machine is overloaded past `minConcurrency`.
212
+ *
213
+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
214
+ * interface, letting the answer be queried directly.
215
+ */
216
+ hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean;
217
+ /**
218
+ * Atomically books a task against the shared budget: re-checks
219
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
220
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
221
+ * room. Call right before the task actually runs.
222
+ *
223
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
224
+ * extra minute.
225
+ */
226
+ tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean;
227
+ /** Returns a slot to the shared budget, whoever booked it. */
228
+ registerTaskEnd(_consumer?: ConcurrencyConsumer): void;
229
+ /**
230
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
231
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
232
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
233
+ */
234
+ getCurrentStatus(): SystemInfo;
235
+ }
@@ -0,0 +1,357 @@
1
+ import { serviceLocator, validators } from '@crawlee/core';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { betterClearInterval, betterSetInterval } from '@apify/utilities';
5
+ import { Snapshotter } from './snapshotter.js';
6
+ import { SystemStatus } from './system_status.js';
7
+ const concurrencySchema = z.number().int().gte(1).optional();
8
+ // `schemas.anyObject` passes values through by reference, so the load signal instances inside
9
+ // `loadSignals` and class instances like loggers keep their prototype.
10
+ const concurrencySystemOptionsSchema = z.strictObject({
11
+ maxConcurrency: z.number().int().gte(1).default(200),
12
+ minConcurrency: z.number().int().gte(1).default(1),
13
+ desiredConcurrency: z.number().int().gte(1).optional(),
14
+ desiredConcurrencyRatio: z.number().gt(0).lt(1).default(0.9),
15
+ scaleUpStepRatio: z.number().gt(0).lt(1).default(0.05),
16
+ scaleDownStepRatio: z.number().gt(0).lt(1).default(0.05),
17
+ loggingIntervalSecs: schemas.anyNumber
18
+ .refine((value) => value > 0, 'Expected a number greater than 0')
19
+ .nullish()
20
+ .default(60),
21
+ autoscaleIntervalSecs: schemas.anyNumber
22
+ .refine((value) => value > 0, 'Expected a number greater than 0')
23
+ .default(10),
24
+ loadSignals: schemas.anyObject.default(() => ({})),
25
+ snapshotHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
26
+ currentHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
27
+ log: validators.logger.default(() => serviceLocator.getLogger()),
28
+ maxTasksPerMinute: z
29
+ .union([z.number().int().gte(1), z.literal(Number.POSITIVE_INFINITY)])
30
+ .default(Number.POSITIVE_INFINITY),
31
+ });
32
+ /**
33
+ * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
34
+ * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
35
+ * over time.
36
+ *
37
+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
38
+ * of letting each scale independently and oversubscribe the machine.
39
+ *
40
+ * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
41
+ * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
42
+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
43
+ * system down for every borrower.
44
+ * @category Scaling
45
+ */
46
+ export class ConcurrencySystem {
47
+ #log;
48
+ #desiredConcurrencyRatio;
49
+ #scaleUpStepRatio;
50
+ #scaleDownStepRatio;
51
+ #loggingIntervalMillis;
52
+ #autoscaleIntervalMillis;
53
+ /** The cap on tasks started per minute, or `Infinity` when uncapped. */
54
+ maxTasksPerMinute;
55
+ #minConcurrency;
56
+ #maxConcurrency;
57
+ #desiredConcurrency;
58
+ #currentConcurrency = 0;
59
+ #lastLoggingTime;
60
+ #tasksPerMinute = Array.from({ length: 60 }, () => 0);
61
+ #snapshotter;
62
+ #loadSignals;
63
+ #systemStatus;
64
+ #autoscaleInterval;
65
+ #tasksDonePerSecondInterval;
66
+ /** Whether the snapshotter and autoscaling intervals are currently running. */
67
+ #running = false;
68
+ /** The in-flight (or completed) startup, memoized so concurrent `start()` calls await one boot. */
69
+ #startPromise;
70
+ /** Set once per session, so a pool outliving `stop()` is reported once rather than every half second. */
71
+ #warnedAboutQueryWhileStopped = false;
72
+ constructor(options = {}) {
73
+ const { maxConcurrency, minConcurrency, desiredConcurrency, desiredConcurrencyRatio, scaleUpStepRatio, scaleDownStepRatio, loggingIntervalSecs, autoscaleIntervalSecs, loadSignals, snapshotHistorySecs, currentHistorySecs, log, maxTasksPerMinute, } = parseArgument(options, concurrencySystemOptionsSchema, 'ConcurrencySystemOptions');
74
+ this.#log = log.child({ prefix: 'ConcurrencySystem' });
75
+ this.#desiredConcurrencyRatio = desiredConcurrencyRatio;
76
+ this.#scaleUpStepRatio = scaleUpStepRatio;
77
+ this.#scaleDownStepRatio = scaleDownStepRatio;
78
+ this.#loggingIntervalMillis = (loggingIntervalSecs ?? 0) * 1000;
79
+ this.#autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;
80
+ this.maxTasksPerMinute = maxTasksPerMinute;
81
+ this.#minConcurrency = minConcurrency;
82
+ this.#maxConcurrency = maxConcurrency;
83
+ this.#desiredConcurrency = desiredConcurrency ?? minConcurrency;
84
+ this.#clampDesiredConcurrency();
85
+ // The built-in signals are collected by the snapshotter; custom ones are simply evaluated alongside them.
86
+ const { custom: customLoadSignals = [], ...builtinSignalOptions } = loadSignals;
87
+ this.#snapshotter = new Snapshotter(builtinSignalOptions);
88
+ this.#loadSignals = customLoadSignals;
89
+ this.#systemStatus = new SystemStatus({
90
+ snapshotter: this.#snapshotter,
91
+ loadSignals: customLoadSignals,
92
+ currentHistorySecs,
93
+ // Both windows are requested from the signals explicitly, so a signal's own retention can neither widen
94
+ // nor (given the start context below) narrow what it contributes.
95
+ historySecs: snapshotHistorySecs,
96
+ });
97
+ }
98
+ /**
99
+ * Gets the minimum number of tasks running in parallel.
100
+ */
101
+ get minConcurrency() {
102
+ return this.#minConcurrency;
103
+ }
104
+ /**
105
+ * Sets the minimum number of tasks running in parallel.
106
+ *
107
+ * *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.
108
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
109
+ */
110
+ set minConcurrency(value) {
111
+ parseArgument(value, concurrencySchema);
112
+ this.#minConcurrency = value;
113
+ this.#clampDesiredConcurrency();
114
+ }
115
+ /**
116
+ * Gets the maximum number of tasks running in parallel.
117
+ */
118
+ get maxConcurrency() {
119
+ return this.#maxConcurrency;
120
+ }
121
+ /**
122
+ * Sets the maximum number of tasks running in parallel. Lowering it below the current
123
+ * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
124
+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
125
+ * limit as they settle).
126
+ */
127
+ set maxConcurrency(value) {
128
+ parseArgument(value, concurrencySchema);
129
+ this.#maxConcurrency = value;
130
+ this.#clampDesiredConcurrency();
131
+ }
132
+ /**
133
+ * Gets the desired concurrency for the system,
134
+ * which is an estimated number of parallel tasks that the system can currently support.
135
+ *
136
+ * Read-only: the value is owned by the autoscaler, which recomputes it from the load signals on every tick.
137
+ * Tune the budget through `minConcurrency`/`maxConcurrency` instead.
138
+ */
139
+ get desiredConcurrency() {
140
+ return this.#desiredConcurrency;
141
+ }
142
+ /**
143
+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
144
+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
145
+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
146
+ * that is the limit callers set in order to protect something.
147
+ */
148
+ #clampDesiredConcurrency() {
149
+ const atLeastMin = Math.max(this.#desiredConcurrency, this.#minConcurrency);
150
+ this.#desiredConcurrency = Math.min(atLeastMin, this.#maxConcurrency);
151
+ }
152
+ get currentConcurrency() {
153
+ return this.#currentConcurrency;
154
+ }
155
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
156
+ get isRunning() {
157
+ return this.#running;
158
+ }
159
+ /**
160
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
161
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
162
+ * signal fails to start.
163
+ */
164
+ async start() {
165
+ // Unwound and dropped again on failure, so a later `start()` retries instead of resolving instantly against
166
+ // a system that is down.
167
+ this.#startPromise ??= this.#boot().catch(async (error) => {
168
+ this.#startPromise = undefined;
169
+ await this.#shutDown();
170
+ throw error;
171
+ });
172
+ await this.#startPromise;
173
+ }
174
+ async #boot() {
175
+ // Per-session measurement state, reset so a restarted system isn't judged on the previous session. The
176
+ // per-minute window matters most: its ageing interval is cleared while we are down, so starts from before an
177
+ // arbitrarily long stop would otherwise still count against "this minute" and trip the cap immediately.
178
+ this.#tasksPerMinute = Array.from({ length: 60 }, () => 0);
179
+ this.#lastLoggingTime = undefined;
180
+ this.#warnedAboutQueryWhileStopped = false;
181
+ // Signals are told how much history to keep when they start: exactly the longest window they will be sampled
182
+ // over, so nobody has to guess a retention value that matches this system's configuration.
183
+ const startContext = { maxSampleWindowMillis: this.#systemStatus.maxSampleWindowMillis };
184
+ await this.#snapshotter.start(startContext);
185
+ await Promise.all(this.#loadSignals.map(async (s) => s.start(startContext)));
186
+ this.#autoscaleInterval = betterSetInterval((cb) => this.#autoscale(cb), this.#autoscaleIntervalMillis);
187
+ if (this.maxTasksPerMinute !== Infinity) {
188
+ this.#tasksDonePerSecondInterval = betterSetInterval((cb) => this.#incrementTasksDonePerSecond(cb), 1000);
189
+ }
190
+ // Last, so `isRunning` never claims a system whose signals aren't collecting yet.
191
+ this.#running = true;
192
+ }
193
+ async [Symbol.asyncDispose]() {
194
+ await this.stop();
195
+ }
196
+ /**
197
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
198
+ */
199
+ async stop() {
200
+ if (this.#startPromise === undefined) {
201
+ return;
202
+ }
203
+ // Waited out rather than interrupted, or the intervals a starting signal is about to register outlive us.
204
+ await this.#startPromise.catch(() => { });
205
+ this.#startPromise = undefined;
206
+ this.#running = false;
207
+ await this.#shutDown();
208
+ }
209
+ async #shutDown() {
210
+ if (this.#autoscaleInterval)
211
+ betterClearInterval(this.#autoscaleInterval);
212
+ if (this.#tasksDonePerSecondInterval)
213
+ betterClearInterval(this.#tasksDonePerSecondInterval);
214
+ await this.#snapshotter.stop();
215
+ await Promise.all(this.#loadSignals.map(async (s) => s.stop()));
216
+ }
217
+ /**
218
+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
219
+ * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
220
+ * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
221
+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
222
+ */
223
+ #warnIfNotRunning() {
224
+ if (this.#running || this.#warnedAboutQueryWhileStopped) {
225
+ return;
226
+ }
227
+ this.#warnedAboutQueryWhileStopped = true;
228
+ this.#log.warning('Capacity is being queried on a ConcurrencySystem that is not running, so system load is no longer being ' +
229
+ 'monitored and the concurrency will no longer be adjusted. Whoever creates a ConcurrencySystem owns ' +
230
+ 'its lifecycle: call `await concurrencySystem.stop()` only once every pool and crawler borrowing it ' +
231
+ 'has finished.');
232
+ }
233
+ /**
234
+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
235
+ * reached) or when the machine is overloaded past `minConcurrency`.
236
+ *
237
+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
238
+ * interface, letting the answer be queried directly.
239
+ */
240
+ hasCapacityForTask(_consumer) {
241
+ this.#warnIfNotRunning();
242
+ if (this.#currentConcurrency >= this.#desiredConcurrency) {
243
+ this.#log.perf('Task will not run. Desired concurrency achieved.');
244
+ return false;
245
+ }
246
+ const currentStatus = this.#systemStatus.getCurrentStatus();
247
+ const { isSystemIdle } = currentStatus;
248
+ if (!isSystemIdle && this.#currentConcurrency >= this.#minConcurrency) {
249
+ this.#log.perf('Task will not be run. System is overloaded.', currentStatus);
250
+ return false;
251
+ }
252
+ return true;
253
+ }
254
+ /** Whether the per-minute task cap has been reached. */
255
+ get #isOverMaxRequestLimit() {
256
+ if (this.maxTasksPerMinute === Infinity) {
257
+ return false;
258
+ }
259
+ return this.#tasksPerMinute.reduce((acc, curr) => acc + curr, 0) >= this.maxTasksPerMinute;
260
+ }
261
+ /**
262
+ * Atomically books a task against the shared budget: re-checks
263
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
264
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
265
+ * room. Call right before the task actually runs.
266
+ *
267
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
268
+ * extra minute.
269
+ */
270
+ tryRegisterTaskStart(consumer) {
271
+ if (!this.hasCapacityForTask(consumer)) {
272
+ return false;
273
+ }
274
+ if (this.#isOverMaxRequestLimit) {
275
+ this.#log.perf('Task will not run. Maximum tasks per minute reached.');
276
+ return false;
277
+ }
278
+ this.#currentConcurrency++;
279
+ this.#tasksPerMinute[0]++;
280
+ return true;
281
+ }
282
+ /** Returns a slot to the shared budget, whoever booked it. */
283
+ registerTaskEnd(_consumer) {
284
+ this.#currentConcurrency--;
285
+ }
286
+ /**
287
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
288
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
289
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
290
+ */
291
+ getCurrentStatus() {
292
+ return this.#systemStatus.getCurrentStatus();
293
+ }
294
+ /**
295
+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
296
+ * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
297
+ */
298
+ #autoscale(intervalCallback) {
299
+ if (this.#isOverMaxRequestLimit)
300
+ return intervalCallback();
301
+ const systemStatus = this.#systemStatus.getHistoricalStatus();
302
+ const { isSystemIdle } = systemStatus;
303
+ const weAreNotAtMax = this.#desiredConcurrency < this.#maxConcurrency;
304
+ const minCurrentConcurrency = Math.floor(this.#desiredConcurrency * this.#desiredConcurrencyRatio);
305
+ const weAreReachingDesiredConcurrency = this.#currentConcurrency >= minCurrentConcurrency;
306
+ if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency)
307
+ this.#scaleUp(systemStatus);
308
+ const isSystemOverloaded = !isSystemIdle;
309
+ const weAreNotAtMin = this.#desiredConcurrency > this.#minConcurrency;
310
+ if (isSystemOverloaded && weAreNotAtMin)
311
+ this.#scaleDown(systemStatus);
312
+ if (this.#loggingIntervalMillis > 0) {
313
+ const now = Date.now();
314
+ if (this.#lastLoggingTime == null) {
315
+ this.#lastLoggingTime = now;
316
+ }
317
+ else if (now > this.#lastLoggingTime + this.#loggingIntervalMillis) {
318
+ this.#lastLoggingTime = now;
319
+ this.#log.info('state', {
320
+ currentConcurrency: this.#currentConcurrency,
321
+ desiredConcurrency: this.#desiredConcurrency,
322
+ systemStatus,
323
+ });
324
+ }
325
+ }
326
+ return intervalCallback();
327
+ }
328
+ /**
329
+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
330
+ */
331
+ #scaleUp(systemStatus) {
332
+ const step = Math.ceil(this.#desiredConcurrency * this.#scaleUpStepRatio);
333
+ this.#desiredConcurrency = Math.min(this.#maxConcurrency, this.#desiredConcurrency + step);
334
+ this.#log.debug('scaling up', {
335
+ oldConcurrency: this.#desiredConcurrency - step,
336
+ newConcurrency: this.#desiredConcurrency,
337
+ systemStatus,
338
+ });
339
+ }
340
+ /**
341
+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
342
+ */
343
+ #scaleDown(systemStatus) {
344
+ const step = Math.ceil(this.#desiredConcurrency * this.#scaleDownStepRatio);
345
+ this.#desiredConcurrency = Math.max(this.#minConcurrency, this.#desiredConcurrency - step);
346
+ this.#log.debug('scaling down', {
347
+ oldConcurrency: this.#desiredConcurrency + step,
348
+ newConcurrency: this.#desiredConcurrency,
349
+ systemStatus,
350
+ });
351
+ }
352
+ #incrementTasksDonePerSecond(intervalCallback) {
353
+ this.#tasksPerMinute.unshift(0);
354
+ this.#tasksPerMinute.pop();
355
+ return intervalCallback();
356
+ }
357
+ }
@@ -0,0 +1,43 @@
1
+ import type { SystemInfo } from '@crawlee/core';
2
+ import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
3
+ /**
4
+ * A snapshot produced by the built-in CPU signal.
5
+ * @internal
6
+ */
7
+ export interface CpuSnapshot extends LoadSnapshot {
8
+ usedRatio: number;
9
+ ticks?: {
10
+ idle: number;
11
+ total: number;
12
+ };
13
+ }
14
+ /**
15
+ * Tuning for the built-in **CPU** load signal, as accepted both by {@link CpuLoadSignal} and by the
16
+ * {@link LoadSignalsOptions.cpu|`cpu`} shorthand on {@link LoadSignalsOptions}.
17
+ */
18
+ export interface CpuLoadSignalOptions {
19
+ /**
20
+ * Maximum ratio of overloaded snapshots in a sample before the CPU counts as overloaded.
21
+ * @default 0.4
22
+ */
23
+ overloadedRatio?: number;
24
+ }
25
+ /**
26
+ * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when the platform or local OS metrics indicate the
27
+ * CPU is overloaded.
28
+ *
29
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
30
+ *
31
+ * @category Scaling
32
+ */
33
+ export declare class CpuLoadSignal implements LoadSignal {
34
+ #private;
35
+ readonly name = "cpuInfo";
36
+ readonly overloadedRatio: number;
37
+ constructor(options?: CpuLoadSignalOptions);
38
+ start(context: LoadSignalStartContext): Promise<void>;
39
+ stop(): Promise<void>;
40
+ getSample(sampleDurationMillis?: number): LoadSnapshot[];
41
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
42
+ handle(systemInfo: SystemInfo): void;
43
+ }
@@ -0,0 +1,46 @@
1
+ import { EventType, serviceLocator } from '@crawlee/core';
2
+ import { SnapshotStore } from './load_signal.js';
3
+ /**
4
+ * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when the platform or local OS metrics indicate the
5
+ * CPU is overloaded.
6
+ *
7
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
8
+ *
9
+ * @category Scaling
10
+ */
11
+ export class CpuLoadSignal {
12
+ name = 'cpuInfo';
13
+ overloadedRatio;
14
+ #store = new SnapshotStore();
15
+ #events;
16
+ constructor(options = {}) {
17
+ this.overloadedRatio = options.overloadedRatio ?? 0.4;
18
+ this.handle = this.handle.bind(this);
19
+ }
20
+ async start(context) {
21
+ this.#store.useSampleWindow(context.maxSampleWindowMillis);
22
+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.
23
+ this.#store.clear();
24
+ // Resolved here rather than in the constructor, so an instance built ahead of time (to be wrapped, or shared
25
+ // between systems) cannot capture whichever event manager happened to be registered at that moment.
26
+ this.#events = serviceLocator.getEventManager();
27
+ this.#events.on(EventType.SYSTEM_INFO, this.handle);
28
+ }
29
+ async stop() {
30
+ this.#events?.off(EventType.SYSTEM_INFO, this.handle);
31
+ this.#events = undefined;
32
+ }
33
+ getSample(sampleDurationMillis) {
34
+ return this.#store.getSample(sampleDurationMillis);
35
+ }
36
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
37
+ handle(systemInfo) {
38
+ const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;
39
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
40
+ this.#store.push({
41
+ createdAt,
42
+ isOverloaded: isCpuOverloaded,
43
+ usedRatio: Math.ceil(cpuCurrentUsage / 100),
44
+ }, createdAt);
45
+ }
46
+ }