@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,251 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { addTimeoutToPromise, storage as timeoutStorage, tryCancel } from '@apify/timeout';
3
+ import { serviceLocator } from '../service_locator.js';
4
+ const DEFAULT_STORAGE_WRITE_POLICY = { requestQueue: 'writeThrough' };
5
+ const DEFAULT_COMMIT_TIMEOUT_MILLIS = 300_000;
6
+ const transactionStorage = new AsyncLocalStorage();
7
+ const COMMIT_ORDER = ['keyValueStore', 'requestQueue', 'dataset'];
8
+ /**
9
+ * A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
10
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
11
+ * are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
12
+ * into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
13
+ * the recorded writes first, so a handler sees its own writes.
14
+ *
15
+ * Create one with {@link createStorageTransaction} (explicit commit/rollback) or
16
+ * {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
17
+ * handler unless `transactionalStorage: false` is set.
18
+ */
19
+ export class StorageTransaction {
20
+ /** The ordered, append-only journal — the source of truth for commit, introspection and reads. */
21
+ journal = [];
22
+ /** Per-storage-type write policy. */
23
+ policy;
24
+ #commitTimeoutMillis;
25
+ #state = 'open';
26
+ #disposed = false;
27
+ /** @internal */
28
+ constructor(options = {}) {
29
+ this.policy = { ...DEFAULT_STORAGE_WRITE_POLICY, ...options.policy };
30
+ this.#commitTimeoutMillis = options.commitTimeoutMillis ?? DEFAULT_COMMIT_TIMEOUT_MILLIS;
31
+ }
32
+ get state() {
33
+ return this.#state;
34
+ }
35
+ /**
36
+ * `true` only while `state === 'open'`. This is the single predicate every storage operation
37
+ * consults — operations performed after the transaction is closed pass through to the real backend.
38
+ */
39
+ get isActive() {
40
+ return this.#state === 'open';
41
+ }
42
+ /** Runs `callback` with this transaction installed in the async context. */
43
+ async run(callback) {
44
+ return transactionStorage.run(this, async () => callback());
45
+ }
46
+ /**
47
+ * Records a write operation in the journal.
48
+ * @internal
49
+ */
50
+ recordJournalEntry(entry) {
51
+ if (!this.isActive) {
52
+ throw new Error(`Cannot record a journal entry on a transaction in the '${this.#state}' state`);
53
+ }
54
+ this.journal.push(entry);
55
+ }
56
+ /**
57
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
58
+ *
59
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
60
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
61
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
62
+ * partway may have applied some of the writes already.
63
+ */
64
+ async commit() {
65
+ if (this.#state !== 'open') {
66
+ return;
67
+ }
68
+ this.#state = 'committing';
69
+ try {
70
+ // The replay re-drives the frontend write path, which checks for cancellation (`tryCancel`)
71
+ // on every operation - and `@apify/timeout` shares one `AbortController` across nested
72
+ // frames, so a request-handler timeout that already fired would abort the commit of a
73
+ // handler that succeeded. Hence a fresh timeout context, which also provides the time bound.
74
+ await timeoutStorage.exit(async () => addTimeoutToPromise(async () => this.flush(), this.#commitTimeoutMillis, `Committing the storage transaction timed out after ${this.#commitTimeoutMillis / 1000} seconds.`));
75
+ this.#state = 'committed';
76
+ }
77
+ catch (error) {
78
+ this.#state = 'failed';
79
+ throw error;
80
+ }
81
+ }
82
+ async flush() {
83
+ // Each participating frontend replays all of its buffered entries in one call. Frontends are
84
+ // ordered by storage type: key-value stores and request queues first (idempotent under retry),
85
+ // datasets last (not idempotent), minimizing the blast radius of a partial commit failure.
86
+ const groups = new Map();
87
+ for (const entry of this.journal) {
88
+ if (entry.type === 'requestQueue' && entry.writeThrough)
89
+ continue;
90
+ const group = groups.get(entry.participant);
91
+ if (group)
92
+ group.push(entry);
93
+ else
94
+ groups.set(entry.participant, [entry]);
95
+ }
96
+ // A participant only records entries of its own storage type, so the first entry determines
97
+ // the group's place in the commit order.
98
+ const orderedGroups = [...groups.values()].sort((a, b) => COMMIT_ORDER.indexOf(a[0].type) - COMMIT_ORDER.indexOf(b[0].type));
99
+ for (const entries of orderedGroups) {
100
+ await entries[0].participant.commitJournalEntries(entries);
101
+ }
102
+ }
103
+ /**
104
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
105
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
106
+ * and never throws.
107
+ */
108
+ rollback() {
109
+ if (this.#state !== 'open') {
110
+ return;
111
+ }
112
+ this.#state = 'rolledBack';
113
+ }
114
+ /**
115
+ * Releases the journal and the write-time snapshots it holds. Must be called for *every* terminal
116
+ * state, `failed` included. Idempotent, never throws, and does not change `state`. Any
117
+ * {@link StorageTransactionView} of this transaction is only valid until this is called.
118
+ */
119
+ dispose() {
120
+ if (this.#disposed) {
121
+ return;
122
+ }
123
+ if (this.#state === 'open') {
124
+ // Disposing an open transaction is an internal invariant violation - roll back first.
125
+ try {
126
+ serviceLocator
127
+ .getLogger()
128
+ .warning('Internal error: a storage transaction was disposed while still open; rolling it back.');
129
+ }
130
+ catch {
131
+ // Never throw from dispose.
132
+ }
133
+ this.rollback();
134
+ }
135
+ this.#disposed = true;
136
+ this.journal.length = 0;
137
+ }
138
+ get datasetItems() {
139
+ return this.journal.flatMap((entry) => entry.type === 'dataset' ? entry.items.map((item) => ({ item, datasetId: entry.storageId })) : []);
140
+ }
141
+ get enqueuedUrls() {
142
+ return this.journal.flatMap((entry) => entry.type === 'requestQueue' ? entry.requests.map(({ url, label }) => ({ url, label })) : []);
143
+ }
144
+ get keyValueStoreChanges() {
145
+ const result = {};
146
+ for (const entry of this.journal) {
147
+ if (entry.type !== 'keyValueStore')
148
+ continue;
149
+ result[entry.storageId] ??= {};
150
+ result[entry.storageId][entry.key] = { changedValue: entry.value, options: entry.options };
151
+ }
152
+ return result;
153
+ }
154
+ }
155
+ /**
156
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
157
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
158
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
159
+ */
160
+ export function createStorageTransaction(options = {}) {
161
+ return new StorageTransaction(options);
162
+ }
163
+ /**
164
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
165
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
166
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
167
+ * — there are no nested transaction semantics.
168
+ */
169
+ export async function withStorageTransaction(callback, options = {}) {
170
+ const existing = transactionStorage.getStore();
171
+ if (existing?.isActive) {
172
+ return callback(existing);
173
+ }
174
+ const transaction = createStorageTransaction(options);
175
+ try {
176
+ const result = await transaction.run(async () => callback(transaction));
177
+ await transaction.commit();
178
+ return result;
179
+ }
180
+ catch (error) {
181
+ transaction.rollback();
182
+ throw error;
183
+ }
184
+ finally {
185
+ transaction.dispose();
186
+ }
187
+ }
188
+ /**
189
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
190
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
191
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
192
+ */
193
+ export async function withDirectStorageAccess(callback) {
194
+ return transactionStorage.exit(async () => callback());
195
+ }
196
+ /**
197
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
198
+ * that aborts storage operations when the request handler times out, and returns the active storage
199
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
200
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
201
+ * @internal
202
+ */
203
+ export function activeStorageTransaction() {
204
+ tryCancel();
205
+ const transaction = transactionStorage.getStore();
206
+ return transaction?.isActive ? transaction : undefined;
207
+ }
208
+ /**
209
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
210
+ * crawler to drive the outcome of the transaction it opened.
211
+ * @internal
212
+ */
213
+ export function currentStorageTransaction() {
214
+ return transactionStorage.getStore();
215
+ }
216
+ /**
217
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
218
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
219
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
220
+ * backends perform anyway.
221
+ * @internal
222
+ */
223
+ export function snapshotValue(value) {
224
+ try {
225
+ return structuredClone(value);
226
+ }
227
+ catch {
228
+ return JSON.parse(JSON.stringify(value));
229
+ }
230
+ }
231
+ /**
232
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
233
+ * active, and performs the per-operation cancellation check either way.
234
+ * @internal
235
+ */
236
+ export function rejectOperationInTransaction(operation, reason = 'it cannot be rolled back.') {
237
+ if (activeStorageTransaction() === undefined) {
238
+ return;
239
+ }
240
+ throw operationRejectedInTransaction(operation, reason);
241
+ }
242
+ /**
243
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
244
+ * established a transaction is active and so wants to `throw` unconditionally.
245
+ * @internal
246
+ */
247
+ export function operationRejectedInTransaction(operation, reason = 'it cannot be rolled back.') {
248
+ return new Error(`${operation} cannot be used inside a storage transaction: ${reason} ` +
249
+ 'If you really need it, wrap the call in withDirectStorageAccess(() => ...) - operations ' +
250
+ 'performed there are applied immediately and are not rolled back.');
251
+ }
@@ -1,5 +1,6 @@
1
- import type { Dictionary, StorageClient } from '@crawlee/types';
1
+ import type { BaseHttpClient, Dictionary, StorageBackend } from '@crawlee/types';
2
2
  import { Configuration } from '../configuration.js';
3
+ import type { IProxyConfiguration } from '../proxy_configuration.js';
3
4
  /**
4
5
  * Options for purging default storage.
5
6
  */
@@ -8,8 +9,8 @@ interface PurgeDefaultStorageOptions {
8
9
  * If set to `true`, calling multiple times will only have effect at the first time.
9
10
  */
10
11
  onlyPurgeOnce?: boolean;
11
- config?: Configuration;
12
- client?: StorageClient;
12
+ configuration?: Configuration;
13
+ storageBackend?: StorageBackend;
13
14
  }
14
15
  /**
15
16
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
@@ -19,7 +20,7 @@ interface PurgeDefaultStorageOptions {
19
20
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
20
21
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
21
22
  *
22
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
23
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
23
24
  * it will call the `purge` method of the underlying storage implementation we are currently using. You can
24
25
  * make sure the storage is purged only once for a given execution context if you set `onlyPurgeOnce` to `true` in
25
26
  * the `options` object
@@ -33,12 +34,12 @@ export declare function purgeDefaultStorages(options?: PurgeDefaultStorageOption
33
34
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
34
35
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
35
36
  *
36
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
37
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
37
38
  * it will call the `purge` method of the underlying storage implementation we are currently using.
38
39
  */
39
- export declare function purgeDefaultStorages(config?: Configuration, client?: StorageClient): Promise<void>;
40
+ export declare function purgeDefaultStorages(configuration?: Configuration, storageBackend?: StorageBackend): Promise<void>;
40
41
  export interface UseStateOptions {
41
- config?: Configuration;
42
+ configuration?: Configuration;
42
43
  /**
43
44
  * The name of the key-value store you'd like the state to be stored in.
44
45
  * If not provided, the default store will be used.
@@ -52,7 +53,7 @@ export interface UseStateOptions {
52
53
  *
53
54
  * @param name The name of the store to use.
54
55
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
55
- * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
56
+ * @param options An optional object parameter where a custom `keyValueStoreName` and `configuration` can be passed in.
56
57
  */
57
58
  export declare function useState<State extends Dictionary = Dictionary>(name?: string, defaultValue?: State, options?: UseStateOptions): Promise<State>;
58
59
  /**
@@ -89,5 +90,49 @@ export declare const API_PROCESSED_REQUESTS_DELAY_MILLIS = 10000;
89
90
  * @internal
90
91
  */
91
92
  export declare const MAX_QUERIES_FOR_CONSISTENCY = 6;
93
+ /** @internal */
94
+ export interface DualIterableOptions<TItem, TRawPage> {
95
+ /** Factory that returns an async generator yielding pages. */
96
+ createPages: () => AsyncGenerator<TRawPage>;
97
+ /** Extracts individual items from a page (for iteration). */
98
+ extractItems: (page: TRawPage) => TItem[];
99
+ }
100
+ /**
101
+ * Creates an object that is both an `AsyncIterable<TItem>` (for `for await...of`)
102
+ * and a `Promise<TItem[]>` (for `await`) from a single async page generator.
103
+ *
104
+ * - `await result` drains all pages from a fresh generator and returns every
105
+ * item as a flat array.
106
+ * - `for await (const item of result)` streams all items across all pages,
107
+ * yielding them one by one without buffering everything in memory.
108
+ *
109
+ * Each usage path creates its own generator instance, so `await` and
110
+ * `for await...of` never interfere with each other.
111
+ *
112
+ * @internal
113
+ */
114
+ export declare function createDualIterable<TItem, TRawPage>(options: DualIterableOptions<TItem, TRawPage>): AsyncIterable<TItem> & Promise<TItem[]>;
115
+ /**
116
+ * Options for the static `open()` method on storage classes ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
117
+ */
118
+ export interface StorageOpenOptions {
119
+ /**
120
+ * SDK configuration instance, defaults to the static register.
121
+ */
122
+ configuration?: Configuration;
123
+ /**
124
+ * Optional storage backend that should be used to open storages.
125
+ */
126
+ storageBackend?: StorageBackend;
127
+ /**
128
+ * Used to pass the proxy configuration for the `requestsFromUrl` objects.
129
+ * Takes advantage of the internal address rotation and authentication process.
130
+ * If undefined, the `requestsFromUrl` requests will be made without proxy.
131
+ */
132
+ proxyConfiguration?: IProxyConfiguration;
133
+ /**
134
+ * HTTP client to be used to download the list of URLs in `RequestQueue`.
135
+ */
136
+ httpClient?: BaseHttpClient;
137
+ }
92
138
  export {};
93
- //# sourceMappingURL=utils.d.ts.map
package/storages/utils.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { Configuration } from '../configuration.js';
3
+ import { serviceLocator } from '../service_locator.js';
3
4
  import { KeyValueStore } from './key_value_store.js';
4
- export async function purgeDefaultStorages(configOrOptions, client) {
5
- const options = configOrOptions instanceof Configuration
5
+ export async function purgeDefaultStorages(configurationOrOptions, storageBackend) {
6
+ const options = configurationOrOptions instanceof Configuration
6
7
  ? {
7
- client,
8
- config: configOrOptions,
8
+ storageBackend,
9
+ configuration: configurationOrOptions,
9
10
  }
10
- : (configOrOptions ?? {});
11
- const { config = Configuration.getGlobalConfig(), onlyPurgeOnce = false } = options;
12
- ({ client = config.getStorageClient() } = options);
13
- const casted = client;
11
+ : (configurationOrOptions ?? {});
12
+ const { configuration = serviceLocator.getConfiguration(), onlyPurgeOnce = false } = options;
13
+ ({ storageBackend = serviceLocator.getStorageBackend() } = options);
14
+ const casted = storageBackend;
14
15
  // if `onlyPurgeOnce` is true, will purge anytime this function is called, otherwise - only on start
15
- if (!onlyPurgeOnce || (config.get('purgeOnStart') && !casted.__purged)) {
16
+ if (!onlyPurgeOnce || (configuration.purgeOnStart && !casted.__purged)) {
16
17
  casted.__purged = true;
17
18
  await casted.purge?.();
18
19
  }
@@ -24,11 +25,11 @@ export async function purgeDefaultStorages(configOrOptions, client) {
24
25
  *
25
26
  * @param name The name of the store to use.
26
27
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
27
- * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
28
+ * @param options An optional object parameter where a custom `keyValueStoreName` and `configuration` can be passed in.
28
29
  */
29
30
  export async function useState(name, defaultValue = {}, options) {
30
- const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
31
- config: options?.config || Configuration.getGlobalConfig(),
31
+ const kvStore = await KeyValueStore.open(options?.keyValueStoreName ? { name: options.keyValueStoreName } : null, {
32
+ configuration: options?.configuration || serviceLocator.getConfiguration(),
32
33
  });
33
34
  return kvStore.getAutoSavedValue(name || 'CRAWLEE_GLOBAL_STATE', defaultValue);
34
35
  }
@@ -69,4 +70,54 @@ export const API_PROCESSED_REQUESTS_DELAY_MILLIS = 10_000;
69
70
  * @internal
70
71
  */
71
72
  export const MAX_QUERIES_FOR_CONSISTENCY = 6;
72
- //# sourceMappingURL=utils.js.map
73
+ /**
74
+ * Creates an object that is both an `AsyncIterable<TItem>` (for `for await...of`)
75
+ * and a `Promise<TItem[]>` (for `await`) from a single async page generator.
76
+ *
77
+ * - `await result` drains all pages from a fresh generator and returns every
78
+ * item as a flat array.
79
+ * - `for await (const item of result)` streams all items across all pages,
80
+ * yielding them one by one without buffering everything in memory.
81
+ *
82
+ * Each usage path creates its own generator instance, so `await` and
83
+ * `for await...of` never interfere with each other.
84
+ *
85
+ * @internal
86
+ */
87
+ export function createDualIterable(options) {
88
+ const { createPages, extractItems } = options;
89
+ let cached = null;
90
+ function getOrCreate() {
91
+ if (!cached) {
92
+ cached = (async () => {
93
+ const items = [];
94
+ for await (const page of createPages()) {
95
+ items.push(...extractItems(page));
96
+ }
97
+ return items;
98
+ })();
99
+ }
100
+ return cached;
101
+ }
102
+ async function* iterateAll() {
103
+ for await (const page of createPages()) {
104
+ yield* extractItems(page);
105
+ }
106
+ }
107
+ const result = {
108
+ [Symbol.asyncIterator]() {
109
+ return iterateAll();
110
+ },
111
+ then(onfulfilled, onrejected) {
112
+ return getOrCreate().then(onfulfilled, onrejected);
113
+ },
114
+ catch(onrejected) {
115
+ return getOrCreate().catch(onrejected);
116
+ },
117
+ finally(onfinally) {
118
+ return getOrCreate().finally(onfinally);
119
+ },
120
+ [Symbol.toStringTag]: 'DualIterable',
121
+ };
122
+ return result;
123
+ }
@@ -0,0 +1,67 @@
1
+ import type { CrawleeLogger } from '@crawlee/types';
2
+ /**
3
+ * Gets the "bare metal" cpu load.
4
+ * Used in
5
+ * - AWS Lambda
6
+ * - Containers without a cGroup quota
7
+ * - Uncontainerized environments
8
+ * @returns a number between 0 and 1 for the cpu load
9
+ * @internal
10
+ */
11
+ export declare function getCurrentCpuTicks(): number;
12
+ /**
13
+ * Reads the cgroup cpu quota.
14
+ * In V1, a quota of -1 means “unlimited.”
15
+ * In V2, a first field of "max" means unlimited.
16
+ * @param cgroupsVersion the cGroup version
17
+ * @returns The Cpu Quota
18
+ * @internal
19
+ */
20
+ export declare function getCpuQuota(cgroupsVersion: string): Promise<number | null>;
21
+ /**
22
+ * Reads the cgroup cpu period.
23
+ * @param cgroupsVersion the cGroup version
24
+ * @returns The Cpu quota period
25
+ * @internal
26
+ */
27
+ export declare function getCpuPeriod(cgroupsVersion: string): Promise<number>;
28
+ /**
29
+ * Reads the cgroup cpu usage of the container
30
+ *
31
+ * @param cgroupsVersion the cGroup version
32
+ * @returns the cpu usage
33
+ * @internal
34
+ */
35
+ export declare function getContainerCpuUsage(cgroupsVersion: string): Promise<number>;
36
+ /**
37
+ * Reads the cgroup cpu usage of the system from cgroup
38
+ *
39
+ * @returns the cpu usage
40
+ * @internal
41
+ */
42
+ export declare function getSystemCpuUsage(): Promise<number>;
43
+ /**
44
+ * a cpu sample with the container usage and system usage
45
+ */
46
+ export interface CpuSample {
47
+ containerUsage: number;
48
+ systemUsage: number;
49
+ }
50
+ /**
51
+ * Takes a CPU usage sample for both the container and the system.
52
+ *
53
+ * @returns An object containing the container and system CPU usage.
54
+ * @internal
55
+ */
56
+ export declare function sampleCpuUsage(cGroupsVersion: string): Promise<CpuSample>;
57
+ /**
58
+ * Gets the cpu usage of the system.
59
+ * If the crawler is running in a containerized environment, crawlee will check for a cgroup enforced cpu limit.
60
+ * If a cgroup limit is found, it will be taken as the maximum load against which the current load will be gauged.
61
+ * @returns a number between 0 and 1 for the cpu load
62
+ * @internal
63
+ */
64
+ export declare function getCurrentCpuTicksV2(options?: {
65
+ containerized?: boolean;
66
+ logger?: CrawleeLogger;
67
+ }): Promise<number>;