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

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 +40 -27
  51. package/enqueue_links/shared.js +90 -68
  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 +825 -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
@@ -0,0 +1,104 @@
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 client signals read the last entry to measure change since it).
61
+ */
62
+ getAll() {
63
+ return this.#snapshots;
64
+ }
65
+ /**
66
+ * Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
67
+ * samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
68
+ * snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
69
+ * rather than on stop leaves a finished session readable.
70
+ */
71
+ clear() {
72
+ this.#snapshots = [];
73
+ }
74
+ }
75
+ /**
76
+ * Evaluate whether a sample of `LoadSnapshot` values exceeds the given
77
+ * overloaded ratio, using a time-weighted average. This is the shared
78
+ * evaluation logic used by `SystemStatus` for all signal types.
79
+ * @internal
80
+ */
81
+ export function evaluateLoadSignalSample(sample, overloadedRatio) {
82
+ if (sample.length === 0) {
83
+ return {
84
+ isOverloaded: false,
85
+ limitRatio: overloadedRatio,
86
+ actualRatio: 0,
87
+ };
88
+ }
89
+ const weights = [];
90
+ const values = [];
91
+ for (let i = 1; i < sample.length; i++) {
92
+ const previous = sample[i - 1];
93
+ const current = sample[i];
94
+ const weight = +current.createdAt - +previous.createdAt;
95
+ weights.push(weight || 1); // Prevent errors from 0ms long intervals (sync) between snapshots.
96
+ values.push(+current.isOverloaded);
97
+ }
98
+ const wAvg = sample.length === 1 ? +sample[0].isOverloaded : weightedAvg(values, weights);
99
+ return {
100
+ isOverloaded: wAvg > overloadedRatio,
101
+ limitRatio: overloadedRatio,
102
+ actualRatio: Math.round(wAvg * 1000) / 1000,
103
+ };
104
+ }
@@ -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,105 @@
1
+ import { serviceLocator } from '../service_locator.js';
2
+ import { getMemoryInfo } from '../system-info/memory-info.js';
3
+ import { isContainerized } from '../system-info/runtime.js';
4
+ import { SnapshotStore } from './load_signal.js';
5
+ const RESERVE_MEMORY_RATIO = 0.5;
6
+ const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10_000;
7
+ /**
8
+ * Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a
9
+ * threshold. Also warns when memory use becomes critical.
10
+ *
11
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
12
+ *
13
+ * @category Scaling
14
+ */
15
+ export class MemoryLoadSignal {
16
+ name = 'memInfo';
17
+ overloadedRatio;
18
+ #store = new SnapshotStore();
19
+ #maxUsedRatio;
20
+ /** All resolved in `start()`, before anything that reads them can fire. */
21
+ #config;
22
+ #log;
23
+ #maxMemoryBytes;
24
+ #events;
25
+ #maxMemoryRatio;
26
+ #lastLoggedCriticalMemoryOverloadAt = null;
27
+ constructor(options = {}) {
28
+ this.#maxUsedRatio = options.maxUsedRatio ?? 0.9;
29
+ this.overloadedRatio = options.overloadedRatio ?? 0.2;
30
+ this.handle = this.handle.bind(this);
31
+ }
32
+ async start(context) {
33
+ this.#store.useSampleWindow(context.maxSampleWindowMillis);
34
+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.
35
+ this.#store.clear();
36
+ // Resolved here rather than in the constructor: an instance built ahead of time (to be wrapped, or shared
37
+ // between systems) must not capture whichever services happened to be registered at that moment.
38
+ this.#config = serviceLocator.getConfiguration();
39
+ this.#events = serviceLocator.getEventManager();
40
+ this.#log = serviceLocator.getLogger().child({ prefix: 'MemoryLoadSignal' });
41
+ const memoryMbytes = this.#config.memoryMbytes ?? 0;
42
+ if (memoryMbytes > 0) {
43
+ this.#maxMemoryBytes = memoryMbytes * 1024 * 1024;
44
+ }
45
+ else {
46
+ this.#maxMemoryRatio = this.#config.availableMemoryRatio;
47
+ if (!this.#maxMemoryRatio) {
48
+ throw new Error('availableMemoryRatio is not set in configuration.');
49
+ }
50
+ else {
51
+ this.#log.debug(`Setting max memory of this run to ${this.#maxMemoryRatio * 100} % of available memory. ` +
52
+ 'Use the CRAWLEE_MEMORY_MBYTES or CRAWLEE_AVAILABLE_MEMORY_RATIO environment variable to override it.');
53
+ }
54
+ // Fallback memory measurement in case memTotalBytes is missing from SystemInfo.
55
+ this.#maxMemoryBytes = await this.getTotalMemoryBytes();
56
+ }
57
+ this.#events.on("systemInfo" /* EventType.SYSTEM_INFO */, this.handle);
58
+ }
59
+ async stop() {
60
+ this.#events?.off("systemInfo" /* EventType.SYSTEM_INFO */, this.handle);
61
+ this.#events = undefined;
62
+ }
63
+ getSample(sampleDurationMillis) {
64
+ return this.#store.getSample(sampleDurationMillis);
65
+ }
66
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
67
+ handle(systemInfo) {
68
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
69
+ const { memCurrentBytes, memTotalBytes } = systemInfo;
70
+ let maxMemoryBytes = this.#maxMemoryBytes;
71
+ if (this.#maxMemoryRatio !== undefined && this.#maxMemoryRatio > 0) {
72
+ maxMemoryBytes = this.#maxMemoryRatio * (memTotalBytes ?? this.#maxMemoryBytes);
73
+ }
74
+ const snapshot = {
75
+ createdAt,
76
+ isOverloaded: memCurrentBytes / maxMemoryBytes > this.#maxUsedRatio,
77
+ usedBytes: memCurrentBytes,
78
+ };
79
+ this.#store.push(snapshot, createdAt);
80
+ this.memoryOverloadWarning(systemInfo, maxMemoryBytes);
81
+ }
82
+ memoryOverloadWarning(systemInfo, maxMemoryBytes) {
83
+ const effectiveMax = maxMemoryBytes ?? this.#maxMemoryBytes;
84
+ const { memCurrentBytes } = systemInfo;
85
+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
86
+ if (this.#lastLoggedCriticalMemoryOverloadAt &&
87
+ +createdAt < +this.#lastLoggedCriticalMemoryOverloadAt + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS)
88
+ return;
89
+ const maxDesiredMemoryBytes = this.#maxUsedRatio * effectiveMax;
90
+ const reserveMemory = effectiveMax * (1 - this.#maxUsedRatio) * RESERVE_MEMORY_RATIO;
91
+ const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;
92
+ const isCriticalOverload = memCurrentBytes > criticalOverloadBytes;
93
+ if (isCriticalOverload) {
94
+ const usedPercentage = Math.round((memCurrentBytes / effectiveMax) * 100);
95
+ const toMb = (bytes) => Math.round(bytes / 1024 ** 2);
96
+ this.#log.warning('Memory is critically overloaded. ' +
97
+ `Using ${toMb(memCurrentBytes)} MB of ${toMb(effectiveMax)} MB (${usedPercentage}%). Consider increasing available memory.`);
98
+ this.#lastLoggedCriticalMemoryOverloadAt = createdAt;
99
+ }
100
+ }
101
+ async getTotalMemoryBytes() {
102
+ const containerized = this.#config.containerized ?? (await isContainerized());
103
+ return (await getMemoryInfo({ containerized, logger: serviceLocator.getLogger() })).totalBytes;
104
+ }
105
+ }
@@ -1,189 +1,84 @@
1
- import type { StorageClient } from '@crawlee/types';
2
- import type { Log } from '@apify/log';
3
- import type { BetterIntervalID } from '@apify/utilities';
4
- import { Configuration } from '../configuration.js';
5
- import type { EventManager } from '../events/event_manager.js';
6
- import type { SystemInfo } from './system_status.js';
7
- export interface SnapshotterOptions {
8
- /**
9
- * Defines the interval of measuring the event loop response time.
10
- * @default 0.5
11
- */
12
- eventLoopSnapshotIntervalSecs?: number;
1
+ import type { ClientLoadSignalOptions } from './client_load_signal.js';
2
+ import type { CpuLoadSignalOptions } from './cpu_load_signal.js';
3
+ import type { EventLoopLoadSignalOptions } from './event_loop_load_signal.js';
4
+ import type { LoadSignal, LoadSignalStartContext } from './load_signal.js';
5
+ import type { MemoryLoadSignalOptions } from './memory_load_signal.js';
6
+ /**
7
+ * The load signals a {@link ConcurrencySystem} watches to decide whether the machine is overloaded.
8
+ *
9
+ * Each of the four built-in signals is configured by passing its options bag — shorthand for constructing the
10
+ * corresponding {@link LoadSignal} class yourself, so `{ cpu: { overloadedRatio: 0.5 } }` is exactly
11
+ * `{ cpu: false, custom: [new CpuLoadSignal({ overloadedRatio: 0.5 })] }`. Pass `false` to leave a resource
12
+ * unwatched, and put anything else you want taken into account in {@link LoadSignalsOptions.custom|`custom`}.
13
+ *
14
+ * How far back the signals are evaluated is *not* set here, but by
15
+ * {@link ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`} and
16
+ * {@link ConcurrencySystemOptions.currentHistorySecs|`currentHistorySecs`}.
17
+ */
18
+ export interface LoadSignalsOptions {
13
19
  /**
14
- * Defines the interval of checking the current state
15
- * of the remote API client.
16
- * @default 1
20
+ * Tuning for the built-in {@link MemoryLoadSignal} (used-memory limit + overload ratio), or `false` to switch
21
+ * it off.
17
22
  */
18
- clientSnapshotIntervalSecs?: number;
23
+ memory?: MemoryLoadSignalOptions | false;
19
24
  /**
20
- * Maximum allowed delay of the event loop in milliseconds.
21
- * Exceeding this limit overloads the event loop.
22
- * @default 50
25
+ * Tuning for the built-in {@link EventLoopLoadSignal} (snapshot interval + blocked-millis limit + overload
26
+ * ratio), or `false` to switch it off — which also stops its measuring interval.
23
27
  */
24
- maxBlockedMillis?: number;
28
+ eventLoop?: EventLoopLoadSignalOptions | false;
25
29
  /**
26
- * Defines the maximum ratio of total memory that can be used.
27
- * Exceeding this limit overloads the memory.
28
- * @default 0.9
30
+ * Tuning for the built-in {@link CpuLoadSignal} (overload ratio), or `false` to switch it off.
29
31
  */
30
- maxUsedMemoryRatio?: number;
32
+ cpu?: CpuLoadSignalOptions | false;
31
33
  /**
32
- * Defines the maximum number of new rate limit errors within
33
- * the given interval.
34
- * @default 1
34
+ * Tuning for the built-in {@link ClientLoadSignal} (snapshot interval + error limit + overload ratio), or
35
+ * `false` to switch it off — worth doing when the storage backend reports no rate-limit statistics, since the
36
+ * signal otherwise polls it every second to no purpose.
35
37
  */
36
- maxClientErrors?: number;
38
+ client?: ClientLoadSignalOptions | false;
37
39
  /**
38
- * Sets the interval in seconds for which a history of resource snapshots
39
- * will be kept. Increasing this to very high numbers will affect performance.
40
- * @default 60
40
+ * Additional {@link LoadSignal} implementations e.g. navigation timeouts or proxy health — evaluated
41
+ * alongside the built-in four. If any signal reports overload, the system counts as overloaded. Their lifecycle
42
+ * is driven by the {@link ConcurrencySystem} they are given to, and their {@link LoadSignal.name|names} must
43
+ * not collide with an enabled built-in's.
41
44
  */
42
- snapshotHistorySecs?: number;
43
- /** @internal */
44
- log?: Log;
45
- /** @internal */
46
- client?: StorageClient;
47
- /** @internal */
48
- config?: Configuration;
49
- }
50
- interface MemorySnapshot {
51
- createdAt: Date;
52
- isOverloaded: boolean;
53
- usedBytes?: number;
54
- }
55
- interface CpuSnapshot {
56
- createdAt: Date;
57
- isOverloaded: boolean;
58
- usedRatio: number;
59
- ticks?: {
60
- idle: number;
61
- total: number;
62
- };
63
- }
64
- interface EventLoopSnapshot {
65
- createdAt: Date;
66
- isOverloaded: boolean;
67
- exceededMillis: number;
68
- }
69
- interface ClientSnapshot {
70
- createdAt: Date;
71
- isOverloaded: boolean;
72
- rateLimitErrorCount: number;
45
+ custom?: LoadSignal[];
73
46
  }
74
47
  /**
75
- * Creates snapshots of system resources at given intervals and marks the resource
76
- * as either overloaded or not during the last interval. Keeps a history of the snapshots.
77
- * It tracks the following resources: Memory, EventLoop, API and CPU.
78
- * The class is used by the {@link AutoscaledPool} class.
79
- *
80
- * When running on the Apify platform, the CPU and memory statistics are provided by the platform,
81
- * as collected from the running Docker container. When running locally, `Snapshotter`
82
- * makes its own statistics by querying the OS.
83
- *
84
- * CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or
85
- * when Apify platform marks it as overloaded.
86
- *
87
- * Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option.
88
- * It's computed using the total memory available to the container when running on
89
- * the Apify platform and a quarter of total system memory when running locally.
90
- * Max total memory when running locally may be overridden by using the `CRAWLEE_MEMORY_MBYTES`
91
- * environment variable.
92
- *
93
- * Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.
48
+ * An implementation detail of the {@link ConcurrencySystem}: the built-in signal tuning from
49
+ * {@link LoadSignalsOptions}, minus the custom signals, which the system evaluates itself rather than collecting
50
+ * them here.
51
+ * @internal
52
+ */
53
+ export type SnapshotterOptions = Omit<LoadSignalsOptions, 'custom'>;
54
+ /**
55
+ * Owns the four built-in {@link LoadSignal} instances — {@link MemoryLoadSignal},
56
+ * {@link EventLoopLoadSignal}, {@link CpuLoadSignal} and {@link ClientLoadSignal} — constructing the ones
57
+ * that were not switched off and driving their shared lifecycle.
94
58
  *
95
- * Client becomes overloaded when rate limit errors (429 - Too Many Requests),
96
- * typically received from the request queue, exceed the set limit within the set interval.
97
- * @category Scaling
59
+ * Configured indirectly through {@link ConcurrencySystemOptions.loadSignals|`loadSignals`}, whose per-signal bags
60
+ * are simply forwarded to the corresponding constructor.
61
+ * @internal
98
62
  */
99
63
  export declare class Snapshotter {
100
- log: Log;
101
- client: StorageClient;
102
- config: Configuration;
103
- events: EventManager;
104
- eventLoopSnapshotIntervalMillis: number;
105
- clientSnapshotIntervalMillis: number;
106
- snapshotHistoryMillis: number;
107
- maxBlockedMillis: number;
108
- maxUsedMemoryRatio: number;
109
- maxClientErrors: number;
110
- maxMemoryBytes: number;
111
- cpuSnapshots: CpuSnapshot[];
112
- eventLoopSnapshots: EventLoopSnapshot[];
113
- memorySnapshots: MemorySnapshot[];
114
- clientSnapshots: ClientSnapshot[];
115
- eventLoopInterval: BetterIntervalID;
116
- clientInterval: BetterIntervalID;
117
- lastLoggedCriticalMemoryOverloadAt: Date | null;
64
+ #private;
65
+ /**
66
+ * Returns the enabled built-in signals, so `SystemStatus` can iterate them alongside any custom `LoadSignal`
67
+ * instances. Signals switched off through the options are simply absent — the system status reports them as
68
+ * not overloaded.
69
+ */
70
+ getLoadSignals(): LoadSignal[];
118
71
  /**
119
72
  * @param [options] All `Snapshotter` configuration options.
120
73
  */
121
74
  constructor(options?: SnapshotterOptions);
122
75
  /**
123
- * Starts capturing snapshots at configured intervals.
76
+ * Starts capturing snapshots at configured intervals. The `context` carries the sample window the signals will
77
+ * be queried with, which is also how much history they retain.
124
78
  */
125
- start(): Promise<void>;
79
+ start(context: LoadSignalStartContext): Promise<void>;
126
80
  /**
127
81
  * Stops all resource capturing.
128
82
  */
129
83
  stop(): Promise<void>;
130
- /**
131
- * Returns a sample of latest memory snapshots, with the size of the sample defined
132
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
133
- */
134
- getMemorySample(sampleDurationMillis?: number): MemorySnapshot[];
135
- /**
136
- * Returns a sample of latest event loop snapshots, with the size of the sample defined
137
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
138
- */
139
- getEventLoopSample(sampleDurationMillis?: number): EventLoopSnapshot[];
140
- /**
141
- * Returns a sample of latest CPU snapshots, with the size of the sample defined
142
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
143
- */
144
- getCpuSample(sampleDurationMillis?: number): CpuSnapshot[];
145
- /**
146
- * Returns a sample of latest Client snapshots, with the size of the sample defined
147
- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
148
- */
149
- getClientSample(sampleDurationMillis?: number): ClientSnapshot[];
150
- /**
151
- * Finds the latest snapshots by sampleDurationMillis in the provided array.
152
- */
153
- protected _getSample<T extends {
154
- createdAt: Date;
155
- }>(snapshots: T[], sampleDurationMillis?: number): T[];
156
- /**
157
- * Creates a snapshot of current memory usage
158
- * using the Apify platform `systemInfo` event.
159
- */
160
- protected _snapshotMemory(systemInfo: SystemInfo): void;
161
- /**
162
- * Checks for critical memory overload and logs it to the console.
163
- */
164
- protected _memoryOverloadWarning(systemInfo: SystemInfo): void;
165
- /**
166
- * Creates a snapshot of current event loop delay.
167
- */
168
- protected _snapshotEventLoop(intervalCallback: () => unknown): void;
169
- /**
170
- * Creates a snapshot of current CPU usage using the Apify platform `systemInfo` event.
171
- */
172
- protected _snapshotCpu(systemInfo: SystemInfo): void;
173
- /**
174
- * Creates a snapshot of current API state by checking for
175
- * rate limit errors. Only errors produced by a 2nd retry
176
- * of the API call are considered for snapshotting since
177
- * earlier errors may just be caused by a random spike in
178
- * number of requests and do not necessarily signify API
179
- * overloading.
180
- */
181
- protected _snapshotClient(intervalCallback: () => unknown): void;
182
- /**
183
- * Removes snapshots that are older than the snapshotHistorySecs option
184
- * from the array (destructively - in place).
185
- */
186
- protected _pruneSnapshots(snapshots: MemorySnapshot[] | CpuSnapshot[] | EventLoopSnapshot[] | ClientSnapshot[], now: Date): void;
187
84
  }
188
- export {};
189
- //# sourceMappingURL=snapshotter.d.ts.map