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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +362 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -129
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +68 -154
  47. package/enqueue_links/enqueue_links.js +38 -210
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +52 -26
  51. package/enqueue_links/shared.js +115 -66
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +108 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +201 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +409 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +14 -13
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +32 -147
  89. package/recoverable_state.d.ts +155 -0
  90. package/recoverable_state.js +231 -0
  91. package/request.d.ts +80 -16
  92. package/request.js +147 -68
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +73 -91
  110. package/session_pool/session_pool.js +172 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +291 -148
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +445 -169
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -115
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -82
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js +0 -430
  269. package/storages/sitemap_request_list.js.map +0 -1
  270. package/storages/storage_manager.d.ts +0 -58
  271. package/storages/storage_manager.d.ts.map +0 -1
  272. package/storages/storage_manager.js +0 -105
  273. package/storages/storage_manager.js.map +0 -1
  274. package/storages/utils.d.ts.map +0 -1
  275. package/storages/utils.js.map +0 -1
  276. package/tsconfig.build.tsbuildinfo +0 -1
  277. package/typedefs.d.ts.map +0 -1
  278. package/typedefs.js.map +0 -1
  279. package/validators.d.ts.map +0 -1
  280. package/validators.js.map +0 -1
@@ -0,0 +1,252 @@
1
+ import type { Awaitable, Dictionary } from '@crawlee/types';
2
+ import type { RecordOptions } from './key_value_store.js';
3
+ /**
4
+ * Governs whether writes of a given storage type performed inside a {@link StorageTransaction} are
5
+ * applied immediately (`writeThrough`) or recorded and replayed on commit (`deferred`).
6
+ */
7
+ export type StorageWriteMode = 'deferred' | 'writeThrough';
8
+ /**
9
+ * Per-storage-type write policy of a {@link StorageTransaction}. Datasets and key-value stores are
10
+ * always `deferred` and not configurable — deferring is the only safe mode for non-idempotent writes,
11
+ * and {@link withDirectStorageAccess} covers one-off immediate writes.
12
+ */
13
+ export interface StorageWritePolicy {
14
+ /**
15
+ * Write mode for request queue additions. Note that this is a *write policy* for the queue, not the
16
+ * queue instance itself (which is the top-level `requestQueue` crawler option).
17
+ *
18
+ * - `writeThrough` (default): requests are added immediately and are **not** rolled back with the
19
+ * transaction. This is safe (additions are deduplicated by `uniqueKey`, so a retry is idempotent)
20
+ * and keeps new requests visible to the crawler while the handler still runs.
21
+ * - `deferred`: requests are only added when the transaction commits — strict all-or-nothing
22
+ * semantics, at the cost of the crawler not seeing them until the handler finishes.
23
+ */
24
+ requestQueue: StorageWriteMode;
25
+ }
26
+ export type StorageTransactionState = 'open' | 'committing' | 'committed' | 'failed' | 'rolledBack';
27
+ /**
28
+ * A storage frontend that can record operations in a transaction journal.
29
+ * @internal
30
+ */
31
+ export interface TransactionParticipant {
32
+ /**
33
+ * Replay the given buffered journal entries (all recorded by this participant) into the real storage
34
+ * backend. Called during commit, with the transaction already in the `committing` state, so the
35
+ * replayed operations pass through.
36
+ */
37
+ commitJournalEntries(entries: JournalEntry[]): Promise<void>;
38
+ }
39
+ /**
40
+ * A single dataset write (`pushData`) recorded in a transaction journal.
41
+ */
42
+ export interface DatasetJournalEntry {
43
+ type: 'dataset';
44
+ /** @internal **/
45
+ participant: TransactionParticipant;
46
+ storageId: string;
47
+ /** The pushed items, captured by `structuredClone` at write time. */
48
+ items: Dictionary[];
49
+ recordedAt: Date;
50
+ }
51
+ /**
52
+ * A single key-value store write (`setValue`) recorded in a transaction journal.
53
+ */
54
+ export interface KeyValueStoreJournalEntry {
55
+ type: 'keyValueStore';
56
+ /** @internal **/
57
+ participant: TransactionParticipant;
58
+ storageId: string;
59
+ key: string;
60
+ /** The original, pre-serialization value captured by `structuredClone`; `null` denotes a deletion. */
61
+ value: unknown;
62
+ options?: RecordOptions;
63
+ }
64
+ /**
65
+ * A request recorded in a transaction journal.
66
+ */
67
+ export interface JournaledRequest {
68
+ url: string;
69
+ uniqueKey: string;
70
+ label?: string;
71
+ /**
72
+ * A full JSON snapshot of the request for the commit replay. Only present for buffered additions —
73
+ * deduplicated and write-through ones are journaled for introspection only.
74
+ */
75
+ snapshot?: Dictionary;
76
+ }
77
+ /**
78
+ * A batch of request queue additions recorded in a transaction journal.
79
+ */
80
+ export interface RequestQueueJournalEntry {
81
+ type: 'requestQueue';
82
+ /** @internal **/
83
+ participant: TransactionParticipant;
84
+ requests: JournaledRequest[];
85
+ forefront: boolean;
86
+ /** Write-through entries were applied immediately; they are never replayed. */
87
+ writeThrough: boolean;
88
+ }
89
+ export type JournalEntry = DatasetJournalEntry | KeyValueStoreJournalEntry | RequestQueueJournalEntry;
90
+ /**
91
+ * A read-only view of a {@link StorageTransaction}: only the journal-backed introspection accessors,
92
+ * without the lifecycle methods. The accessors are synchronous and expose the original pre-serialization
93
+ * values. They cover every write recorded while the transaction was open, under either write policy —
94
+ * with the one exception noted on {@link StorageTransactionView.enqueuedUrls|`enqueuedUrls`}. A view
95
+ * is valid until the transaction is disposed.
96
+ */
97
+ export interface StorageTransactionView {
98
+ readonly state: StorageTransactionState;
99
+ /** Items pushed to datasets during the transaction, in push order. */
100
+ readonly datasetItems: {
101
+ item: Dictionary;
102
+ datasetId: string;
103
+ }[];
104
+ /**
105
+ * URLs enqueued to request queues during the transaction, under either write policy. Recorded as
106
+ * requested, so duplicate, already-present and backend-rejected URLs are included.
107
+ *
108
+ * One gap: unless a caller of `addRequestsBatched()` waits for every chunk
109
+ * (`waitForAllRequestsToBeAdded` or `maxNewRequests`, both of which {@link enqueueLinks} sets when
110
+ * a crawl limit applies), the chunks after the first are added by a background writer that outlives
111
+ * the transaction and is not recorded here.
112
+ */
113
+ readonly enqueuedUrls: {
114
+ url: string;
115
+ label?: string;
116
+ }[];
117
+ /** Key-value store changes made during the transaction, keyed by store id, last write per key. */
118
+ readonly keyValueStoreChanges: Record<string, Record<string, {
119
+ changedValue: unknown;
120
+ options?: RecordOptions;
121
+ }>>;
122
+ }
123
+ export interface StorageTransactionOptions {
124
+ /** Overrides of the per-storage-type write policy. See {@link StorageWritePolicy}. */
125
+ policy?: Partial<StorageWritePolicy>;
126
+ /**
127
+ * How long a commit may take before it fails, in milliseconds. There is no automatic retry — the
128
+ * replay of dataset items is not idempotent.
129
+ * @default 300000
130
+ */
131
+ commitTimeoutMillis?: number;
132
+ }
133
+ /**
134
+ * A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
135
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
136
+ * are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
137
+ * into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
138
+ * the recorded writes first, so a handler sees its own writes.
139
+ *
140
+ * Create one with {@link createStorageTransaction} (explicit commit/rollback) or
141
+ * {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
142
+ * handler unless `transactionalStorage: false` is set.
143
+ */
144
+ export declare class StorageTransaction implements StorageTransactionView {
145
+ #private;
146
+ /** The ordered, append-only journal — the source of truth for commit, introspection and reads. */
147
+ readonly journal: JournalEntry[];
148
+ /** Per-storage-type write policy. */
149
+ readonly policy: StorageWritePolicy;
150
+ /** @internal */
151
+ constructor(options?: StorageTransactionOptions);
152
+ get state(): StorageTransactionState;
153
+ /**
154
+ * `true` only while `state === 'open'`. This is the single predicate every storage operation
155
+ * consults — operations performed after the transaction is closed pass through to the real backend.
156
+ */
157
+ get isActive(): boolean;
158
+ /** Runs `callback` with this transaction installed in the async context. */
159
+ run<T>(callback: () => Awaitable<T>): Promise<T>;
160
+ /**
161
+ * Records a write operation in the journal.
162
+ * @internal
163
+ */
164
+ recordJournalEntry(entry: JournalEntry): void;
165
+ /**
166
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
167
+ *
168
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
169
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
170
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
171
+ * partway may have applied some of the writes already.
172
+ */
173
+ commit(): Promise<void>;
174
+ private flush;
175
+ /**
176
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
177
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
178
+ * and never throws.
179
+ */
180
+ rollback(): void;
181
+ /**
182
+ * Releases the journal and the write-time snapshots it holds. Must be called for *every* terminal
183
+ * state, `failed` included. Idempotent, never throws, and does not change `state`. Any
184
+ * {@link StorageTransactionView} of this transaction is only valid until this is called.
185
+ */
186
+ dispose(): void;
187
+ get datasetItems(): {
188
+ item: Dictionary;
189
+ datasetId: string;
190
+ }[];
191
+ get enqueuedUrls(): {
192
+ url: string;
193
+ label?: string;
194
+ }[];
195
+ get keyValueStoreChanges(): Record<string, Record<string, {
196
+ changedValue: unknown;
197
+ options?: RecordOptions;
198
+ }>>;
199
+ }
200
+ /**
201
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
202
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
203
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
204
+ */
205
+ export declare function createStorageTransaction(options?: StorageTransactionOptions): StorageTransaction;
206
+ /**
207
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
208
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
209
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
210
+ * — there are no nested transaction semantics.
211
+ */
212
+ export declare function withStorageTransaction<T>(callback: (transaction: StorageTransaction) => Awaitable<T>, options?: StorageTransactionOptions): Promise<T>;
213
+ /**
214
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
215
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
216
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
217
+ */
218
+ export declare function withDirectStorageAccess<T>(callback: () => Awaitable<T>): Promise<T>;
219
+ /**
220
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
221
+ * that aborts storage operations when the request handler times out, and returns the active storage
222
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
223
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
224
+ * @internal
225
+ */
226
+ export declare function activeStorageTransaction(): StorageTransaction | undefined;
227
+ /**
228
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
229
+ * crawler to drive the outcome of the transaction it opened.
230
+ * @internal
231
+ */
232
+ export declare function currentStorageTransaction(): StorageTransaction | undefined;
233
+ /**
234
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
235
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
236
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
237
+ * backends perform anyway.
238
+ * @internal
239
+ */
240
+ export declare function snapshotValue<T>(value: T): T;
241
+ /**
242
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
243
+ * active, and performs the per-operation cancellation check either way.
244
+ * @internal
245
+ */
246
+ export declare function rejectOperationInTransaction(operation: string, reason?: string): void;
247
+ /**
248
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
249
+ * established a transaction is active and so wants to `throw` unconditionally.
250
+ * @internal
251
+ */
252
+ export declare function operationRejectedInTransaction(operation: string, reason?: string): Error;
@@ -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,7 @@
1
- import type { Dictionary, StorageClient } from '@crawlee/types';
1
+ import type { BaseHttpClient } from '@crawlee/http-client';
2
+ import type { Dictionary, StorageBackend } from '@crawlee/types';
2
3
  import { Configuration } from '../configuration.js';
4
+ import type { IProxyConfiguration } from '../proxy_configuration.js';
3
5
  /**
4
6
  * Options for purging default storage.
5
7
  */
@@ -8,18 +10,19 @@ interface PurgeDefaultStorageOptions {
8
10
  * If set to `true`, calling multiple times will only have effect at the first time.
9
11
  */
10
12
  onlyPurgeOnce?: boolean;
11
- config?: Configuration;
12
- client?: StorageClient;
13
+ configuration?: Configuration;
14
+ storageBackend?: StorageBackend;
13
15
  }
14
16
  /**
15
17
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
16
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
18
+ * Purging empties the storages that belong to a single run the default one and every alias-keyed one —
19
+ * keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
17
20
  *
18
21
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
19
22
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
20
23
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
21
24
  *
22
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
25
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
23
26
  * it will call the `purge` method of the underlying storage implementation we are currently using. You can
24
27
  * make sure the storage is purged only once for a given execution context if you set `onlyPurgeOnce` to `true` in
25
28
  * the `options` object
@@ -27,18 +30,19 @@ interface PurgeDefaultStorageOptions {
27
30
  export declare function purgeDefaultStorages(options?: PurgeDefaultStorageOptions): Promise<void>;
28
31
  /**
29
32
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
30
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
33
+ * Purging empties the storages that belong to a single run the default one and every alias-keyed one —
34
+ * keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
31
35
  *
32
36
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
33
37
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
34
38
  * option or by setting `CRAWLEE_PURGE_ON_START` environment variable to `0` or `false`.
35
39
  *
36
- * This is a shortcut for running (optional) `purge` method on the StorageClient interface, in other words
40
+ * This is a shortcut for running (optional) `purge` method on the StorageBackend interface, in other words
37
41
  * it will call the `purge` method of the underlying storage implementation we are currently using.
38
42
  */
39
- export declare function purgeDefaultStorages(config?: Configuration, client?: StorageClient): Promise<void>;
43
+ export declare function purgeDefaultStorages(configuration?: Configuration, storageBackend?: StorageBackend): Promise<void>;
40
44
  export interface UseStateOptions {
41
- config?: Configuration;
45
+ configuration?: Configuration;
42
46
  /**
43
47
  * The name of the key-value store you'd like the state to be stored in.
44
48
  * If not provided, the default store will be used.
@@ -52,7 +56,7 @@ export interface UseStateOptions {
52
56
  *
53
57
  * @param name The name of the store to use.
54
58
  * @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.
59
+ * @param options An optional object parameter where a custom `keyValueStoreName` and `configuration` can be passed in.
56
60
  */
57
61
  export declare function useState<State extends Dictionary = Dictionary>(name?: string, defaultValue?: State, options?: UseStateOptions): Promise<State>;
58
62
  /**
@@ -89,5 +93,49 @@ export declare const API_PROCESSED_REQUESTS_DELAY_MILLIS = 10000;
89
93
  * @internal
90
94
  */
91
95
  export declare const MAX_QUERIES_FOR_CONSISTENCY = 6;
96
+ /** @internal */
97
+ export interface DualIterableOptions<TItem, TRawPage> {
98
+ /** Factory that returns an async generator yielding pages. */
99
+ createPages: () => AsyncGenerator<TRawPage>;
100
+ /** Extracts individual items from a page (for iteration). */
101
+ extractItems: (page: TRawPage) => TItem[];
102
+ }
103
+ /**
104
+ * Creates an object that is both an `AsyncIterable<TItem>` (for `for await...of`)
105
+ * and a `Promise<TItem[]>` (for `await`) from a single async page generator.
106
+ *
107
+ * - `await result` drains all pages from a fresh generator and returns every
108
+ * item as a flat array.
109
+ * - `for await (const item of result)` streams all items across all pages,
110
+ * yielding them one by one without buffering everything in memory.
111
+ *
112
+ * Each usage path creates its own generator instance, so `await` and
113
+ * `for await...of` never interfere with each other.
114
+ *
115
+ * @internal
116
+ */
117
+ export declare function createDualIterable<TItem, TRawPage>(options: DualIterableOptions<TItem, TRawPage>): AsyncIterable<TItem> & Promise<TItem[]>;
118
+ /**
119
+ * Options for the static `open()` method on storage classes ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
120
+ */
121
+ export interface StorageOpenOptions {
122
+ /**
123
+ * SDK configuration instance, defaults to the static register.
124
+ */
125
+ configuration?: Configuration;
126
+ /**
127
+ * Optional storage backend that should be used to open storages.
128
+ */
129
+ storageBackend?: StorageBackend;
130
+ /**
131
+ * Used to pass the proxy configuration for the `requestsFromUrl` objects.
132
+ * Takes advantage of the internal address rotation and authentication process.
133
+ * If undefined, the `requestsFromUrl` requests will be made without proxy.
134
+ */
135
+ proxyConfiguration?: IProxyConfiguration;
136
+ /**
137
+ * HTTP client to be used to download the list of URLs in `RequestQueue`.
138
+ */
139
+ httpClient?: BaseHttpClient;
140
+ }
92
141
  export {};
93
- //# sourceMappingURL=utils.d.ts.map