@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/configuration.d.ts +16 -47
  3. package/configuration.js +13 -25
  4. package/debug.js +4 -4
  5. package/errors.d.ts +28 -38
  6. package/errors.js +33 -47
  7. package/events/event_manager.d.ts +2 -2
  8. package/events/event_manager.js +7 -6
  9. package/events/index.d.ts +1 -0
  10. package/events/local_event_manager.d.ts +1 -8
  11. package/events/local_event_manager.js +13 -13
  12. package/events/system_info.d.ts +38 -0
  13. package/index.d.ts +2 -8
  14. package/index.js +4 -8
  15. package/internal.d.ts +8 -0
  16. package/internal.js +9 -0
  17. package/log.d.ts +10 -11
  18. package/log.js +52 -20
  19. package/memory-storage/memory-storage.d.ts +15 -18
  20. package/memory-storage/memory-storage.js +80 -58
  21. package/memory-storage/resource-clients/dataset.d.ts +1 -6
  22. package/memory-storage/resource-clients/dataset.js +23 -31
  23. package/memory-storage/resource-clients/key-value-store.d.ts +1 -10
  24. package/memory-storage/resource-clients/key-value-store.js +43 -67
  25. package/memory-storage/resource-clients/request-queue.d.ts +1 -42
  26. package/memory-storage/resource-clients/request-queue.js +109 -117
  27. package/owned_or_injected.d.ts +1 -3
  28. package/owned_or_injected.js +17 -17
  29. package/package.json +17 -20
  30. package/proxy_configuration.d.ts +21 -26
  31. package/proxy_configuration.js +35 -25
  32. package/recoverable_state.d.ts +104 -47
  33. package/recoverable_state.js +199 -74
  34. package/request.d.ts +20 -107
  35. package/request.js +78 -244
  36. package/serialization.js +17 -16
  37. package/service_locator.d.ts +22 -10
  38. package/service_locator.js +59 -48
  39. package/storages/batched_adds.d.ts +37 -0
  40. package/storages/batched_adds.js +73 -0
  41. package/storages/dataset.d.ts +13 -8
  42. package/storages/dataset.js +149 -40
  43. package/storages/index.d.ts +4 -4
  44. package/storages/index.js +2 -4
  45. package/storages/key_value_store.d.ts +16 -35
  46. package/storages/key_value_store.js +223 -110
  47. package/storages/key_value_store_codec.js +6 -11
  48. package/storages/request_dedup_cache.d.ts +1 -4
  49. package/storages/request_dedup_cache.js +15 -15
  50. package/storages/request_list.d.ts +9 -104
  51. package/storages/request_list.js +236 -233
  52. package/storages/request_loader.d.ts +49 -18
  53. package/storages/request_loader.js +36 -1
  54. package/storages/request_manager.d.ts +86 -0
  55. package/storages/request_manager_tandem.d.ts +14 -38
  56. package/storages/request_manager_tandem.js +67 -64
  57. package/storages/request_queue.d.ts +23 -50
  58. package/storages/request_queue.js +371 -226
  59. package/storages/storage_instance_manager.d.ts +2 -4
  60. package/storages/storage_instance_manager.js +21 -21
  61. package/storages/storage_stats.d.ts +1 -1
  62. package/storages/storage_stats.js +4 -4
  63. package/storages/transaction.d.ts +270 -0
  64. package/storages/transaction.js +296 -0
  65. package/storages/utils.d.ts +6 -3
  66. package/storages/utils.js +11 -2
  67. package/system-info/runtime.js +7 -7
  68. package/url.d.ts +9 -0
  69. package/url.js +11 -0
  70. package/validators.d.ts +23 -25
  71. package/validators.js +14 -25
  72. package/autoscaling/autoscaled_pool.d.ts +0 -213
  73. package/autoscaling/autoscaled_pool.js +0 -378
  74. package/autoscaling/client_load_signal.d.ts +0 -59
  75. package/autoscaling/client_load_signal.js +0 -73
  76. package/autoscaling/concurrency_system.d.ts +0 -283
  77. package/autoscaling/concurrency_system.js +0 -350
  78. package/autoscaling/cpu_load_signal.d.ts +0 -44
  79. package/autoscaling/cpu_load_signal.js +0 -46
  80. package/autoscaling/event_loop_load_signal.d.ts +0 -54
  81. package/autoscaling/event_loop_load_signal.js +0 -60
  82. package/autoscaling/index.d.ts +0 -9
  83. package/autoscaling/index.js +0 -9
  84. package/autoscaling/load_signal.d.ts +0 -99
  85. package/autoscaling/load_signal.js +0 -103
  86. package/autoscaling/memory_load_signal.d.ts +0 -56
  87. package/autoscaling/memory_load_signal.js +0 -106
  88. package/autoscaling/snapshotter.d.ts +0 -87
  89. package/autoscaling/snapshotter.js +0 -67
  90. package/autoscaling/system_status.d.ts +0 -161
  91. package/autoscaling/system_status.js +0 -139
  92. package/autoscaling/weighted_avg.d.ts +0 -5
  93. package/autoscaling/weighted_avg.js +0 -14
  94. package/cookie_utils.d.ts +0 -44
  95. package/cookie_utils.js +0 -122
  96. package/crawlers/context_pipeline.d.ts +0 -70
  97. package/crawlers/context_pipeline.js +0 -122
  98. package/crawlers/crawler_commons.d.ts +0 -257
  99. package/crawlers/crawler_commons.js +0 -107
  100. package/crawlers/error_snapshotter.d.ts +0 -59
  101. package/crawlers/error_snapshotter.js +0 -117
  102. package/crawlers/error_tracker.d.ts +0 -54
  103. package/crawlers/error_tracker.js +0 -308
  104. package/crawlers/index.d.ts +0 -5
  105. package/crawlers/index.js +0 -5
  106. package/crawlers/internals/types.d.ts +0 -7
  107. package/crawlers/statistics.d.ts +0 -209
  108. package/crawlers/statistics.js +0 -350
  109. package/enqueue_links/enqueue_links.d.ts +0 -264
  110. package/enqueue_links/enqueue_links.js +0 -271
  111. package/enqueue_links/index.d.ts +0 -2
  112. package/enqueue_links/index.js +0 -2
  113. package/enqueue_links/shared.d.ts +0 -83
  114. package/enqueue_links/shared.js +0 -221
  115. package/router.d.ts +0 -309
  116. package/router.js +0 -309
  117. package/session_pool/consts.d.ts +0 -3
  118. package/session_pool/consts.js +0 -3
  119. package/session_pool/errors.d.ts +0 -7
  120. package/session_pool/errors.js +0 -11
  121. package/session_pool/fingerprint.d.ts +0 -9
  122. package/session_pool/fingerprint.js +0 -30
  123. package/session_pool/index.d.ts +0 -4
  124. package/session_pool/index.js +0 -4
  125. package/session_pool/session.d.ts +0 -161
  126. package/session_pool/session.js +0 -218
  127. package/session_pool/session_pool.d.ts +0 -246
  128. package/session_pool/session_pool.js +0 -386
  129. package/storages/access_checking.d.ts +0 -12
  130. package/storages/access_checking.js +0 -17
  131. package/storages/sitemap_request_loader.d.ts +0 -249
  132. package/storages/sitemap_request_loader.js +0 -432
  133. /package/{crawlers/internals/types.js → events/system_info.js} +0 -0
@@ -1,350 +0,0 @@
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
- }
@@ -1,44 +0,0 @@
1
- import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
2
- import type { SystemInfo } from './system_status.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
- readonly name = "cpuInfo";
35
- readonly overloadedRatio: number;
36
- private readonly store;
37
- private events?;
38
- constructor(options?: CpuLoadSignalOptions);
39
- start(context: LoadSignalStartContext): Promise<void>;
40
- stop(): Promise<void>;
41
- getSample(sampleDurationMillis?: number): LoadSnapshot[];
42
- /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
43
- handle(systemInfo: SystemInfo): void;
44
- }
@@ -1,46 +0,0 @@
1
- import { serviceLocator } from '../service_locator.js';
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("systemInfo" /* EventType.SYSTEM_INFO */, this.handle);
28
- }
29
- async stop() {
30
- this.events?.off("systemInfo" /* 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
- }
@@ -1,54 +0,0 @@
1
- import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
2
- /**
3
- * A snapshot produced by the built-in event loop signal.
4
- * @internal
5
- */
6
- export interface EventLoopSnapshot extends LoadSnapshot {
7
- exceededMillis: number;
8
- }
9
- /**
10
- * Tuning for the built-in **event loop** load signal, as accepted both by {@link EventLoopLoadSignal} and by the
11
- * {@link LoadSignalsOptions.eventLoop|`eventLoop`} shorthand on {@link LoadSignalsOptions}.
12
- */
13
- export interface EventLoopLoadSignalOptions {
14
- /**
15
- * Defines the interval of measuring the event loop response time, in seconds.
16
- * @default 0.5
17
- */
18
- snapshotIntervalSecs?: number;
19
- /**
20
- * Maximum allowed delay of the event loop in milliseconds.
21
- * Exceeding this limit overloads the event loop.
22
- * @default 50
23
- */
24
- maxBlockedMillis?: number;
25
- /**
26
- * Maximum ratio of overloaded snapshots in a sample before the event loop counts as overloaded.
27
- * @default 0.6
28
- */
29
- overloadedRatio?: number;
30
- }
31
- /**
32
- * Periodically measures event loop delay and reports overload when the delay exceeds a configured threshold.
33
- *
34
- * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
35
- *
36
- * @category Scaling
37
- */
38
- export declare class EventLoopLoadSignal implements LoadSignal {
39
- readonly name = "eventLoopInfo";
40
- readonly overloadedRatio: number;
41
- private readonly store;
42
- private readonly intervalMillis;
43
- private readonly maxBlockedMillis;
44
- private interval?;
45
- constructor(options?: EventLoopLoadSignalOptions);
46
- start(context: LoadSignalStartContext): Promise<void>;
47
- stop(): Promise<void>;
48
- getSample(sampleDurationMillis?: number): LoadSnapshot[];
49
- /**
50
- * Records one snapshot: how much later than scheduled this tick ran is how long the loop was blocked.
51
- * @internal Also lets tests drive the measurement without waiting on a timer.
52
- */
53
- handle(intervalCallback: () => unknown): void;
54
- }
@@ -1,60 +0,0 @@
1
- import { betterClearInterval, betterSetInterval } from '@apify/utilities';
2
- import { SnapshotStore } from './load_signal.js';
3
- /**
4
- * Periodically measures event loop delay and reports overload when the delay exceeds a configured threshold.
5
- *
6
- * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
7
- *
8
- * @category Scaling
9
- */
10
- export class EventLoopLoadSignal {
11
- name = 'eventLoopInfo';
12
- overloadedRatio;
13
- store = new SnapshotStore();
14
- intervalMillis;
15
- maxBlockedMillis;
16
- interval;
17
- constructor(options = {}) {
18
- this.overloadedRatio = options.overloadedRatio ?? 0.6;
19
- this.intervalMillis = (options.snapshotIntervalSecs ?? 0.5) * 1000;
20
- this.maxBlockedMillis = options.maxBlockedMillis ?? 50;
21
- this.handle = this.handle.bind(this);
22
- }
23
- async start(context) {
24
- this.store.useSampleWindow(context.maxSampleWindowMillis);
25
- // A new session starts from a clean slate, or the downtime gets charged to the event loop: `handle()` measures
26
- // the gap since the previous snapshot, which across a restart is however long the system was stopped.
27
- this.store.clear();
28
- this.interval = betterSetInterval(this.handle, this.intervalMillis);
29
- }
30
- async stop() {
31
- if (this.interval)
32
- betterClearInterval(this.interval);
33
- this.interval = undefined;
34
- }
35
- getSample(sampleDurationMillis) {
36
- return this.store.getSample(sampleDurationMillis);
37
- }
38
- /**
39
- * Records one snapshot: how much later than scheduled this tick ran is how long the loop was blocked.
40
- * @internal Also lets tests drive the measurement without waiting on a timer.
41
- */
42
- handle(intervalCallback) {
43
- const now = new Date();
44
- const snapshot = {
45
- createdAt: now,
46
- isOverloaded: false,
47
- exceededMillis: 0,
48
- };
49
- const all = this.store.getAll();
50
- const previousSnapshot = all[all.length - 1];
51
- if (previousSnapshot) {
52
- const delta = now.getTime() - +previousSnapshot.createdAt - this.intervalMillis;
53
- if (delta > this.maxBlockedMillis)
54
- snapshot.isOverloaded = true;
55
- snapshot.exceededMillis = Math.max(delta - this.maxBlockedMillis, 0);
56
- }
57
- this.store.push(snapshot, now);
58
- intervalCallback();
59
- }
60
- }
@@ -1,9 +0,0 @@
1
- export * from './autoscaled_pool.js';
2
- export * from './concurrency_system.js';
3
- export * from './client_load_signal.js';
4
- export * from './cpu_load_signal.js';
5
- export * from './event_loop_load_signal.js';
6
- export * from './load_signal.js';
7
- export * from './memory_load_signal.js';
8
- export * from './snapshotter.js';
9
- export * from './system_status.js';
@@ -1,9 +0,0 @@
1
- export * from './autoscaled_pool.js';
2
- export * from './concurrency_system.js';
3
- export * from './client_load_signal.js';
4
- export * from './cpu_load_signal.js';
5
- export * from './event_loop_load_signal.js';
6
- export * from './load_signal.js';
7
- export * from './memory_load_signal.js';
8
- export * from './snapshotter.js';
9
- export * from './system_status.js';
@@ -1,99 +0,0 @@
1
- import type { ClientInfo } from './system_status.js';
2
- /**
3
- * A snapshot of a resource's overload state at a point in time.
4
- */
5
- export interface LoadSnapshot {
6
- createdAt: Date;
7
- isOverloaded: boolean;
8
- }
9
- /**
10
- * Handed to a {@link LoadSignal} when it starts, so it can size its snapshot retention to what it will actually
11
- * be asked for — without having to know how the {@link ConcurrencySystem} that drives it is configured.
12
- */
13
- export interface LoadSignalStartContext {
14
- /**
15
- * The longest sample window the signal will be queried with (the wider of the task-gating and autoscaling
16
- * windows). Keeping less history than this contributes a narrower view of the resource than the other signals;
17
- * keeping more is wasted memory, as the extra snapshots are never sampled.
18
- */
19
- maxSampleWindowMillis: number;
20
- }
21
- /**
22
- * A signal that reports whether a particular resource is overloaded. The {@link ConcurrencySystem} aggregates
23
- * several of them — if any one reports overload, the system is overloaded.
24
- *
25
- * The built-in signals cover memory, CPU, event loop and storage-client rate limits. Implement this interface to add
26
- * your own (navigation timeouts, proxy health, …) and pass them via
27
- * {@link LoadSignalsOptions.custom|`loadSignals.custom`}; {@link SnapshotStore} does the time-windowed
28
- * bookkeeping if you want it. Each built-in is also a public class, so one can be *wrapped* rather than reimplemented
29
- * — construct it yourself and switch the default off with {@link LoadSignalsOptions.cpu|`cpu: false`} or friends.
30
- */
31
- export interface LoadSignal {
32
- /**
33
- * This signal's key in the reported {@link SystemInfo}, also used in logging — so it must be unique among the
34
- * signals of one {@link ConcurrencySystem}, which throws on a duplicate. The four built-in names (`memInfo`,
35
- * `eventLoopInfo`, `cpuInfo`, `clientInfo`) land in the correspondingly named `SystemInfo` fields rather than the
36
- * `loadSignalInfo` bag; taking one over means switching that built-in off.
37
- */
38
- readonly name: string;
39
- /**
40
- * Maximum ratio of overloaded snapshots in a sample before the signal
41
- * is considered overloaded. For example, `0.2` means the signal fires
42
- * when more than 20% of the sample window is overloaded.
43
- */
44
- readonly overloadedRatio: number;
45
- /**
46
- * Start collecting snapshots, retaining at least the sample window named in the `context`. Called when the
47
- * {@link ConcurrencySystem} starts — which may be a *restart*, so drop anything measured before it.
48
- */
49
- start(context: LoadSignalStartContext): Promise<void>;
50
- /** Stop collecting snapshots. Called when the {@link ConcurrencySystem} shuts down. */
51
- stop(): Promise<void>;
52
- /**
53
- * Return snapshots for a recent time window (used for "current" status).
54
- * @param sampleDurationMillis How far back to look, in milliseconds.
55
- */
56
- getSample(sampleDurationMillis?: number): LoadSnapshot[];
57
- }
58
- /**
59
- * A time-pruning, time-windowed store for `LoadSnapshot` values. All four built-in signals compose with one of these,
60
- * and so can yours — it is the only part of their machinery worth reusing.
61
- */
62
- export declare class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {
63
- private snapshots;
64
- /** Retention window in milliseconds. Unbounded until {@link SnapshotStore.useSampleWindow|`useSampleWindow()`}. */
65
- private historyMillis;
66
- /**
67
- * Sizes retention to the window the signal will be sampled over, as handed to it in
68
- * {@link LoadSignal.start|`start()`}. Until this is called nothing is pruned at all, so a signal that ignores
69
- * its start context grows unboundedly.
70
- */
71
- useSampleWindow(maxSampleWindowMillis: number): void;
72
- /**
73
- * Add a snapshot and prune entries older than the history window.
74
- */
75
- push(snapshot: T, now?: Date): void;
76
- /**
77
- * Return all snapshots, or only those within the given time window.
78
- */
79
- getSample(sampleDurationMillis?: number): T[];
80
- /**
81
- * Direct, unwindowed access to the underlying array — used by signals whose handler needs the previous snapshot
82
- * to compute a delta (e.g. the event loop and client signals read the last entry to measure change since it).
83
- */
84
- getAll(): T[];
85
- /**
86
- * Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
87
- * samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
88
- * snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
89
- * rather than on stop leaves a finished session readable.
90
- */
91
- clear(): void;
92
- }
93
- /**
94
- * Evaluate whether a sample of `LoadSnapshot` values exceeds the given
95
- * overloaded ratio, using a time-weighted average. This is the shared
96
- * evaluation logic used by `SystemStatus` for all signal types.
97
- * @internal
98
- */
99
- export declare function evaluateLoadSignalSample(sample: LoadSnapshot[], overloadedRatio: number): ClientInfo;