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

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
@@ -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 { CpuLoadSignalOptions } from './cpu_load_signal.js';
2
+ import type { EventLoopLoadSignalOptions } from './event_loop_load_signal.js';
3
+ import type { LoadSignal, LoadSignalStartContext } from './load_signal.js';
4
+ import type { MemoryLoadSignalOptions } from './memory_load_signal.js';
5
+ import type { StorageBackendLoadSignalOptions } from './storage_backend_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 StorageBackendLoadSignal} (snapshot interval + error limit + overload ratio),
35
+ * or `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
+ storageBackend?: StorageBackendLoadSignalOptions | 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 StorageBackendLoadSignal} — constructing
57
+ * the ones 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
@@ -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 { CpuLoadSignal } from './cpu_load_signal.js';
2
+ import { EventLoopLoadSignal } from './event_loop_load_signal.js';
3
+ import { MemoryLoadSignal } from './memory_load_signal.js';
4
+ import { StorageBackendLoadSignal } from './storage_backend_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 StorageBackendLoadSignal} constructing
8
+ * the ones 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. `storageBackend: false`).
16
+ #memorySignal;
17
+ #eventLoopSignal;
18
+ #cpuSignal;
19
+ #storageBackendSignal;
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.#storageBackendSignal,
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 = {}, storageBackend = {} } = 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 (storageBackend !== false)
48
+ this.#storageBackendSignal = new StorageBackendLoadSignal(storageBackend);
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
@@ -0,0 +1,56 @@
1
+ import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
2
+ /**
3
+ * A snapshot produced by the built-in storage backend (rate-limit) signal.
4
+ * @internal
5
+ */
6
+ export interface StorageBackendSnapshot extends LoadSnapshot {
7
+ rateLimitErrorCount: number;
8
+ }
9
+ /**
10
+ * Tuning for the built-in **storage backend** (rate-limit) load signal, as accepted both by
11
+ * {@link StorageBackendLoadSignal} and by the
12
+ * {@link LoadSignalsOptions.storageBackend|`storageBackend`} shorthand on {@link LoadSignalsOptions}.
13
+ */
14
+ export interface StorageBackendLoadSignalOptions {
15
+ /**
16
+ * Defines the interval of checking the current state of the storage backend, in seconds.
17
+ * @default 1
18
+ */
19
+ snapshotIntervalSecs?: number;
20
+ /**
21
+ * Defines the maximum number of new rate limit errors within the given interval.
22
+ * @default 3
23
+ */
24
+ maxErrors?: number;
25
+ /**
26
+ * Maximum ratio of overloaded snapshots in a sample before the storage backend counts as overloaded.
27
+ * @default 0.3
28
+ */
29
+ overloadedRatio?: number;
30
+ }
31
+ /**
32
+ * Periodically checks the storage backend for rate-limit errors (HTTP 429) and reports overload when the error delta
33
+ * exceeds a threshold.
34
+ *
35
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
36
+ *
37
+ * Switch it off entirely ({@link LoadSignalsOptions.storageBackend|`storageBackend: false`}) if the storage backend
38
+ * reports no rate-limit statistics, since it otherwise polls it every second to no purpose.
39
+ *
40
+ * @category Scaling
41
+ */
42
+ export declare class StorageBackendLoadSignal implements LoadSignal {
43
+ #private;
44
+ readonly name = "storageBackendInfo";
45
+ readonly overloadedRatio: number;
46
+ constructor(options?: StorageBackendLoadSignalOptions);
47
+ start(context: LoadSignalStartContext): Promise<void>;
48
+ stop(): Promise<void>;
49
+ getSample(sampleDurationMillis?: number): LoadSnapshot[];
50
+ /**
51
+ * Records one snapshot, overloaded when rate-limit errors grew by more than the configured limit since the
52
+ * previous one.
53
+ * @internal Also lets tests drive the measurement without waiting on a timer.
54
+ */
55
+ handle(intervalCallback: () => unknown): void;
56
+ }