@crawlee/core 4.0.0-beta.13 → 4.0.0-beta.131

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 (280) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +362 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  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 +3 -2
  29. package/cookie_utils.js +18 -7
  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 -129
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  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 +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +68 -154
  47. package/enqueue_links/enqueue_links.js +38 -210
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +52 -26
  51. package/enqueue_links/shared.js +115 -66
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  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 +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +108 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +201 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +409 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +14 -13
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +32 -147
  89. package/recoverable_state.d.ts +155 -0
  90. package/recoverable_state.js +231 -0
  91. package/request.d.ts +80 -16
  92. package/request.js +147 -68
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +73 -91
  110. package/session_pool/session_pool.js +172 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +291 -148
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +445 -169
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -115
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -82
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js +0 -430
  269. package/storages/sitemap_request_list.js.map +0 -1
  270. package/storages/storage_manager.d.ts +0 -58
  271. package/storages/storage_manager.d.ts.map +0 -1
  272. package/storages/storage_manager.js +0 -105
  273. package/storages/storage_manager.js.map +0 -1
  274. package/storages/utils.d.ts.map +0 -1
  275. package/storages/utils.js.map +0 -1
  276. package/tsconfig.build.tsbuildinfo +0 -1
  277. package/typedefs.d.ts.map +0 -1
  278. package/typedefs.js.map +0 -1
  279. package/validators.d.ts.map +0 -1
  280. package/validators.js.map +0 -1
@@ -0,0 +1,47 @@
1
+ import { EventType } from '../events/event_manager.js';
2
+ import { serviceLocator } from '../service_locator.js';
3
+ import { SnapshotStore } from './load_signal.js';
4
+ /**
5
+ * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when the platform or local OS metrics indicate the
6
+ * CPU is overloaded.
7
+ *
8
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
9
+ *
10
+ * @category Scaling
11
+ */
12
+ export class CpuLoadSignal {
13
+ name = 'cpuInfo';
14
+ overloadedRatio;
15
+ #store = new SnapshotStore();
16
+ #events;
17
+ constructor(options = {}) {
18
+ this.overloadedRatio = options.overloadedRatio ?? 0.4;
19
+ this.handle = this.handle.bind(this);
20
+ }
21
+ async start(context) {
22
+ this.#store.useSampleWindow(context.maxSampleWindowMillis);
23
+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.
24
+ this.#store.clear();
25
+ // Resolved here rather than in the constructor, so an instance built ahead of time (to be wrapped, or shared
26
+ // between systems) cannot capture whichever event manager happened to be registered at that moment.
27
+ this.#events = serviceLocator.getEventManager();
28
+ this.#events.on(EventType.SYSTEM_INFO, this.handle);
29
+ }
30
+ async stop() {
31
+ this.#events?.off(EventType.SYSTEM_INFO, this.handle);
32
+ this.#events = undefined;
33
+ }
34
+ getSample(sampleDurationMillis) {
35
+ return this.#store.getSample(sampleDurationMillis);
36
+ }
37
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
38
+ handle(systemInfo) {
39
+ const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;
40
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
41
+ this.#store.push({
42
+ createdAt,
43
+ isOverloaded: isCpuOverloaded,
44
+ usedRatio: Math.ceil(cpuCurrentUsage / 100),
45
+ }, createdAt);
46
+ }
47
+ }
@@ -0,0 +1,51 @@
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
+ #private;
40
+ readonly name = "eventLoopInfo";
41
+ readonly overloadedRatio: number;
42
+ constructor(options?: EventLoopLoadSignalOptions);
43
+ start(context: LoadSignalStartContext): Promise<void>;
44
+ stop(): Promise<void>;
45
+ getSample(sampleDurationMillis?: number): LoadSnapshot[];
46
+ /**
47
+ * Records one snapshot: how much later than scheduled this tick ran is how long the loop was blocked.
48
+ * @internal Also lets tests drive the measurement without waiting on a timer.
49
+ */
50
+ handle(intervalCallback: () => unknown): void;
51
+ }
@@ -0,0 +1,60 @@
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,4 +1,9 @@
1
1
  export * from './autoscaled_pool.js';
2
+ export * from './concurrency_system.js';
3
+ export * from './cpu_load_signal.js';
4
+ export * from './event_loop_load_signal.js';
5
+ export * from './load_signal.js';
6
+ export * from './memory_load_signal.js';
2
7
  export * from './snapshotter.js';
8
+ export * from './storage_backend_load_signal.js';
3
9
  export * from './system_status.js';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,9 @@
1
1
  export * from './autoscaled_pool.js';
2
+ export * from './concurrency_system.js';
3
+ export * from './cpu_load_signal.js';
4
+ export * from './event_loop_load_signal.js';
5
+ export * from './load_signal.js';
6
+ export * from './memory_load_signal.js';
2
7
  export * from './snapshotter.js';
8
+ export * from './storage_backend_load_signal.js';
3
9
  export * from './system_status.js';
4
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,100 @@
1
+ import type { LoadSignalInfo } 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 backend 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`, `storageBackendInfo`) land in the correspondingly named `SystemInfo` fields rather
36
+ * than the `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;
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 storage backend signals read the last entry to measure change since
83
+ * it).
84
+ */
85
+ getAll(): T[];
86
+ /**
87
+ * Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
88
+ * samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
89
+ * snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
90
+ * rather than on stop leaves a finished session readable.
91
+ */
92
+ clear(): void;
93
+ }
94
+ /**
95
+ * Evaluate whether a sample of `LoadSnapshot` values exceeds the given
96
+ * overloaded ratio, using a time-weighted average. This is the shared
97
+ * evaluation logic used by `SystemStatus` for all signal types.
98
+ * @internal
99
+ */
100
+ export declare function evaluateLoadSignalSample(sample: LoadSnapshot[], overloadedRatio: number): LoadSignalInfo;
@@ -0,0 +1,105 @@
1
+ import { weightedAvg } from './weighted_avg.js';
2
+ /**
3
+ * A time-pruning, time-windowed store for `LoadSnapshot` values. All four built-in signals compose with one of these,
4
+ * and so can yours — it is the only part of their machinery worth reusing.
5
+ */
6
+ export class SnapshotStore {
7
+ #snapshots = [];
8
+ /** Retention window in milliseconds. Unbounded until {@link SnapshotStore.useSampleWindow|`useSampleWindow()`}. */
9
+ // kept as TS-private: concurrency_system tests read this retention window directly
10
+ historyMillis = Infinity;
11
+ /**
12
+ * Sizes retention to the window the signal will be sampled over, as handed to it in
13
+ * {@link LoadSignal.start|`start()`}. Until this is called nothing is pruned at all, so a signal that ignores
14
+ * its start context grows unboundedly.
15
+ */
16
+ useSampleWindow(maxSampleWindowMillis) {
17
+ this.historyMillis = maxSampleWindowMillis;
18
+ }
19
+ /**
20
+ * Add a snapshot and prune entries older than the history window.
21
+ */
22
+ push(snapshot, now = snapshot.createdAt) {
23
+ // Inline pruning to avoid private-method transpilation issues
24
+ let oldCount = 0;
25
+ for (let i = 0; i < this.#snapshots.length; i++) {
26
+ const { createdAt } = this.#snapshots[i];
27
+ if (now.getTime() - new Date(createdAt).getTime() > this.historyMillis)
28
+ oldCount++;
29
+ else
30
+ break;
31
+ }
32
+ if (oldCount)
33
+ this.#snapshots.splice(0, oldCount);
34
+ this.#snapshots.push(snapshot);
35
+ }
36
+ /**
37
+ * Return all snapshots, or only those within the given time window.
38
+ */
39
+ getSample(sampleDurationMillis) {
40
+ if (!sampleDurationMillis)
41
+ return this.#snapshots;
42
+ const sample = [];
43
+ let idx = this.#snapshots.length;
44
+ if (!idx)
45
+ return sample;
46
+ const latestTime = this.#snapshots[idx - 1].createdAt;
47
+ while (idx--) {
48
+ const snapshot = this.#snapshots[idx];
49
+ if (+latestTime - +snapshot.createdAt <= sampleDurationMillis) {
50
+ sample.unshift(snapshot);
51
+ }
52
+ else {
53
+ break;
54
+ }
55
+ }
56
+ return sample;
57
+ }
58
+ /**
59
+ * Direct, unwindowed access to the underlying array — used by signals whose handler needs the previous snapshot
60
+ * to compute a delta (e.g. the event loop and storage backend signals read the last entry to measure change since
61
+ * it).
62
+ */
63
+ getAll() {
64
+ return this.#snapshots;
65
+ }
66
+ /**
67
+ * Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
68
+ * samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
69
+ * snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
70
+ * rather than on stop leaves a finished session readable.
71
+ */
72
+ clear() {
73
+ this.#snapshots = [];
74
+ }
75
+ }
76
+ /**
77
+ * Evaluate whether a sample of `LoadSnapshot` values exceeds the given
78
+ * overloaded ratio, using a time-weighted average. This is the shared
79
+ * evaluation logic used by `SystemStatus` for all signal types.
80
+ * @internal
81
+ */
82
+ export function evaluateLoadSignalSample(sample, overloadedRatio) {
83
+ if (sample.length === 0) {
84
+ return {
85
+ isOverloaded: false,
86
+ limitRatio: overloadedRatio,
87
+ actualRatio: 0,
88
+ };
89
+ }
90
+ const weights = [];
91
+ const values = [];
92
+ for (let i = 1; i < sample.length; i++) {
93
+ const previous = sample[i - 1];
94
+ const current = sample[i];
95
+ const weight = +current.createdAt - +previous.createdAt;
96
+ weights.push(weight || 1); // Prevent errors from 0ms long intervals (sync) between snapshots.
97
+ values.push(+current.isOverloaded);
98
+ }
99
+ const wAvg = sample.length === 1 ? +sample[0].isOverloaded : weightedAvg(values, weights);
100
+ return {
101
+ isOverloaded: wAvg > overloadedRatio,
102
+ limitRatio: overloadedRatio,
103
+ actualRatio: Math.round(wAvg * 1000) / 1000,
104
+ };
105
+ }
@@ -0,0 +1,47 @@
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 memory signal.
5
+ * @internal
6
+ */
7
+ export interface MemorySnapshot extends LoadSnapshot {
8
+ usedBytes?: number;
9
+ }
10
+ /**
11
+ * Tuning for the built-in **memory** load signal, as accepted both by {@link MemoryLoadSignal} and by the
12
+ * {@link LoadSignalsOptions.memory|`memory`} shorthand on {@link LoadSignalsOptions}.
13
+ */
14
+ export interface MemoryLoadSignalOptions {
15
+ /**
16
+ * Defines the maximum ratio of total memory that can be used.
17
+ * Exceeding this limit overloads the memory.
18
+ * @default 0.9
19
+ */
20
+ maxUsedRatio?: number;
21
+ /**
22
+ * Maximum ratio of overloaded snapshots in a sample before memory counts as overloaded.
23
+ * @default 0.2
24
+ */
25
+ overloadedRatio?: number;
26
+ }
27
+ /**
28
+ * Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a
29
+ * threshold. Also warns when memory use becomes critical.
30
+ *
31
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
32
+ *
33
+ * @category Scaling
34
+ */
35
+ export declare class MemoryLoadSignal implements LoadSignal {
36
+ #private;
37
+ readonly name = "memInfo";
38
+ readonly overloadedRatio: number;
39
+ constructor(options?: MemoryLoadSignalOptions);
40
+ start(context: LoadSignalStartContext): Promise<void>;
41
+ stop(): Promise<void>;
42
+ getSample(sampleDurationMillis?: number): LoadSnapshot[];
43
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
44
+ handle(systemInfo: SystemInfo): void;
45
+ private memoryOverloadWarning;
46
+ private getTotalMemoryBytes;
47
+ }
@@ -0,0 +1,106 @@
1
+ import { EventType } from '../events/event_manager.js';
2
+ import { serviceLocator } from '../service_locator.js';
3
+ import { getMemoryInfo } from '../system-info/memory-info.js';
4
+ import { isContainerized } from '../system-info/runtime.js';
5
+ import { SnapshotStore } from './load_signal.js';
6
+ const RESERVE_MEMORY_RATIO = 0.5;
7
+ const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10_000;
8
+ /**
9
+ * Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a
10
+ * threshold. Also warns when memory use becomes critical.
11
+ *
12
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
13
+ *
14
+ * @category Scaling
15
+ */
16
+ export class MemoryLoadSignal {
17
+ name = 'memInfo';
18
+ overloadedRatio;
19
+ #store = new SnapshotStore();
20
+ #maxUsedRatio;
21
+ /** All resolved in `start()`, before anything that reads them can fire. */
22
+ #config;
23
+ #log;
24
+ #maxMemoryBytes;
25
+ #events;
26
+ #maxMemoryRatio;
27
+ #lastLoggedCriticalMemoryOverloadAt = null;
28
+ constructor(options = {}) {
29
+ this.#maxUsedRatio = options.maxUsedRatio ?? 0.9;
30
+ this.overloadedRatio = options.overloadedRatio ?? 0.2;
31
+ this.handle = this.handle.bind(this);
32
+ }
33
+ async start(context) {
34
+ this.#store.useSampleWindow(context.maxSampleWindowMillis);
35
+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.
36
+ this.#store.clear();
37
+ // Resolved here rather than in the constructor: an instance built ahead of time (to be wrapped, or shared
38
+ // between systems) must not capture whichever services happened to be registered at that moment.
39
+ this.#config = serviceLocator.getConfiguration();
40
+ this.#events = serviceLocator.getEventManager();
41
+ this.#log = serviceLocator.getLogger().child({ prefix: 'MemoryLoadSignal' });
42
+ const memoryMbytes = this.#config.memoryMbytes ?? 0;
43
+ if (memoryMbytes > 0) {
44
+ this.#maxMemoryBytes = memoryMbytes * 1024 * 1024;
45
+ }
46
+ else {
47
+ this.#maxMemoryRatio = this.#config.availableMemoryRatio;
48
+ if (!this.#maxMemoryRatio) {
49
+ throw new Error('availableMemoryRatio is not set in configuration.');
50
+ }
51
+ else {
52
+ this.#log.debug(`Setting max memory of this run to ${this.#maxMemoryRatio * 100} % of available memory. ` +
53
+ 'Use the CRAWLEE_MEMORY_MBYTES or CRAWLEE_AVAILABLE_MEMORY_RATIO environment variable to override it.');
54
+ }
55
+ // Fallback memory measurement in case memTotalBytes is missing from SystemInfo.
56
+ this.#maxMemoryBytes = await this.getTotalMemoryBytes();
57
+ }
58
+ this.#events.on(EventType.SYSTEM_INFO, this.handle);
59
+ }
60
+ async stop() {
61
+ this.#events?.off(EventType.SYSTEM_INFO, this.handle);
62
+ this.#events = undefined;
63
+ }
64
+ getSample(sampleDurationMillis) {
65
+ return this.#store.getSample(sampleDurationMillis);
66
+ }
67
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
68
+ handle(systemInfo) {
69
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
70
+ const { memCurrentBytes, memTotalBytes } = systemInfo;
71
+ let maxMemoryBytes = this.#maxMemoryBytes;
72
+ if (this.#maxMemoryRatio !== undefined && this.#maxMemoryRatio > 0) {
73
+ maxMemoryBytes = this.#maxMemoryRatio * (memTotalBytes ?? this.#maxMemoryBytes);
74
+ }
75
+ const snapshot = {
76
+ createdAt,
77
+ isOverloaded: memCurrentBytes / maxMemoryBytes > this.#maxUsedRatio,
78
+ usedBytes: memCurrentBytes,
79
+ };
80
+ this.#store.push(snapshot, createdAt);
81
+ this.memoryOverloadWarning(systemInfo, maxMemoryBytes);
82
+ }
83
+ memoryOverloadWarning(systemInfo, maxMemoryBytes) {
84
+ const effectiveMax = maxMemoryBytes ?? this.#maxMemoryBytes;
85
+ const { memCurrentBytes } = systemInfo;
86
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
87
+ if (this.#lastLoggedCriticalMemoryOverloadAt &&
88
+ +createdAt < +this.#lastLoggedCriticalMemoryOverloadAt + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS)
89
+ return;
90
+ const maxDesiredMemoryBytes = this.#maxUsedRatio * effectiveMax;
91
+ const reserveMemory = effectiveMax * (1 - this.#maxUsedRatio) * RESERVE_MEMORY_RATIO;
92
+ const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;
93
+ const isCriticalOverload = memCurrentBytes > criticalOverloadBytes;
94
+ if (isCriticalOverload) {
95
+ const usedPercentage = Math.round((memCurrentBytes / effectiveMax) * 100);
96
+ const toMb = (bytes) => Math.round(bytes / 1024 ** 2);
97
+ this.#log.warning('Memory is critically overloaded. ' +
98
+ `Using ${toMb(memCurrentBytes)} MB of ${toMb(effectiveMax)} MB (${usedPercentage}%). Consider increasing available memory.`);
99
+ this.#lastLoggedCriticalMemoryOverloadAt = createdAt;
100
+ }
101
+ }
102
+ async getTotalMemoryBytes() {
103
+ const containerized = this.#config.containerized ?? (await isContainerized());
104
+ return (await getMemoryInfo({ containerized, logger: serviceLocator.getLogger() })).totalBytes;
105
+ }
106
+ }