@crawlee/core 4.0.0-beta.11 → 4.0.0-beta.110

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 (271) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +105 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +1 -4
  35. package/crawlers/error_snapshotter.js +3 -6
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +91 -41
  43. package/crawlers/statistics.js +83 -72
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +39 -26
  51. package/enqueue_links/shared.js +89 -67
  52. package/errors.d.ts +41 -4
  53. package/errors.js +50 -5
  54. package/events/event_manager.d.ts +34 -8
  55. package/events/event_manager.js +8 -10
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +37 -11
  60. package/index.d.ts +6 -4
  61. package/index.js +5 -3
  62. package/iterables.d.ts +79 -0
  63. package/iterables.js +134 -0
  64. package/log.d.ts +82 -3
  65. package/log.js +106 -1
  66. package/memory-storage/consts.d.ts +4 -0
  67. package/memory-storage/consts.js +4 -0
  68. package/memory-storage/index.d.ts +1 -0
  69. package/memory-storage/index.js +1 -0
  70. package/memory-storage/memory-storage.d.ts +42 -0
  71. package/memory-storage/memory-storage.js +136 -0
  72. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  73. package/memory-storage/resource-clients/common/base-client.js +6 -0
  74. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  75. package/memory-storage/resource-clients/dataset.js +114 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +204 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  79. package/memory-storage/resource-clients/request-queue.js +422 -0
  80. package/memory-storage/utils.d.ts +16 -0
  81. package/memory-storage/utils.js +41 -0
  82. package/owned_or_injected.d.ts +58 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +27 -152
  86. package/proxy_configuration.js +27 -179
  87. package/recoverable_state.d.ts +111 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +86 -17
  90. package/request.js +117 -41
  91. package/router.d.ts +193 -21
  92. package/router.js +188 -43
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +9 -11
  95. package/service_locator.d.ts +147 -0
  96. package/service_locator.js +244 -0
  97. package/session_pool/consts.d.ts +1 -2
  98. package/session_pool/consts.js +1 -2
  99. package/session_pool/errors.d.ts +0 -1
  100. package/session_pool/errors.js +0 -1
  101. package/session_pool/fingerprint.d.ts +9 -0
  102. package/session_pool/fingerprint.js +30 -0
  103. package/session_pool/index.d.ts +0 -2
  104. package/session_pool/index.js +0 -2
  105. package/session_pool/session.d.ts +37 -86
  106. package/session_pool/session.js +85 -138
  107. package/session_pool/session_pool.d.ts +77 -91
  108. package/session_pool/session_pool.js +159 -147
  109. package/storages/dataset.d.ts +114 -54
  110. package/storages/dataset.js +285 -144
  111. package/storages/index.d.ts +9 -8
  112. package/storages/index.js +7 -8
  113. package/storages/key_value_store.d.ts +185 -42
  114. package/storages/key_value_store.js +424 -151
  115. package/storages/key_value_store_codec.d.ts +32 -0
  116. package/storages/key_value_store_codec.js +113 -0
  117. package/storages/request_dedup_cache.d.ts +22 -0
  118. package/storages/request_dedup_cache.js +48 -0
  119. package/storages/request_list.d.ts +52 -116
  120. package/storages/request_list.js +158 -133
  121. package/storages/request_loader.d.ts +96 -0
  122. package/storages/request_loader.js +1 -0
  123. package/storages/request_manager.d.ts +33 -0
  124. package/storages/request_manager.js +1 -0
  125. package/storages/request_manager_tandem.d.ts +97 -0
  126. package/storages/request_manager_tandem.js +197 -0
  127. package/storages/request_queue.d.ts +290 -47
  128. package/storages/request_queue.js +824 -216
  129. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  130. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +136 -143
  131. package/storages/storage_instance_manager.d.ts +87 -0
  132. package/storages/storage_instance_manager.js +256 -0
  133. package/storages/storage_stats.d.ts +48 -0
  134. package/storages/storage_stats.js +29 -0
  135. package/storages/transaction.d.ts +252 -0
  136. package/storages/transaction.js +251 -0
  137. package/storages/utils.d.ts +54 -9
  138. package/storages/utils.js +64 -13
  139. package/system-info/cpu-info.d.ts +67 -0
  140. package/system-info/cpu-info.js +216 -0
  141. package/system-info/memory-info.d.ts +31 -0
  142. package/system-info/memory-info.js +115 -0
  143. package/system-info/ps-tree.d.ts +17 -0
  144. package/system-info/ps-tree.js +144 -0
  145. package/system-info/runtime.d.ts +14 -0
  146. package/system-info/runtime.js +80 -0
  147. package/typedefs.d.ts +0 -6
  148. package/typedefs.js +0 -1
  149. package/validators.d.ts +8 -1
  150. package/validators.js +10 -3
  151. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  152. package/autoscaling/autoscaled_pool.js.map +0 -1
  153. package/autoscaling/index.d.ts.map +0 -1
  154. package/autoscaling/index.js.map +0 -1
  155. package/autoscaling/snapshotter.d.ts.map +0 -1
  156. package/autoscaling/snapshotter.js.map +0 -1
  157. package/autoscaling/system_status.d.ts.map +0 -1
  158. package/autoscaling/system_status.js.map +0 -1
  159. package/configuration.d.ts.map +0 -1
  160. package/configuration.js.map +0 -1
  161. package/cookie_utils.d.ts.map +0 -1
  162. package/cookie_utils.js.map +0 -1
  163. package/crawlers/context_pipeline.d.ts.map +0 -1
  164. package/crawlers/context_pipeline.js.map +0 -1
  165. package/crawlers/crawler_commons.d.ts.map +0 -1
  166. package/crawlers/crawler_commons.js.map +0 -1
  167. package/crawlers/crawler_utils.d.ts +0 -10
  168. package/crawlers/crawler_utils.d.ts.map +0 -1
  169. package/crawlers/crawler_utils.js +0 -12
  170. package/crawlers/crawler_utils.js.map +0 -1
  171. package/crawlers/error_snapshotter.d.ts.map +0 -1
  172. package/crawlers/error_snapshotter.js.map +0 -1
  173. package/crawlers/error_tracker.d.ts.map +0 -1
  174. package/crawlers/error_tracker.js.map +0 -1
  175. package/crawlers/index.d.ts.map +0 -1
  176. package/crawlers/index.js.map +0 -1
  177. package/crawlers/internals/types.d.ts.map +0 -1
  178. package/crawlers/internals/types.js.map +0 -1
  179. package/crawlers/statistics.d.ts.map +0 -1
  180. package/crawlers/statistics.js.map +0 -1
  181. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  182. package/enqueue_links/enqueue_links.js.map +0 -1
  183. package/enqueue_links/index.d.ts.map +0 -1
  184. package/enqueue_links/index.js.map +0 -1
  185. package/enqueue_links/shared.d.ts.map +0 -1
  186. package/enqueue_links/shared.js.map +0 -1
  187. package/errors.d.ts.map +0 -1
  188. package/errors.js.map +0 -1
  189. package/events/event_manager.d.ts.map +0 -1
  190. package/events/event_manager.js.map +0 -1
  191. package/events/index.d.ts.map +0 -1
  192. package/events/index.js.map +0 -1
  193. package/events/local_event_manager.d.ts.map +0 -1
  194. package/events/local_event_manager.js.map +0 -1
  195. package/http_clients/base-http-client.d.ts +0 -134
  196. package/http_clients/base-http-client.d.ts.map +0 -1
  197. package/http_clients/base-http-client.js +0 -33
  198. package/http_clients/base-http-client.js.map +0 -1
  199. package/http_clients/form-data-like.d.ts +0 -67
  200. package/http_clients/form-data-like.d.ts.map +0 -1
  201. package/http_clients/form-data-like.js +0 -5
  202. package/http_clients/form-data-like.js.map +0 -1
  203. package/http_clients/got-scraping-http-client.d.ts +0 -15
  204. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  205. package/http_clients/got-scraping-http-client.js +0 -69
  206. package/http_clients/got-scraping-http-client.js.map +0 -1
  207. package/http_clients/index.d.ts +0 -3
  208. package/http_clients/index.d.ts.map +0 -1
  209. package/http_clients/index.js +0 -3
  210. package/http_clients/index.js.map +0 -1
  211. package/index.d.ts.map +0 -1
  212. package/index.js.map +0 -1
  213. package/log.d.ts.map +0 -1
  214. package/log.js.map +0 -1
  215. package/proxy_configuration.d.ts.map +0 -1
  216. package/proxy_configuration.js.map +0 -1
  217. package/request.d.ts.map +0 -1
  218. package/request.js.map +0 -1
  219. package/router.d.ts.map +0 -1
  220. package/router.js.map +0 -1
  221. package/serialization.d.ts.map +0 -1
  222. package/serialization.js.map +0 -1
  223. package/session_pool/consts.d.ts.map +0 -1
  224. package/session_pool/consts.js.map +0 -1
  225. package/session_pool/errors.d.ts.map +0 -1
  226. package/session_pool/errors.js.map +0 -1
  227. package/session_pool/events.d.ts +0 -3
  228. package/session_pool/events.d.ts.map +0 -1
  229. package/session_pool/events.js +0 -3
  230. package/session_pool/events.js.map +0 -1
  231. package/session_pool/index.d.ts.map +0 -1
  232. package/session_pool/index.js.map +0 -1
  233. package/session_pool/session.d.ts.map +0 -1
  234. package/session_pool/session.js.map +0 -1
  235. package/session_pool/session_pool.d.ts.map +0 -1
  236. package/session_pool/session_pool.js.map +0 -1
  237. package/storages/access_checking.d.ts +0 -13
  238. package/storages/access_checking.d.ts.map +0 -1
  239. package/storages/access_checking.js +0 -14
  240. package/storages/access_checking.js.map +0 -1
  241. package/storages/dataset.d.ts.map +0 -1
  242. package/storages/dataset.js.map +0 -1
  243. package/storages/index.d.ts.map +0 -1
  244. package/storages/index.js.map +0 -1
  245. package/storages/key_value_store.d.ts.map +0 -1
  246. package/storages/key_value_store.js.map +0 -1
  247. package/storages/request_list.d.ts.map +0 -1
  248. package/storages/request_list.js.map +0 -1
  249. package/storages/request_provider.d.ts +0 -308
  250. package/storages/request_provider.d.ts.map +0 -1
  251. package/storages/request_provider.js +0 -555
  252. package/storages/request_provider.js.map +0 -1
  253. package/storages/request_queue.d.ts.map +0 -1
  254. package/storages/request_queue.js.map +0 -1
  255. package/storages/request_queue_v2.d.ts +0 -87
  256. package/storages/request_queue_v2.d.ts.map +0 -1
  257. package/storages/request_queue_v2.js +0 -438
  258. package/storages/request_queue_v2.js.map +0 -1
  259. package/storages/sitemap_request_list.d.ts.map +0 -1
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/tsconfig.build.tsbuildinfo +0 -1
  268. package/typedefs.d.ts.map +0 -1
  269. package/typedefs.js.map +0 -1
  270. package/validators.d.ts.map +0 -1
  271. package/validators.js.map +0 -1
@@ -1,285 +1,67 @@
1
- import { getMemoryInfo, isContainerized } from '@crawlee/utils';
2
- import ow from 'ow';
3
- import { betterClearInterval, betterSetInterval } from '@apify/utilities';
4
- import { Configuration } from '../configuration.js';
5
- import { log as defaultLog } from '../log.js';
6
- const RESERVE_MEMORY_RATIO = 0.5;
7
- const CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT = 2;
8
- const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10000;
1
+ import { ClientLoadSignal } from './client_load_signal.js';
2
+ import { CpuLoadSignal } from './cpu_load_signal.js';
3
+ import { EventLoopLoadSignal } from './event_loop_load_signal.js';
4
+ import { MemoryLoadSignal } from './memory_load_signal.js';
9
5
  /**
10
- * Creates snapshots of system resources at given intervals and marks the resource
11
- * as either overloaded or not during the last interval. Keeps a history of the snapshots.
12
- * It tracks the following resources: Memory, EventLoop, API and CPU.
13
- * The class is used by the {@link AutoscaledPool} class.
6
+ * Owns the four built-in {@link LoadSignal} instances {@link MemoryLoadSignal},
7
+ * {@link EventLoopLoadSignal}, {@link CpuLoadSignal} and {@link ClientLoadSignal} constructing the ones
8
+ * that were not switched off and driving their shared lifecycle.
14
9
  *
15
- * When running on the Apify platform, the CPU and memory statistics are provided by the platform,
16
- * as collected from the running Docker container. When running locally, `Snapshotter`
17
- * makes its own statistics by querying the OS.
18
- *
19
- * CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or
20
- * when Apify platform marks it as overloaded.
21
- *
22
- * Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option.
23
- * It's computed using the total memory available to the container when running on
24
- * the Apify platform and a quarter of total system memory when running locally.
25
- * Max total memory when running locally may be overridden by using the `CRAWLEE_MEMORY_MBYTES`
26
- * environment variable.
27
- *
28
- * Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.
29
- *
30
- * Client becomes overloaded when rate limit errors (429 - Too Many Requests),
31
- * typically received from the request queue, exceed the set limit within the set interval.
32
- * @category Scaling
10
+ * Configured indirectly through {@link ConcurrencySystemOptions.loadSignals|`loadSignals`}, whose per-signal bags
11
+ * are simply forwarded to the corresponding constructor.
12
+ * @internal
33
13
  */
34
14
  export class Snapshotter {
35
- log;
36
- client;
37
- config;
38
- events;
39
- eventLoopSnapshotIntervalMillis;
40
- clientSnapshotIntervalMillis;
41
- snapshotHistoryMillis;
42
- maxBlockedMillis;
43
- maxUsedMemoryRatio;
44
- maxClientErrors;
45
- maxMemoryBytes;
46
- cpuSnapshots = [];
47
- eventLoopSnapshots = [];
48
- memorySnapshots = [];
49
- clientSnapshots = [];
50
- eventLoopInterval = null;
51
- clientInterval = null;
52
- lastLoggedCriticalMemoryOverloadAt = null;
15
+ // Absent when switched off through the corresponding option (e.g. `client: false`).
16
+ #memorySignal;
17
+ #eventLoopSignal;
18
+ #cpuSignal;
19
+ #clientSignal;
20
+ /**
21
+ * Returns the enabled built-in signals, so `SystemStatus` can iterate them alongside any custom `LoadSignal`
22
+ * instances. Signals switched off through the options are simply absent — the system status reports them as
23
+ * not overloaded.
24
+ */
25
+ getLoadSignals() {
26
+ const builtin = [
27
+ this.#memorySignal,
28
+ this.#eventLoopSignal,
29
+ this.#cpuSignal,
30
+ this.#clientSignal,
31
+ ];
32
+ return builtin.filter((signal) => signal !== undefined);
33
+ }
53
34
  /**
54
35
  * @param [options] All `Snapshotter` configuration options.
55
36
  */
56
37
  constructor(options = {}) {
57
- ow(options, ow.object.exactShape({
58
- eventLoopSnapshotIntervalSecs: ow.optional.number,
59
- clientSnapshotIntervalSecs: ow.optional.number,
60
- snapshotHistorySecs: ow.optional.number,
61
- maxBlockedMillis: ow.optional.number,
62
- maxUsedMemoryRatio: ow.optional.number,
63
- maxClientErrors: ow.optional.number,
64
- log: ow.optional.object,
65
- client: ow.optional.object,
66
- config: ow.optional.object,
67
- }));
68
- const { eventLoopSnapshotIntervalSecs = 0.5, clientSnapshotIntervalSecs = 1, snapshotHistorySecs = 30, maxBlockedMillis = 50, maxUsedMemoryRatio = 0.9, maxClientErrors = 3, log = defaultLog, config = Configuration.getGlobalConfig(), client = config.getStorageClient(), } = options;
69
- this.log = log.child({ prefix: 'Snapshotter' });
70
- this.client = client;
71
- this.config = config;
72
- this.events = this.config.getEventManager();
73
- this.eventLoopSnapshotIntervalMillis = eventLoopSnapshotIntervalSecs * 1000;
74
- this.clientSnapshotIntervalMillis = clientSnapshotIntervalSecs * 1000;
75
- this.snapshotHistoryMillis = snapshotHistorySecs * 1000;
76
- this.maxBlockedMillis = maxBlockedMillis;
77
- this.maxUsedMemoryRatio = maxUsedMemoryRatio;
78
- this.maxClientErrors = maxClientErrors;
79
- // We need to pre-bind those functions to be able to successfully remove listeners.
80
- this._snapshotCpu = this._snapshotCpu.bind(this);
81
- this._snapshotMemory = this._snapshotMemory.bind(this);
38
+ const { memory = {}, eventLoop = {}, cpu = {}, client = {} } = options;
39
+ // Each signal resolves its own ambient dependencies when started, and is told the window it will be sampled
40
+ // over then too - so there is nothing to thread in here beyond the caller's tuning.
41
+ if (memory !== false)
42
+ this.#memorySignal = new MemoryLoadSignal(memory);
43
+ if (eventLoop !== false)
44
+ this.#eventLoopSignal = new EventLoopLoadSignal(eventLoop);
45
+ if (cpu !== false)
46
+ this.#cpuSignal = new CpuLoadSignal(cpu);
47
+ if (client !== false)
48
+ this.#clientSignal = new ClientLoadSignal(client);
82
49
  }
83
50
  /**
84
- * Starts capturing snapshots at configured intervals.
51
+ * Starts capturing snapshots at configured intervals. The `context` carries the sample window the signals will
52
+ * be queried with, which is also how much history they retain.
85
53
  */
86
- async start() {
87
- const memoryMbytes = this.config.get('memoryMbytes', 0);
88
- if (memoryMbytes > 0) {
89
- this.maxMemoryBytes = memoryMbytes * 1024 * 1024;
90
- }
91
- else {
92
- const containerized = this.config.get('containerized', await isContainerized());
93
- const memInfo = await getMemoryInfo(containerized);
94
- const totalBytes = memInfo.totalBytes;
95
- this.maxMemoryBytes = Math.ceil(totalBytes * this.config.get('availableMemoryRatio'));
96
- this.log.debug(`Setting max memory of this run to ${Math.round(this.maxMemoryBytes / 1024 / 1024)} MB. ` +
97
- 'Use the CRAWLEE_MEMORY_MBYTES or CRAWLEE_AVAILABLE_MEMORY_RATIO environment variable to override it.');
98
- }
99
- // Start snapshotting.
100
- this.eventLoopInterval = betterSetInterval(this._snapshotEventLoop.bind(this), this.eventLoopSnapshotIntervalMillis);
101
- this.clientInterval = betterSetInterval(this._snapshotClient.bind(this), this.clientSnapshotIntervalMillis);
102
- this.events.on("systemInfo" /* EventType.SYSTEM_INFO */, this._snapshotCpu);
103
- this.events.on("systemInfo" /* EventType.SYSTEM_INFO */, this._snapshotMemory);
54
+ async start(context) {
55
+ await Promise.all(this.getLoadSignals().map(async (signal) => signal.start(context)));
104
56
  }
105
57
  /**
106
58
  * Stops all resource capturing.
107
59
  */
108
60
  async stop() {
109
- betterClearInterval(this.eventLoopInterval);
110
- betterClearInterval(this.clientInterval);
111
- this.events.off("systemInfo" /* EventType.SYSTEM_INFO */, this._snapshotCpu);
112
- this.events.off("systemInfo" /* EventType.SYSTEM_INFO */, this._snapshotMemory);
61
+ await Promise.all(this.getLoadSignals().map(async (signal) => signal.stop()));
113
62
  // Allow microtask queue to unwind before stop returns.
114
63
  await new Promise((resolve) => {
115
64
  setImmediate(resolve);
116
65
  });
117
66
  }
118
- /**
119
- * Returns a sample of latest memory snapshots, with the size of the sample defined
120
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
121
- */
122
- getMemorySample(sampleDurationMillis) {
123
- return this._getSample(this.memorySnapshots, sampleDurationMillis);
124
- }
125
- /**
126
- * Returns a sample of latest event loop snapshots, with the size of the sample defined
127
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
128
- */
129
- getEventLoopSample(sampleDurationMillis) {
130
- return this._getSample(this.eventLoopSnapshots, sampleDurationMillis);
131
- }
132
- /**
133
- * Returns a sample of latest CPU snapshots, with the size of the sample defined
134
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
135
- */
136
- getCpuSample(sampleDurationMillis) {
137
- return this._getSample(this.cpuSnapshots, sampleDurationMillis);
138
- }
139
- /**
140
- * Returns a sample of latest Client snapshots, with the size of the sample defined
141
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
142
- */
143
- getClientSample(sampleDurationMillis) {
144
- return this._getSample(this.clientSnapshots, sampleDurationMillis);
145
- }
146
- /**
147
- * Finds the latest snapshots by sampleDurationMillis in the provided array.
148
- */
149
- _getSample(snapshots, sampleDurationMillis) {
150
- if (!sampleDurationMillis)
151
- return snapshots;
152
- const sample = [];
153
- let idx = snapshots.length;
154
- if (!idx)
155
- return sample;
156
- const latestTime = snapshots[idx - 1].createdAt;
157
- while (idx--) {
158
- const snapshot = snapshots[idx];
159
- if (+latestTime - +snapshot.createdAt <= sampleDurationMillis) {
160
- sample.unshift(snapshot);
161
- }
162
- else {
163
- break;
164
- }
165
- }
166
- return sample;
167
- }
168
- /**
169
- * Creates a snapshot of current memory usage
170
- * using the Apify platform `systemInfo` event.
171
- */
172
- _snapshotMemory(systemInfo) {
173
- const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
174
- this._pruneSnapshots(this.memorySnapshots, createdAt);
175
- const { memCurrentBytes } = systemInfo;
176
- const snapshot = {
177
- createdAt,
178
- isOverloaded: memCurrentBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio,
179
- usedBytes: memCurrentBytes,
180
- };
181
- this.memorySnapshots.push(snapshot);
182
- this._memoryOverloadWarning(systemInfo);
183
- }
184
- /**
185
- * Checks for critical memory overload and logs it to the console.
186
- */
187
- _memoryOverloadWarning(systemInfo) {
188
- const { memCurrentBytes } = systemInfo;
189
- const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
190
- if (this.lastLoggedCriticalMemoryOverloadAt &&
191
- +createdAt < +this.lastLoggedCriticalMemoryOverloadAt + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS)
192
- return;
193
- const maxDesiredMemoryBytes = this.maxUsedMemoryRatio * this.maxMemoryBytes;
194
- const reserveMemory = this.maxMemoryBytes * (1 - this.maxUsedMemoryRatio) * RESERVE_MEMORY_RATIO;
195
- const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;
196
- const isCriticalOverload = memCurrentBytes > criticalOverloadBytes;
197
- if (isCriticalOverload) {
198
- const usedPercentage = Math.round((memCurrentBytes / this.maxMemoryBytes) * 100);
199
- const toMb = (bytes) => Math.round(bytes / 1024 ** 2);
200
- this.log.warning('Memory is critically overloaded. ' +
201
- `Using ${toMb(memCurrentBytes)} MB of ${toMb(this.maxMemoryBytes)} MB (${usedPercentage}%). Consider increasing available memory.`);
202
- this.lastLoggedCriticalMemoryOverloadAt = createdAt;
203
- }
204
- }
205
- /**
206
- * Creates a snapshot of current event loop delay.
207
- */
208
- _snapshotEventLoop(intervalCallback) {
209
- const now = new Date();
210
- this._pruneSnapshots(this.eventLoopSnapshots, now);
211
- const snapshot = {
212
- createdAt: now,
213
- isOverloaded: false,
214
- exceededMillis: 0,
215
- };
216
- const previousSnapshot = this.eventLoopSnapshots[this.eventLoopSnapshots.length - 1];
217
- if (previousSnapshot) {
218
- const { createdAt } = previousSnapshot;
219
- const delta = now.getTime() - +createdAt - this.eventLoopSnapshotIntervalMillis;
220
- if (delta > this.maxBlockedMillis)
221
- snapshot.isOverloaded = true;
222
- snapshot.exceededMillis = Math.max(delta - this.maxBlockedMillis, 0);
223
- }
224
- this.eventLoopSnapshots.push(snapshot);
225
- intervalCallback();
226
- }
227
- /**
228
- * Creates a snapshot of current CPU usage using the Apify platform `systemInfo` event.
229
- */
230
- _snapshotCpu(systemInfo) {
231
- const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;
232
- const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
233
- this._pruneSnapshots(this.cpuSnapshots, createdAt);
234
- this.cpuSnapshots.push({
235
- createdAt,
236
- isOverloaded: isCpuOverloaded,
237
- usedRatio: Math.ceil(cpuCurrentUsage / 100),
238
- });
239
- }
240
- /**
241
- * Creates a snapshot of current API state by checking for
242
- * rate limit errors. Only errors produced by a 2nd retry
243
- * of the API call are considered for snapshotting since
244
- * earlier errors may just be caused by a random spike in
245
- * number of requests and do not necessarily signify API
246
- * overloading.
247
- */
248
- _snapshotClient(intervalCallback) {
249
- const now = new Date();
250
- this._pruneSnapshots(this.clientSnapshots, now);
251
- const allErrorCounts = this.client.stats?.rateLimitErrors ?? []; // storage client might not support this
252
- const currentErrCount = allErrorCounts[CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT] || 0;
253
- // Handle empty snapshots array
254
- const snapshot = {
255
- createdAt: now,
256
- isOverloaded: false,
257
- rateLimitErrorCount: currentErrCount,
258
- };
259
- const previousSnapshot = this.clientSnapshots[this.clientSnapshots.length - 1];
260
- if (previousSnapshot) {
261
- const { rateLimitErrorCount } = previousSnapshot;
262
- const delta = currentErrCount - rateLimitErrorCount;
263
- if (delta > this.maxClientErrors)
264
- snapshot.isOverloaded = true;
265
- }
266
- this.clientSnapshots.push(snapshot);
267
- intervalCallback();
268
- }
269
- /**
270
- * Removes snapshots that are older than the snapshotHistorySecs option
271
- * from the array (destructively - in place).
272
- */
273
- _pruneSnapshots(snapshots, now) {
274
- let oldCount = 0;
275
- for (let i = 0; i < snapshots.length; i++) {
276
- const { createdAt } = snapshots[i];
277
- if (now.getTime() - new Date(createdAt).getTime() > this.snapshotHistoryMillis)
278
- oldCount++;
279
- else
280
- break;
281
- }
282
- snapshots.splice(0, oldCount);
283
- }
284
67
  }
285
- //# sourceMappingURL=snapshotter.js.map
@@ -1,5 +1,5 @@
1
- import type { Configuration } from '../configuration.js';
2
- import { Snapshotter } from './snapshotter.js';
1
+ import type { LoadSignal } from './load_signal.js';
2
+ import type { Snapshotter } from './snapshotter.js';
3
3
  /**
4
4
  * Represents the current status of the system.
5
5
  */
@@ -10,6 +10,7 @@ export interface SystemInfo {
10
10
  eventLoopInfo: ClientInfo;
11
11
  cpuInfo: ClientInfo;
12
12
  clientInfo: ClientInfo;
13
+ memTotalBytes?: number;
13
14
  memCurrentBytes?: number;
14
15
  /**
15
16
  * Platform only property
@@ -26,7 +27,28 @@ export interface SystemInfo {
26
27
  * @internal
27
28
  */
28
29
  createdAt?: Date;
30
+ /**
31
+ * Status of additional load signals beyond the built-in four.
32
+ * Keys are `LoadSignal.name` values, values are overload info.
33
+ */
34
+ loadSignalInfo?: Record<string, ClientInfo>;
29
35
  }
36
+ /**
37
+ * How far back the *current* system status looks by default — the window that gates task dispatch.
38
+ * @internal
39
+ */
40
+ export declare const DEFAULT_CURRENT_HISTORY_SECS = 5;
41
+ /**
42
+ * How far back the *historical* system status looks by default — the window autoscaling decisions are based on, and
43
+ * therefore how much history the signals are asked to retain.
44
+ * @internal
45
+ */
46
+ export declare const DEFAULT_SNAPSHOT_HISTORY_SECS = 30;
47
+ /**
48
+ * An implementation detail of the {@link ConcurrencySystem} — configure it through
49
+ * {@link ConcurrencySystemOptions} (`loadSignals`, `currentHistorySecs` and `snapshotHistorySecs`).
50
+ * @internal
51
+ */
30
52
  export interface SystemStatusOptions {
31
53
  /**
32
54
  * Defines max age of snapshots used in the {@link SystemStatus.getCurrentStatus} measurement.
@@ -34,35 +56,23 @@ export interface SystemStatusOptions {
34
56
  */
35
57
  currentHistorySecs?: number;
36
58
  /**
37
- * Sets the maximum ratio of overloaded snapshots in a memory sample.
38
- * If the sample exceeds this ratio, the system will be overloaded.
39
- * @default 0.2
40
- */
41
- maxMemoryOverloadedRatio?: number;
42
- /**
43
- * Sets the maximum ratio of overloaded snapshots in an event loop sample.
44
- * If the sample exceeds this ratio, the system will be overloaded.
45
- * @default 0.6
59
+ * Defines max age of snapshots used in the {@link SystemStatus.getHistoricalStatus} measurement — the window
60
+ * autoscaling decisions are based on. Applied uniformly to every signal, built-in or custom, so that a signal's
61
+ * private retention cannot silently widen the window.
62
+ * @default 30
46
63
  */
47
- maxEventLoopOverloadedRatio?: number;
64
+ historySecs?: number;
48
65
  /**
49
- * Sets the maximum ratio of overloaded snapshots in a CPU sample.
50
- * If the sample exceeds this ratio, the system will be overloaded.
51
- * @default 0.4
66
+ * The `Snapshotter` whose built-in signals are evaluated.
52
67
  */
53
- maxCpuOverloadedRatio?: number;
68
+ snapshotter: Snapshotter;
54
69
  /**
55
- * Sets the maximum ratio of overloaded snapshots in a Client sample.
56
- * If the sample exceeds this ratio, the system will be overloaded.
57
- * @default 0.3
70
+ * Additional load signals to include in the system status evaluation.
71
+ * These are evaluated alongside the built-in memory, CPU, event loop,
72
+ * and client signals. If any signal reports overload, the system is
73
+ * considered overloaded. Each signal carries its own overload ratio.
58
74
  */
59
- maxClientOverloadedRatio?: number;
60
- /**
61
- * The `Snapshotter` instance to be queried for `SystemStatus`.
62
- */
63
- snapshotter?: Snapshotter;
64
- /** @internal */
65
- config?: Configuration;
75
+ loadSignals?: LoadSignal[];
66
76
  }
67
77
  export interface ClientInfo {
68
78
  isOverloaded: boolean;
@@ -82,35 +92,33 @@ export interface FinalStatistics {
82
92
  crawlerRuntimeMillis: number;
83
93
  }
84
94
  /**
85
- * Provides a simple interface to reading system status from a {@link Snapshotter} instance.
86
- * It only exposes two functions {@link SystemStatus.getCurrentStatus}
87
- * and {@link SystemStatus.getHistoricalStatus}.
88
- * The system status is calculated using a weighted average of overloaded
89
- * messages in the snapshots, with the weights being the time intervals
90
- * between the snapshots. Each resource is calculated separately
91
- * and the system is overloaded whenever at least one resource is overloaded.
92
- * The class is used by the {@link AutoscaledPool} class.
95
+ * Reads the overload verdict of every signal the {@link Snapshotter}'s built-in four plus any custom ones — and
96
+ * combines them into a {@link SystemInfo}: each signal is a time-weighted average of its snapshots, and the system
97
+ * is overloaded whenever at least one of them is.
93
98
  *
94
- * {@link SystemStatus.getCurrentStatus}
95
- * returns a boolean that represents the current status of the system.
96
- * The length of the current timeframe in seconds is configurable
97
- * by the `currentHistorySecs` option and represents the max age
98
- * of snapshots to be considered for the calculation.
99
+ * Evaluated over two windows, both requested explicitly from every signal so that a signal's private retention cannot
100
+ * widen what it contributes: a short `currentHistorySecs` one ({@link SystemStatus.getCurrentStatus}, gating task
101
+ * dispatch) and a longer `historySecs` one ({@link SystemStatus.getHistoricalStatus}, driving autoscaling).
99
102
  *
100
- * {@link SystemStatus.getHistoricalStatus}
101
- * returns a boolean that represents the long-term status
102
- * of the system. It considers the full snapshot history available
103
- * in the {@link Snapshotter} instance.
104
- * @category Scaling
103
+ * An implementation detail of the {@link ConcurrencySystem}, configured through
104
+ * {@link ConcurrencySystemOptions}.
105
+ * @internal
105
106
  */
106
107
  export declare class SystemStatus {
107
- private readonly currentHistoryMillis;
108
- private readonly maxMemoryOverloadedRatio;
109
- private readonly maxEventLoopOverloadedRatio;
110
- private readonly maxCpuOverloadedRatio;
111
- private readonly maxClientOverloadedRatio;
112
- private readonly snapshotter;
113
- constructor(options?: SystemStatusOptions);
108
+ #private;
109
+ constructor(options: SystemStatusOptions);
110
+ /**
111
+ * The widest window any signal will be queried with, and therefore exactly how much history the signals are asked
112
+ * to retain when they start. Derived here, where the windows are resolved, so nothing has to reapply their
113
+ * defaults.
114
+ */
115
+ get maxSampleWindowMillis(): number;
116
+ /**
117
+ * Signal names are the keys of the reported {@link SystemInfo}, so a duplicate would leave a status object that
118
+ * contradicts actual behavior: both signals are still evaluated (any overloaded one holds concurrency down), but
119
+ * only the last is reported.
120
+ */
121
+ private assertUniqueSignalNames;
114
122
  /**
115
123
  * Returns an {@link SystemInfo} object with the following structure:
116
124
  *
@@ -140,42 +148,12 @@ export declare class SystemStatus {
140
148
  * }
141
149
  * ```
142
150
  *
143
- * Where the `isSystemIdle` property is set to `false` if the system
144
- * has been overloaded in the full history of the {@link Snapshotter}
145
- * (which is configurable in the {@link Snapshotter}) and `true` otherwise.
151
+ * Where the `isSystemIdle` property is set to `false` if the system has been overloaded within the last
152
+ * `historySecs` seconds and `true` otherwise.
146
153
  */
147
154
  getHistoricalStatus(): SystemInfo;
148
155
  /**
149
156
  * Returns a system status object.
150
157
  */
151
- protected _isSystemIdle(sampleDurationMillis?: number): SystemInfo;
152
- /**
153
- * Returns an object with an isOverloaded property set to true
154
- * if the memory has been overloaded in the last sampleDurationMillis.
155
- */
156
- protected _isMemoryOverloaded(sampleDurationMillis?: number): ClientInfo;
157
- /**
158
- * Returns an object with an isOverloaded property set to true
159
- * if the event loop has been overloaded in the last sampleDurationMillis.
160
- */
161
- protected _isEventLoopOverloaded(sampleDurationMillis?: number): ClientInfo;
162
- /**
163
- * Returns an object with an isOverloaded property set to true
164
- * if the CPU has been overloaded in the last sampleDurationMillis.
165
- */
166
- protected _isCpuOverloaded(sampleDurationMillis?: number): ClientInfo;
167
- /**
168
- * Returns an object with an isOverloaded property set to true
169
- * if the client has been overloaded in the last sampleDurationMillis.
170
- */
171
- protected _isClientOverloaded(sampleDurationMillis?: number): ClientInfo;
172
- /**
173
- * Returns an object with sample information and an isOverloaded property
174
- * set to true if at least the ratio of snapshots in the sample are overloaded.
175
- */
176
- protected _isSampleOverloaded<T extends {
177
- createdAt: Date;
178
- isOverloaded: boolean;
179
- }>(sample: T[], ratio: number): ClientInfo;
158
+ private isSystemIdle;
180
159
  }
181
- //# sourceMappingURL=system_status.d.ts.map