@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
@@ -0,0 +1,268 @@
1
+ import type { CrawleeLogger } from '../log.js';
2
+ import type { LoadSignalsOptions } from './snapshotter.js';
3
+ import type { SystemInfo } from './system_status.js';
4
+ export interface ConcurrencySystemOptions {
5
+ /**
6
+ * The minimum number of tasks running in parallel.
7
+ *
8
+ * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
9
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
10
+ * @default 1
11
+ */
12
+ minConcurrency?: number;
13
+ /**
14
+ * The maximum number of tasks running in parallel.
15
+ * @default 200
16
+ */
17
+ maxConcurrency?: number;
18
+ /**
19
+ * The desired number of tasks that should be running parallel on the start of the pool,
20
+ * if there is a large enough supply of them.
21
+ * By default, it is `minConcurrency`.
22
+ */
23
+ desiredConcurrency?: number;
24
+ /**
25
+ * Minimum level of desired concurrency to reach before more scaling up is allowed.
26
+ * @default 0.90
27
+ */
28
+ desiredConcurrencyRatio?: number;
29
+ /**
30
+ * Defines the fractional amount of desired concurrency to be added with each scaling up.
31
+ * The minimum scaling step is one.
32
+ * @default 0.05
33
+ */
34
+ scaleUpStepRatio?: number;
35
+ /**
36
+ * Defines the amount of desired concurrency to be subtracted with each scaling down.
37
+ * The minimum scaling step is one.
38
+ * @default 0.05
39
+ */
40
+ scaleDownStepRatio?: number;
41
+ /**
42
+ * Specifies a period in which the instance logs its state, in seconds.
43
+ * Set to `null` to disable periodic logging.
44
+ * @default 60
45
+ */
46
+ loggingIntervalSecs?: number | null;
47
+ /**
48
+ * Defines in seconds how often the system should attempt to adjust the desired concurrency
49
+ * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.
50
+ * We suggest using a value from 5 to 20.
51
+ * @default 10
52
+ */
53
+ autoscaleIntervalSecs?: number;
54
+ /**
55
+ * The signals that tell the system whether the machine is overloaded: per-resource tuning for the built-in four
56
+ * (memory, event loop, CPU, storage backend) plus any {@link LoadSignalsOptions.custom|`custom`}
57
+ * implementations of your own. See {@link LoadSignalsOptions}.
58
+ */
59
+ loadSignals?: LoadSignalsOptions;
60
+ /**
61
+ * How far back the **autoscaling** decisions look, in seconds — the window the historical system status is
62
+ * evaluated over, and therefore how much history the signals retain (the memory cost of raising it).
63
+ * @default 30
64
+ */
65
+ snapshotHistorySecs?: number;
66
+ /**
67
+ * How far back the **task-gating** decision looks, in seconds — the window used to judge whether the system is
68
+ * overloaded *right now*, before dispatching one more task. Deliberately shorter than
69
+ * {@link ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`}, so that dispatch reacts to
70
+ * spikes quickly while scaling stays stable.
71
+ * @default 5
72
+ */
73
+ currentHistorySecs?: number;
74
+ /**
75
+ * The maximum number of tasks per minute the system can run.
76
+ * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.
77
+ */
78
+ maxTasksPerMinute?: number;
79
+ log?: CrawleeLogger;
80
+ }
81
+ /**
82
+ * Identifies *who* is asking a governor for capacity: one {@link AutoscaledPool}, or the crawler driving it. The
83
+ * same object is passed on every call a pool makes, so per-consumer state can be keyed off it or off its `id`.
84
+ * @category Scaling
85
+ */
86
+ export interface ConcurrencyConsumer {
87
+ /** Process-unique and human-readable — a crawler's is its {@link BasicCrawlerOptions.id|`id`} option. */
88
+ readonly id: string;
89
+ }
90
+ /**
91
+ * The contract between an {@link AutoscaledPool} and its concurrency "governor" — the object that answers *is
92
+ * there free compute for one more task?* and tracks the budget that tasks are booked against.
93
+ * {@link ConcurrencySystem} is the canonical implementation; the interface lets alternate governors be substituted
94
+ * without depending on its internals.
95
+ *
96
+ * Every allocation method is told which {@link ConcurrencyConsumer|consumer} is asking, so an implementation can
97
+ * allocate per consumer. {@link ConcurrencySystem} does not: it serves whoever asks first, which can starve a pool
98
+ * that joins a saturated system late.
99
+ * @category Scaling
100
+ */
101
+ export interface IConcurrencySystem {
102
+ /**
103
+ * The number of tasks that should currently be running in parallel, assuming a sufficient supply of them. How it
104
+ * is derived is up to the implementation, hence read-only here — but it must always be at least `1`, or a pool
105
+ * could never start the first task.
106
+ */
107
+ readonly desiredConcurrency: number;
108
+ /** The number of parallel tasks currently booked against this governor, regardless of which pool booked them. */
109
+ readonly currentConcurrency: number;
110
+ /**
111
+ * Whether the governor is ready to be booked against. {@link AutoscaledPool.run|`pool.run()`} refuses to run
112
+ * when this is `false`. An implementation with no startup lifecycle simply reports `true`.
113
+ */
114
+ readonly isRunning: boolean;
115
+ /**
116
+ * May **one more** task start right now, on behalf of `consumer`? A cheap pre-check the pool consults before
117
+ * querying task readiness.
118
+ *
119
+ * Must **not** enforce rate limits that only make sense for ready tasks (e.g. a per-minute task cap): the pool
120
+ * calls this before knowing whether any task is ready, so refusing here would stall an already-empty queue.
121
+ *
122
+ * Must also return `true` whenever `consumer` has nothing in flight of its own. A `false` sends that pool straight
123
+ * to its finished-check **without** consulting `isTaskReadyFunction`, so a governor that starves an idle pool can
124
+ * make its `run()` resolve while work is still pending. Tracking bookings per consumer answers that directly;
125
+ * {@link ConcurrencySystem}, which does not, instead never refuses while
126
+ * {@link IConcurrencySystem.currentConcurrency|`currentConcurrency`} is `0`.
127
+ */
128
+ hasCapacityForTask(consumer: ConcurrencyConsumer): boolean;
129
+ /**
130
+ * Books a task against the budget for `consumer`, returning `false` (without booking) when there is no room — the
131
+ * budget is spent, the consumer is over its share, or an implementation-specific rate limit was reached.
132
+ *
133
+ * Must be an *atomic* (synchronous) check-and-book: several pools may share one governor, and a check separated
134
+ * from the booking by an `await` lets two of them claim the last free slot at once.
135
+ */
136
+ tryRegisterTaskStart(consumer: ConcurrencyConsumer): boolean;
137
+ /** Returns a task's slot to `consumer`'s budget. Called once the task settles (resolve or reject). */
138
+ registerTaskEnd(consumer: ConcurrencyConsumer): void;
139
+ }
140
+ /**
141
+ * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
142
+ * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
143
+ * over time.
144
+ *
145
+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
146
+ * of letting each scale independently and oversubscribe the machine.
147
+ *
148
+ * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
149
+ * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
150
+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
151
+ * system down for every borrower.
152
+ * @category Scaling
153
+ */
154
+ export declare class ConcurrencySystem implements IConcurrencySystem {
155
+ #private;
156
+ private readonly log;
157
+ private readonly desiredConcurrencyRatio;
158
+ private readonly scaleUpStepRatio;
159
+ private readonly scaleDownStepRatio;
160
+ private readonly maxTasksPerMinute;
161
+ private _currentConcurrency;
162
+ private readonly snapshotter;
163
+ private readonly systemStatus;
164
+ constructor(options?: ConcurrencySystemOptions);
165
+ /**
166
+ * Gets the minimum number of tasks running in parallel.
167
+ */
168
+ get minConcurrency(): number;
169
+ /**
170
+ * Sets the minimum number of tasks running in parallel.
171
+ *
172
+ * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
173
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
174
+ */
175
+ set minConcurrency(value: number);
176
+ /**
177
+ * Gets the maximum number of tasks running in parallel.
178
+ */
179
+ get maxConcurrency(): number;
180
+ /**
181
+ * Sets the maximum number of tasks running in parallel. Lowering it below the current
182
+ * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
183
+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
184
+ * limit as they settle).
185
+ */
186
+ set maxConcurrency(value: number);
187
+ /**
188
+ * Gets the desired concurrency for the system,
189
+ * which is an estimated number of parallel tasks that the system can currently support.
190
+ */
191
+ get desiredConcurrency(): number;
192
+ /**
193
+ * Sets the desired concurrency for the system, i.e. the number of tasks that should be running
194
+ * in parallel if there's large enough supply of tasks.
195
+ */
196
+ set desiredConcurrency(value: number);
197
+ /**
198
+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
199
+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
200
+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
201
+ * that is the limit callers set in order to protect something.
202
+ */
203
+ private clampDesiredConcurrency;
204
+ get currentConcurrency(): number;
205
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
206
+ get isRunning(): boolean;
207
+ /**
208
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
209
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
210
+ * signal fails to start.
211
+ */
212
+ start(): Promise<void>;
213
+ private boot;
214
+ /**
215
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
216
+ */
217
+ stop(): Promise<void>;
218
+ private shutDown;
219
+ /**
220
+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
221
+ * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
222
+ * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
223
+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
224
+ */
225
+ private warnIfNotRunning;
226
+ /**
227
+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
228
+ * reached) or when the machine is overloaded past `minConcurrency`.
229
+ *
230
+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
231
+ * interface, letting the answer be queried directly.
232
+ */
233
+ hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean;
234
+ /** Whether the per-minute task cap has been reached. */
235
+ private get isOverMaxRequestLimit();
236
+ /**
237
+ * Atomically books a task against the shared budget: re-checks
238
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
239
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
240
+ * room. Call right before the task actually runs.
241
+ *
242
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
243
+ * extra minute.
244
+ */
245
+ tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean;
246
+ /** Returns a slot to the shared budget, whoever booked it. */
247
+ registerTaskEnd(_consumer?: ConcurrencyConsumer): void;
248
+ /**
249
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
250
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
251
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
252
+ */
253
+ getCurrentStatus(): SystemInfo;
254
+ /**
255
+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
256
+ * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
257
+ */
258
+ private autoscale;
259
+ /**
260
+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
261
+ */
262
+ private scaleUp;
263
+ /**
264
+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
265
+ */
266
+ private scaleDown;
267
+ private incrementTasksDonePerSecond;
268
+ }
@@ -0,0 +1,362 @@
1
+ import { z } from 'zod';
2
+ import { betterClearInterval, betterSetInterval } from '@apify/utilities';
3
+ import { serviceLocator } from '../service_locator.js';
4
+ import { parseArgument, schemas, validators } from '../validators.js';
5
+ import { Snapshotter } from './snapshotter.js';
6
+ import { SystemStatus } from './system_status.js';
7
+ const concurrencySchema = z.number().int().gte(1).optional();
8
+ // `schemas.anyObject` passes values through by reference, so the load signal instances inside
9
+ // `loadSignals` and class instances like loggers keep their prototype.
10
+ const concurrencySystemOptionsSchema = z.strictObject({
11
+ maxConcurrency: z.number().int().gte(1).default(200),
12
+ minConcurrency: z.number().int().gte(1).default(1),
13
+ desiredConcurrency: z.number().int().gte(1).optional(),
14
+ desiredConcurrencyRatio: z.number().gt(0).lt(1).default(0.9),
15
+ scaleUpStepRatio: z.number().gt(0).lt(1).default(0.05),
16
+ scaleDownStepRatio: z.number().gt(0).lt(1).default(0.05),
17
+ loggingIntervalSecs: schemas.anyNumber
18
+ .refine((value) => value > 0, 'Expected a number greater than 0')
19
+ .nullish()
20
+ .default(60),
21
+ autoscaleIntervalSecs: schemas.anyNumber
22
+ .refine((value) => value > 0, 'Expected a number greater than 0')
23
+ .default(10),
24
+ loadSignals: schemas.anyObject.default(() => ({})),
25
+ snapshotHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
26
+ currentHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
27
+ log: validators.logger.default(() => serviceLocator.getLogger()),
28
+ maxTasksPerMinute: z
29
+ .union([z.number().int().gte(1), z.literal(Number.POSITIVE_INFINITY)])
30
+ .default(Number.POSITIVE_INFINITY),
31
+ });
32
+ /**
33
+ * The shareable "governor" behind an {@link AutoscaledPool}: it decides whether there is free compute for one more
34
+ * task by combining live system load (via an internal {@link Snapshotter}) with a concurrency budget it autoscales
35
+ * over time.
36
+ *
37
+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead
38
+ * of letting each scale independently and oversubscribe the machine.
39
+ *
40
+ * Whoever builds the instance owns its lifecycle: call {@link ConcurrencySystem.start|`start()`} before any
41
+ * borrowing pool runs and {@link ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the
42
+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the
43
+ * system down for every borrower.
44
+ * @category Scaling
45
+ */
46
+ export class ConcurrencySystem {
47
+ log;
48
+ desiredConcurrencyRatio;
49
+ scaleUpStepRatio;
50
+ scaleDownStepRatio;
51
+ #loggingIntervalMillis;
52
+ #autoscaleIntervalMillis;
53
+ maxTasksPerMinute;
54
+ #minConcurrency;
55
+ #maxConcurrency;
56
+ #desiredConcurrency;
57
+ // kept as TS-private _-prefixed: autoscaled_pool tests write this backing field directly
58
+ _currentConcurrency = 0;
59
+ #lastLoggingTime;
60
+ #tasksPerMinute = Array.from({ length: 60 }, () => 0);
61
+ snapshotter;
62
+ #loadSignals;
63
+ systemStatus;
64
+ #autoscaleInterval;
65
+ #tasksDonePerSecondInterval;
66
+ /** Whether the snapshotter and autoscaling intervals are currently running. */
67
+ #running = false;
68
+ /** The in-flight (or completed) startup, memoized so concurrent `start()` calls await one boot. */
69
+ #startPromise;
70
+ /** Set once per session, so a pool outliving `stop()` is reported once rather than every half second. */
71
+ #warnedAboutQueryWhileStopped = false;
72
+ constructor(options = {}) {
73
+ const { maxConcurrency, minConcurrency, desiredConcurrency, desiredConcurrencyRatio, scaleUpStepRatio, scaleDownStepRatio, loggingIntervalSecs, autoscaleIntervalSecs, loadSignals, snapshotHistorySecs, currentHistorySecs, log, maxTasksPerMinute, } = parseArgument(options, concurrencySystemOptionsSchema, 'ConcurrencySystemOptions');
74
+ this.log = log.child({ prefix: 'ConcurrencySystem' });
75
+ this.desiredConcurrencyRatio = desiredConcurrencyRatio;
76
+ this.scaleUpStepRatio = scaleUpStepRatio;
77
+ this.scaleDownStepRatio = scaleDownStepRatio;
78
+ this.#loggingIntervalMillis = (loggingIntervalSecs ?? 0) * 1000;
79
+ this.#autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;
80
+ this.maxTasksPerMinute = maxTasksPerMinute;
81
+ this.#minConcurrency = minConcurrency;
82
+ this.#maxConcurrency = maxConcurrency;
83
+ this.#desiredConcurrency = desiredConcurrency ?? minConcurrency;
84
+ this.clampDesiredConcurrency();
85
+ this.autoscale = this.autoscale.bind(this);
86
+ this.incrementTasksDonePerSecond = this.incrementTasksDonePerSecond.bind(this);
87
+ // The built-in signals are collected by the snapshotter; custom ones are simply evaluated alongside them.
88
+ const { custom: customLoadSignals = [], ...builtinSignalOptions } = loadSignals;
89
+ this.snapshotter = new Snapshotter(builtinSignalOptions);
90
+ this.#loadSignals = customLoadSignals;
91
+ this.systemStatus = new SystemStatus({
92
+ snapshotter: this.snapshotter,
93
+ loadSignals: customLoadSignals,
94
+ currentHistorySecs,
95
+ // Both windows are requested from the signals explicitly, so a signal's own retention can neither widen
96
+ // nor (given the start context below) narrow what it contributes.
97
+ historySecs: snapshotHistorySecs,
98
+ });
99
+ }
100
+ /**
101
+ * Gets the minimum number of tasks running in parallel.
102
+ */
103
+ get minConcurrency() {
104
+ return this.#minConcurrency;
105
+ }
106
+ /**
107
+ * Sets the minimum number of tasks running in parallel.
108
+ *
109
+ * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
110
+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.
111
+ */
112
+ set minConcurrency(value) {
113
+ parseArgument(value, concurrencySchema);
114
+ this.#minConcurrency = value;
115
+ this.clampDesiredConcurrency();
116
+ }
117
+ /**
118
+ * Gets the maximum number of tasks running in parallel.
119
+ */
120
+ get maxConcurrency() {
121
+ return this.#maxConcurrency;
122
+ }
123
+ /**
124
+ * Sets the maximum number of tasks running in parallel. Lowering it below the current
125
+ * {@link ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so
126
+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new
127
+ * limit as they settle).
128
+ */
129
+ set maxConcurrency(value) {
130
+ parseArgument(value, concurrencySchema);
131
+ this.#maxConcurrency = value;
132
+ this.clampDesiredConcurrency();
133
+ }
134
+ /**
135
+ * Gets the desired concurrency for the system,
136
+ * which is an estimated number of parallel tasks that the system can currently support.
137
+ */
138
+ get desiredConcurrency() {
139
+ return this.#desiredConcurrency;
140
+ }
141
+ /**
142
+ * Sets the desired concurrency for the system, i.e. the number of tasks that should be running
143
+ * in parallel if there's large enough supply of tasks.
144
+ */
145
+ set desiredConcurrency(value) {
146
+ parseArgument(value, concurrencySchema);
147
+ this.#desiredConcurrency = value;
148
+ this.clampDesiredConcurrency();
149
+ }
150
+ /**
151
+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.
152
+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling
153
+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since
154
+ * that is the limit callers set in order to protect something.
155
+ */
156
+ clampDesiredConcurrency() {
157
+ const atLeastMin = Math.max(this.#desiredConcurrency, this.#minConcurrency);
158
+ this.#desiredConcurrency = Math.min(atLeastMin, this.#maxConcurrency);
159
+ }
160
+ get currentConcurrency() {
161
+ return this._currentConcurrency;
162
+ }
163
+ /** Whether the system is currently monitoring load and autoscaling the budget. */
164
+ get isRunning() {
165
+ return this.#running;
166
+ }
167
+ /**
168
+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted
169
+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a
170
+ * signal fails to start.
171
+ */
172
+ async start() {
173
+ // Unwound and dropped again on failure, so a later `start()` retries instead of resolving instantly against
174
+ // a system that is down.
175
+ this.#startPromise ??= this.boot().catch(async (error) => {
176
+ this.#startPromise = undefined;
177
+ await this.shutDown();
178
+ throw error;
179
+ });
180
+ await this.#startPromise;
181
+ }
182
+ async boot() {
183
+ // Per-session measurement state, reset so a restarted system isn't judged on the previous session. The
184
+ // per-minute window matters most: its ageing interval is cleared while we are down, so starts from before an
185
+ // arbitrarily long stop would otherwise still count against "this minute" and trip the cap immediately.
186
+ this.#tasksPerMinute = Array.from({ length: 60 }, () => 0);
187
+ this.#lastLoggingTime = undefined;
188
+ this.#warnedAboutQueryWhileStopped = false;
189
+ // Signals are told how much history to keep when they start: exactly the longest window they will be sampled
190
+ // over, so nobody has to guess a retention value that matches this system's configuration.
191
+ const startContext = { maxSampleWindowMillis: this.systemStatus.maxSampleWindowMillis };
192
+ await this.snapshotter.start(startContext);
193
+ await Promise.all(this.#loadSignals.map(async (s) => s.start(startContext)));
194
+ this.#autoscaleInterval = betterSetInterval(this.autoscale, this.#autoscaleIntervalMillis);
195
+ if (this.maxTasksPerMinute !== Infinity) {
196
+ this.#tasksDonePerSecondInterval = betterSetInterval(this.incrementTasksDonePerSecond, 1000);
197
+ }
198
+ // Last, so `isRunning` never claims a system whose signals aren't collecting yet.
199
+ this.#running = true;
200
+ }
201
+ /**
202
+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.
203
+ */
204
+ async stop() {
205
+ if (this.#startPromise === undefined) {
206
+ return;
207
+ }
208
+ // Waited out rather than interrupted, or the intervals a starting signal is about to register outlive us.
209
+ await this.#startPromise.catch(() => { });
210
+ this.#startPromise = undefined;
211
+ this.#running = false;
212
+ await this.shutDown();
213
+ }
214
+ async shutDown() {
215
+ if (this.#autoscaleInterval)
216
+ betterClearInterval(this.#autoscaleInterval);
217
+ if (this.#tasksDonePerSecondInterval)
218
+ betterClearInterval(this.#tasksDonePerSecondInterval);
219
+ await this.snapshotter.stop();
220
+ await Promise.all(this.#loadSignals.map(async (s) => s.stop()));
221
+ }
222
+ /**
223
+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing
224
+ * else catches, since {@link AutoscaledPool.run|`pool.run()`} only checks
225
+ * {@link ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and
226
+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.
227
+ */
228
+ warnIfNotRunning() {
229
+ if (this.#running || this.#warnedAboutQueryWhileStopped) {
230
+ return;
231
+ }
232
+ this.#warnedAboutQueryWhileStopped = true;
233
+ this.log.warning('Capacity is being queried on a ConcurrencySystem that is not running, so system load is no longer being ' +
234
+ 'monitored and the concurrency will no longer be adjusted. Whoever creates a ConcurrencySystem owns ' +
235
+ 'its lifecycle: call `await concurrencySystem.stop()` only once every pool and crawler borrowing it ' +
236
+ 'has finished.');
237
+ }
238
+ /**
239
+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency
240
+ * reached) or when the machine is overloaded past `minConcurrency`.
241
+ *
242
+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the
243
+ * interface, letting the answer be queried directly.
244
+ */
245
+ hasCapacityForTask(_consumer) {
246
+ this.warnIfNotRunning();
247
+ if (this._currentConcurrency >= this.#desiredConcurrency) {
248
+ this.log.perf('Task will not run. Desired concurrency achieved.');
249
+ return false;
250
+ }
251
+ const currentStatus = this.systemStatus.getCurrentStatus();
252
+ const { isSystemIdle } = currentStatus;
253
+ if (!isSystemIdle && this._currentConcurrency >= this.#minConcurrency) {
254
+ this.log.perf('Task will not be run. System is overloaded.', currentStatus);
255
+ return false;
256
+ }
257
+ return true;
258
+ }
259
+ /** Whether the per-minute task cap has been reached. */
260
+ get isOverMaxRequestLimit() {
261
+ if (this.maxTasksPerMinute === Infinity) {
262
+ return false;
263
+ }
264
+ return this.#tasksPerMinute.reduce((acc, curr) => acc + curr, 0) >= this.maxTasksPerMinute;
265
+ }
266
+ /**
267
+ * Atomically books a task against the shared budget: re-checks
268
+ * {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and
269
+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no
270
+ * room. Call right before the task actually runs.
271
+ *
272
+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole
273
+ * extra minute.
274
+ */
275
+ tryRegisterTaskStart(consumer) {
276
+ if (!this.hasCapacityForTask(consumer)) {
277
+ return false;
278
+ }
279
+ if (this.isOverMaxRequestLimit) {
280
+ this.log.perf('Task will not run. Maximum tasks per minute reached.');
281
+ return false;
282
+ }
283
+ this._currentConcurrency++;
284
+ this.#tasksPerMinute[0]++;
285
+ return true;
286
+ }
287
+ /** Returns a slot to the shared budget, whoever booked it. */
288
+ registerTaskEnd(_consumer) {
289
+ this._currentConcurrency--;
290
+ }
291
+ /**
292
+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the
293
+ * task-gating window, exactly as {@link ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.
294
+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.
295
+ */
296
+ getCurrentStatus() {
297
+ return this.systemStatus.getCurrentStatus();
298
+ }
299
+ /**
300
+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven
301
+ * by the autoscaling interval started in {@link ConcurrencySystem.start|`start()`}.
302
+ */
303
+ autoscale(intervalCallback) {
304
+ if (this.isOverMaxRequestLimit)
305
+ return intervalCallback();
306
+ const systemStatus = this.systemStatus.getHistoricalStatus();
307
+ const { isSystemIdle } = systemStatus;
308
+ const weAreNotAtMax = this.#desiredConcurrency < this.#maxConcurrency;
309
+ const minCurrentConcurrency = Math.floor(this.#desiredConcurrency * this.desiredConcurrencyRatio);
310
+ const weAreReachingDesiredConcurrency = this._currentConcurrency >= minCurrentConcurrency;
311
+ if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency)
312
+ this.scaleUp(systemStatus);
313
+ const isSystemOverloaded = !isSystemIdle;
314
+ const weAreNotAtMin = this.#desiredConcurrency > this.#minConcurrency;
315
+ if (isSystemOverloaded && weAreNotAtMin)
316
+ this.scaleDown(systemStatus);
317
+ if (this.#loggingIntervalMillis > 0) {
318
+ const now = Date.now();
319
+ if (this.#lastLoggingTime == null) {
320
+ this.#lastLoggingTime = now;
321
+ }
322
+ else if (now > this.#lastLoggingTime + this.#loggingIntervalMillis) {
323
+ this.#lastLoggingTime = now;
324
+ this.log.info('state', {
325
+ currentConcurrency: this._currentConcurrency,
326
+ desiredConcurrency: this.#desiredConcurrency,
327
+ systemStatus,
328
+ });
329
+ }
330
+ }
331
+ return intervalCallback();
332
+ }
333
+ /**
334
+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.
335
+ */
336
+ scaleUp(systemStatus) {
337
+ const step = Math.ceil(this.#desiredConcurrency * this.scaleUpStepRatio);
338
+ this.#desiredConcurrency = Math.min(this.#maxConcurrency, this.#desiredConcurrency + step);
339
+ this.log.debug('scaling up', {
340
+ oldConcurrency: this.#desiredConcurrency - step,
341
+ newConcurrency: this.#desiredConcurrency,
342
+ systemStatus,
343
+ });
344
+ }
345
+ /**
346
+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.
347
+ */
348
+ scaleDown(systemStatus) {
349
+ const step = Math.ceil(this.#desiredConcurrency * this.scaleDownStepRatio);
350
+ this.#desiredConcurrency = Math.max(this.#minConcurrency, this.#desiredConcurrency - step);
351
+ this.log.debug('scaling down', {
352
+ oldConcurrency: this.#desiredConcurrency + step,
353
+ newConcurrency: this.#desiredConcurrency,
354
+ systemStatus,
355
+ });
356
+ }
357
+ incrementTasksDonePerSecond(intervalCallback) {
358
+ this.#tasksPerMinute.unshift(0);
359
+ this.#tasksPerMinute.pop();
360
+ return intervalCallback();
361
+ }
362
+ }
@@ -0,0 +1,43 @@
1
+ import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
2
+ import type { SystemInfo } from './system_status.js';
3
+ /**
4
+ * A snapshot produced by the built-in CPU signal.
5
+ * @internal
6
+ */
7
+ export interface CpuSnapshot extends LoadSnapshot {
8
+ usedRatio: number;
9
+ ticks?: {
10
+ idle: number;
11
+ total: number;
12
+ };
13
+ }
14
+ /**
15
+ * Tuning for the built-in **CPU** load signal, as accepted both by {@link CpuLoadSignal} and by the
16
+ * {@link LoadSignalsOptions.cpu|`cpu`} shorthand on {@link LoadSignalsOptions}.
17
+ */
18
+ export interface CpuLoadSignalOptions {
19
+ /**
20
+ * Maximum ratio of overloaded snapshots in a sample before the CPU counts as overloaded.
21
+ * @default 0.4
22
+ */
23
+ overloadedRatio?: number;
24
+ }
25
+ /**
26
+ * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when the platform or local OS metrics indicate the
27
+ * CPU is overloaded.
28
+ *
29
+ * Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
30
+ *
31
+ * @category Scaling
32
+ */
33
+ export declare class CpuLoadSignal implements LoadSignal {
34
+ #private;
35
+ readonly name = "cpuInfo";
36
+ readonly overloadedRatio: number;
37
+ constructor(options?: CpuLoadSignalOptions);
38
+ start(context: LoadSignalStartContext): Promise<void>;
39
+ stop(): Promise<void>;
40
+ getSample(sampleDurationMillis?: number): LoadSnapshot[];
41
+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
42
+ handle(systemInfo: SystemInfo): void;
43
+ }