@crawlee/core 4.0.0-beta.88 → 4.0.0-beta.89

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.
@@ -0,0 +1,283 @@
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, client) plus any {@link LoadSignalsOptions.custom|`custom`} implementations of
57
+ * 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 readonly log;
156
+ private readonly desiredConcurrencyRatio;
157
+ private readonly scaleUpStepRatio;
158
+ private readonly scaleDownStepRatio;
159
+ private readonly loggingIntervalMillis;
160
+ private readonly autoscaleIntervalMillis;
161
+ private readonly maxTasksPerMinute;
162
+ private _minConcurrency;
163
+ private _maxConcurrency;
164
+ private _desiredConcurrency;
165
+ private _currentConcurrency;
166
+ private lastLoggingTime?;
167
+ private _tasksPerMinute;
168
+ private readonly snapshotter;
169
+ private readonly loadSignals;
170
+ private readonly systemStatus;
171
+ private autoscaleInterval?;
172
+ private tasksDonePerSecondInterval?;
173
+ /** Whether the snapshotter and autoscaling intervals are currently running. */
174
+ private running;
175
+ /** The in-flight (or completed) startup, memoized so concurrent `start()` calls await one boot. */
176
+ private startPromise?;
177
+ /** Set once per session, so a pool outliving `stop()` is reported once rather than every half second. */
178
+ private warnedAboutQueryWhileStopped;
179
+ constructor(options?: ConcurrencySystemOptions);
180
+ /**
181
+ * Gets the minimum number of tasks running in parallel.
182
+ */
183
+ get minConcurrency(): number;
184
+ /**
185
+ * Sets the minimum number of tasks running in parallel.
186
+ *
187
+ * *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.
188
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
189
+ */
190
+ set minConcurrency(value: number);
191
+ /**
192
+ * Gets the maximum number of tasks running in parallel.
193
+ */
194
+ get maxConcurrency(): number;
195
+ /**
196
+ * Sets the maximum number of tasks running in parallel. Lowering it below the current
197
+ * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
198
+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
199
+ * limit as they settle).
200
+ */
201
+ set maxConcurrency(value: number);
202
+ /**
203
+ * Gets the desired concurrency for the system,
204
+ * which is an estimated number of parallel tasks that the system can currently support.
205
+ */
206
+ get desiredConcurrency(): number;
207
+ /**
208
+ * Sets the desired concurrency for the system, i.e. the number of tasks that should be running
209
+ * in parallel if there's large enough supply of tasks.
210
+ */
211
+ set desiredConcurrency(value: number);
212
+ /**
213
+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
214
+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
215
+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
216
+ * that is the limit callers set in order to protect something.
217
+ */
218
+ private clampDesiredConcurrency;
219
+ get currentConcurrency(): number;
220
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
221
+ get isRunning(): boolean;
222
+ /**
223
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
224
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
225
+ * signal fails to start.
226
+ */
227
+ start(): Promise<void>;
228
+ private boot;
229
+ /**
230
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
231
+ */
232
+ stop(): Promise<void>;
233
+ private shutDown;
234
+ /**
235
+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
236
+ * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
237
+ * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
238
+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
239
+ */
240
+ private warnIfNotRunning;
241
+ /**
242
+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
243
+ * reached) or when the machine is overloaded past `minConcurrency`.
244
+ *
245
+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
246
+ * interface, letting the answer be queried directly.
247
+ */
248
+ hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean;
249
+ /** Whether the per-minute task cap has been reached. */
250
+ private get isOverMaxRequestLimit();
251
+ /**
252
+ * Atomically books a task against the shared budget: re-checks
253
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
254
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
255
+ * room. Call right before the task actually runs.
256
+ *
257
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
258
+ * extra minute.
259
+ */
260
+ tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean;
261
+ /** Returns a slot to the shared budget, whoever booked it. */
262
+ registerTaskEnd(_consumer?: ConcurrencyConsumer): void;
263
+ /**
264
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
265
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
266
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
267
+ */
268
+ getCurrentStatus(): SystemInfo;
269
+ /**
270
+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
271
+ * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
272
+ */
273
+ private _autoscale;
274
+ /**
275
+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
276
+ */
277
+ private _scaleUp;
278
+ /**
279
+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
280
+ */
281
+ private _scaleDown;
282
+ private _incrementTasksDonePerSecond;
283
+ }
@@ -0,0 +1,350 @@
1
+ import ow from 'ow';
2
+ import { betterClearInterval, betterSetInterval } from '@apify/utilities';
3
+ import { serviceLocator } from '../service_locator.js';
4
+ import { Snapshotter } from './snapshotter.js';
5
+ import { SystemStatus } from './system_status.js';
6
+ /**
7
+ * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
8
+ * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
9
+ * over time.
10
+ *
11
+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
12
+ * of letting each scale independently and oversubscribe the machine.
13
+ *
14
+ * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
15
+ * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
16
+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
17
+ * system down for every borrower.
18
+ * @category Scaling
19
+ */
20
+ export class ConcurrencySystem {
21
+ log;
22
+ desiredConcurrencyRatio;
23
+ scaleUpStepRatio;
24
+ scaleDownStepRatio;
25
+ loggingIntervalMillis;
26
+ autoscaleIntervalMillis;
27
+ maxTasksPerMinute;
28
+ _minConcurrency;
29
+ _maxConcurrency;
30
+ _desiredConcurrency;
31
+ _currentConcurrency = 0;
32
+ lastLoggingTime;
33
+ _tasksPerMinute = Array.from({ length: 60 }, () => 0);
34
+ snapshotter;
35
+ loadSignals;
36
+ systemStatus;
37
+ autoscaleInterval;
38
+ tasksDonePerSecondInterval;
39
+ /** Whether the snapshotter and autoscaling intervals are currently running. */
40
+ running = false;
41
+ /** The in-flight (or completed) startup, memoized so concurrent `start()` calls await one boot. */
42
+ startPromise;
43
+ /** Set once per session, so a pool outliving `stop()` is reported once rather than every half second. */
44
+ warnedAboutQueryWhileStopped = false;
45
+ constructor(options = {}) {
46
+ ow(options, ow.object.exactShape({
47
+ maxConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
48
+ minConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
49
+ desiredConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
50
+ desiredConcurrencyRatio: ow.optional.number.greaterThan(0).lessThan(1),
51
+ scaleUpStepRatio: ow.optional.number.greaterThan(0).lessThan(1),
52
+ scaleDownStepRatio: ow.optional.number.greaterThan(0).lessThan(1),
53
+ loggingIntervalSecs: ow.any(ow.number.greaterThan(0), ow.nullOrUndefined),
54
+ autoscaleIntervalSecs: ow.optional.number.greaterThan(0),
55
+ loadSignals: ow.optional.object,
56
+ snapshotHistorySecs: ow.optional.number.greaterThan(0),
57
+ currentHistorySecs: ow.optional.number.greaterThan(0),
58
+ log: ow.optional.object,
59
+ maxTasksPerMinute: ow.optional.number.integerOrInfinite.greaterThanOrEqual(1),
60
+ }));
61
+ const { maxConcurrency = 200, minConcurrency = 1, desiredConcurrency, desiredConcurrencyRatio = 0.9, scaleUpStepRatio = 0.05, scaleDownStepRatio = 0.05, loggingIntervalSecs = 60, autoscaleIntervalSecs = 10, loadSignals = {}, snapshotHistorySecs, currentHistorySecs, log = serviceLocator.getLogger(), maxTasksPerMinute = Infinity, } = options;
62
+ this.log = log.child({ prefix: 'ConcurrencySystem' });
63
+ this.desiredConcurrencyRatio = desiredConcurrencyRatio;
64
+ this.scaleUpStepRatio = scaleUpStepRatio;
65
+ this.scaleDownStepRatio = scaleDownStepRatio;
66
+ this.loggingIntervalMillis = (loggingIntervalSecs ?? 0) * 1000;
67
+ this.autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;
68
+ this.maxTasksPerMinute = maxTasksPerMinute;
69
+ this._minConcurrency = minConcurrency;
70
+ this._maxConcurrency = maxConcurrency;
71
+ this._desiredConcurrency = desiredConcurrency ?? minConcurrency;
72
+ this.clampDesiredConcurrency();
73
+ this._autoscale = this._autoscale.bind(this);
74
+ this._incrementTasksDonePerSecond = this._incrementTasksDonePerSecond.bind(this);
75
+ // The built-in signals are collected by the snapshotter; custom ones are simply evaluated alongside them.
76
+ const { custom: customLoadSignals = [], ...builtinSignalOptions } = loadSignals;
77
+ this.snapshotter = new Snapshotter(builtinSignalOptions);
78
+ this.loadSignals = customLoadSignals;
79
+ this.systemStatus = new SystemStatus({
80
+ snapshotter: this.snapshotter,
81
+ loadSignals: customLoadSignals,
82
+ currentHistorySecs,
83
+ // Both windows are requested from the signals explicitly, so a signal's own retention can neither widen
84
+ // nor (given the start context below) narrow what it contributes.
85
+ historySecs: snapshotHistorySecs,
86
+ });
87
+ }
88
+ /**
89
+ * Gets the minimum number of tasks running in parallel.
90
+ */
91
+ get minConcurrency() {
92
+ return this._minConcurrency;
93
+ }
94
+ /**
95
+ * Sets the minimum number of tasks running in parallel.
96
+ *
97
+ * *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.
98
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
99
+ */
100
+ set minConcurrency(value) {
101
+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
102
+ this._minConcurrency = value;
103
+ this.clampDesiredConcurrency();
104
+ }
105
+ /**
106
+ * Gets the maximum number of tasks running in parallel.
107
+ */
108
+ get maxConcurrency() {
109
+ return this._maxConcurrency;
110
+ }
111
+ /**
112
+ * Sets the maximum number of tasks running in parallel. Lowering it below the current
113
+ * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
114
+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
115
+ * limit as they settle).
116
+ */
117
+ set maxConcurrency(value) {
118
+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
119
+ this._maxConcurrency = value;
120
+ this.clampDesiredConcurrency();
121
+ }
122
+ /**
123
+ * Gets the desired concurrency for the system,
124
+ * which is an estimated number of parallel tasks that the system can currently support.
125
+ */
126
+ get desiredConcurrency() {
127
+ return this._desiredConcurrency;
128
+ }
129
+ /**
130
+ * Sets the desired concurrency for the system, i.e. the number of tasks that should be running
131
+ * in parallel if there's large enough supply of tasks.
132
+ */
133
+ set desiredConcurrency(value) {
134
+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
135
+ this._desiredConcurrency = value;
136
+ this.clampDesiredConcurrency();
137
+ }
138
+ /**
139
+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
140
+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
141
+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
142
+ * that is the limit callers set in order to protect something.
143
+ */
144
+ clampDesiredConcurrency() {
145
+ const atLeastMin = Math.max(this._desiredConcurrency, this._minConcurrency);
146
+ this._desiredConcurrency = Math.min(atLeastMin, this._maxConcurrency);
147
+ }
148
+ get currentConcurrency() {
149
+ return this._currentConcurrency;
150
+ }
151
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
152
+ get isRunning() {
153
+ return this.running;
154
+ }
155
+ /**
156
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
157
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
158
+ * signal fails to start.
159
+ */
160
+ async start() {
161
+ // Unwound and dropped again on failure, so a later `start()` retries instead of resolving instantly against
162
+ // a system that is down.
163
+ this.startPromise ??= this.boot().catch(async (error) => {
164
+ this.startPromise = undefined;
165
+ await this.shutDown();
166
+ throw error;
167
+ });
168
+ await this.startPromise;
169
+ }
170
+ async boot() {
171
+ // Per-session measurement state, reset so a restarted system isn't judged on the previous session. The
172
+ // per-minute window matters most: its ageing interval is cleared while we are down, so starts from before an
173
+ // arbitrarily long stop would otherwise still count against "this minute" and trip the cap immediately.
174
+ this._tasksPerMinute = Array.from({ length: 60 }, () => 0);
175
+ this.lastLoggingTime = undefined;
176
+ this.warnedAboutQueryWhileStopped = false;
177
+ // Signals are told how much history to keep when they start: exactly the longest window they will be sampled
178
+ // over, so nobody has to guess a retention value that matches this system's configuration.
179
+ const startContext = { maxSampleWindowMillis: this.systemStatus.maxSampleWindowMillis };
180
+ await this.snapshotter.start(startContext);
181
+ await Promise.all(this.loadSignals.map(async (s) => s.start(startContext)));
182
+ this.autoscaleInterval = betterSetInterval(this._autoscale, this.autoscaleIntervalMillis);
183
+ if (this.maxTasksPerMinute !== Infinity) {
184
+ this.tasksDonePerSecondInterval = betterSetInterval(this._incrementTasksDonePerSecond, 1000);
185
+ }
186
+ // Last, so `isRunning` never claims a system whose signals aren't collecting yet.
187
+ this.running = true;
188
+ }
189
+ /**
190
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
191
+ */
192
+ async stop() {
193
+ if (this.startPromise === undefined) {
194
+ return;
195
+ }
196
+ // Waited out rather than interrupted, or the intervals a starting signal is about to register outlive us.
197
+ await this.startPromise.catch(() => { });
198
+ this.startPromise = undefined;
199
+ this.running = false;
200
+ await this.shutDown();
201
+ }
202
+ async shutDown() {
203
+ if (this.autoscaleInterval)
204
+ betterClearInterval(this.autoscaleInterval);
205
+ if (this.tasksDonePerSecondInterval)
206
+ betterClearInterval(this.tasksDonePerSecondInterval);
207
+ await this.snapshotter.stop();
208
+ await Promise.all(this.loadSignals.map(async (s) => s.stop()));
209
+ }
210
+ /**
211
+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
212
+ * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
213
+ * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
214
+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
215
+ */
216
+ warnIfNotRunning() {
217
+ if (this.running || this.warnedAboutQueryWhileStopped) {
218
+ return;
219
+ }
220
+ this.warnedAboutQueryWhileStopped = true;
221
+ this.log.warning('Capacity is being queried on a ConcurrencySystem that is not running, so system load is no longer being ' +
222
+ 'monitored and the concurrency will no longer be adjusted. Whoever creates a ConcurrencySystem owns ' +
223
+ 'its lifecycle: call `await concurrencySystem.stop()` only once every pool and crawler borrowing it ' +
224
+ 'has finished.');
225
+ }
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) {
234
+ this.warnIfNotRunning();
235
+ if (this._currentConcurrency >= this._desiredConcurrency) {
236
+ this.log.perf('Task will not run. Desired concurrency achieved.');
237
+ return false;
238
+ }
239
+ const currentStatus = this.systemStatus.getCurrentStatus();
240
+ const { isSystemIdle } = currentStatus;
241
+ if (!isSystemIdle && this._currentConcurrency >= this._minConcurrency) {
242
+ this.log.perf('Task will not be run. System is overloaded.', currentStatus);
243
+ return false;
244
+ }
245
+ return true;
246
+ }
247
+ /** Whether the per-minute task cap has been reached. */
248
+ get isOverMaxRequestLimit() {
249
+ if (this.maxTasksPerMinute === Infinity) {
250
+ return false;
251
+ }
252
+ return this._tasksPerMinute.reduce((acc, curr) => acc + curr, 0) >= this.maxTasksPerMinute;
253
+ }
254
+ /**
255
+ * Atomically books a task against the shared budget: re-checks
256
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
257
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
258
+ * room. Call right before the task actually runs.
259
+ *
260
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
261
+ * extra minute.
262
+ */
263
+ tryRegisterTaskStart(consumer) {
264
+ if (!this.hasCapacityForTask(consumer)) {
265
+ return false;
266
+ }
267
+ if (this.isOverMaxRequestLimit) {
268
+ this.log.perf('Task will not run. Maximum tasks per minute reached.');
269
+ return false;
270
+ }
271
+ this._currentConcurrency++;
272
+ this._tasksPerMinute[0]++;
273
+ return true;
274
+ }
275
+ /** Returns a slot to the shared budget, whoever booked it. */
276
+ registerTaskEnd(_consumer) {
277
+ this._currentConcurrency--;
278
+ }
279
+ /**
280
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
281
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
282
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
283
+ */
284
+ getCurrentStatus() {
285
+ return this.systemStatus.getCurrentStatus();
286
+ }
287
+ /**
288
+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
289
+ * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
290
+ */
291
+ _autoscale(intervalCallback) {
292
+ if (this.isOverMaxRequestLimit)
293
+ return intervalCallback();
294
+ const systemStatus = this.systemStatus.getHistoricalStatus();
295
+ const { isSystemIdle } = systemStatus;
296
+ const weAreNotAtMax = this._desiredConcurrency < this._maxConcurrency;
297
+ const minCurrentConcurrency = Math.floor(this._desiredConcurrency * this.desiredConcurrencyRatio);
298
+ const weAreReachingDesiredConcurrency = this._currentConcurrency >= minCurrentConcurrency;
299
+ if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency)
300
+ this._scaleUp(systemStatus);
301
+ const isSystemOverloaded = !isSystemIdle;
302
+ const weAreNotAtMin = this._desiredConcurrency > this._minConcurrency;
303
+ if (isSystemOverloaded && weAreNotAtMin)
304
+ this._scaleDown(systemStatus);
305
+ if (this.loggingIntervalMillis > 0) {
306
+ const now = Date.now();
307
+ if (this.lastLoggingTime == null) {
308
+ this.lastLoggingTime = now;
309
+ }
310
+ else if (now > this.lastLoggingTime + this.loggingIntervalMillis) {
311
+ this.lastLoggingTime = now;
312
+ this.log.info('state', {
313
+ currentConcurrency: this._currentConcurrency,
314
+ desiredConcurrency: this._desiredConcurrency,
315
+ systemStatus,
316
+ });
317
+ }
318
+ }
319
+ return intervalCallback();
320
+ }
321
+ /**
322
+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
323
+ */
324
+ _scaleUp(systemStatus) {
325
+ const step = Math.ceil(this._desiredConcurrency * this.scaleUpStepRatio);
326
+ this._desiredConcurrency = Math.min(this._maxConcurrency, this._desiredConcurrency + step);
327
+ this.log.debug('scaling up', {
328
+ oldConcurrency: this._desiredConcurrency - step,
329
+ newConcurrency: this._desiredConcurrency,
330
+ systemStatus,
331
+ });
332
+ }
333
+ /**
334
+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
335
+ */
336
+ _scaleDown(systemStatus) {
337
+ const step = Math.ceil(this._desiredConcurrency * this.scaleDownStepRatio);
338
+ this._desiredConcurrency = Math.max(this._minConcurrency, this._desiredConcurrency - step);
339
+ this.log.debug('scaling down', {
340
+ oldConcurrency: this._desiredConcurrency + step,
341
+ newConcurrency: this._desiredConcurrency,
342
+ systemStatus,
343
+ });
344
+ }
345
+ _incrementTasksDonePerSecond(intervalCallback) {
346
+ this._tasksPerMinute.unshift(0);
347
+ this._tasksPerMinute.pop();
348
+ return intervalCallback();
349
+ }
350
+ }