@crawlee/core 4.0.0-beta.17 → 4.0.0-beta.170

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 (287) hide show
  1. package/README.md +14 -14
  2. package/autoscaling/autoscaled_pool.d.ts +73 -177
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +364 -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 +98 -0
  13. package/autoscaling/load_signal.js +103 -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 +70 -92
  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 +128 -124
  33. package/crawlers/crawler_commons.js +1 -108
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +5 -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 +194 -79
  43. package/crawlers/statistics.js +382 -201
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +61 -154
  47. package/enqueue_links/enqueue_links.js +40 -232
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +55 -28
  51. package/enqueue_links/shared.js +116 -69
  52. package/errors.d.ts +82 -4
  53. package/errors.js +101 -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 -5
  63. package/index.js +8 -4
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +77 -1
  67. package/log.js +134 -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 +44 -0
  73. package/memory-storage/memory-storage.js +160 -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 +106 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +199 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +414 -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 +17 -16
  87. package/proxy_configuration.d.ts +22 -128
  88. package/proxy_configuration.js +32 -144
  89. package/recoverable_state.d.ts +84 -51
  90. package/recoverable_state.js +175 -72
  91. package/request.d.ts +57 -16
  92. package/request.js +130 -69
  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 +40 -90
  108. package/session_pool/session.js +103 -160
  109. package/session_pool/session_pool.d.ts +85 -101
  110. package/session_pool/session_pool.js +254 -210
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -56
  114. package/storages/dataset.js +292 -149
  115. package/storages/index.d.ts +9 -9
  116. package/storages/index.js +7 -9
  117. package/storages/key_value_store.d.ts +186 -48
  118. package/storages/key_value_store.js +452 -170
  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 +54 -129
  124. package/storages/request_list.js +272 -245
  125. package/storages/request_loader.d.ts +133 -0
  126. package/storages/request_loader.js +36 -0
  127. package/storages/request_manager.d.ts +109 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +55 -23
  130. package/storages/request_manager_tandem.js +139 -57
  131. package/storages/request_queue.d.ts +286 -48
  132. package/storages/request_queue.js +757 -218
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +43 -91
  134. package/storages/sitemap_request_loader.js +439 -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 +223 -0
  140. package/storages/throttling_request_manager.js +835 -0
  141. package/storages/transaction.d.ts +260 -0
  142. package/storages/transaction.js +287 -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 +23 -18
  158. package/validators.js +14 -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 -85
  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/recoverable_state.d.ts.map +0 -1
  226. package/recoverable_state.js.map +0 -1
  227. package/request.d.ts.map +0 -1
  228. package/request.js.map +0 -1
  229. package/router.d.ts.map +0 -1
  230. package/router.js.map +0 -1
  231. package/serialization.d.ts.map +0 -1
  232. package/serialization.js.map +0 -1
  233. package/session_pool/consts.d.ts.map +0 -1
  234. package/session_pool/consts.js.map +0 -1
  235. package/session_pool/errors.d.ts.map +0 -1
  236. package/session_pool/errors.js.map +0 -1
  237. package/session_pool/events.d.ts +0 -3
  238. package/session_pool/events.d.ts.map +0 -1
  239. package/session_pool/events.js +0 -3
  240. package/session_pool/events.js.map +0 -1
  241. package/session_pool/index.d.ts.map +0 -1
  242. package/session_pool/index.js.map +0 -1
  243. package/session_pool/session.d.ts.map +0 -1
  244. package/session_pool/session.js.map +0 -1
  245. package/session_pool/session_pool.d.ts.map +0 -1
  246. package/session_pool/session_pool.js.map +0 -1
  247. package/storages/access_checking.d.ts +0 -13
  248. package/storages/access_checking.d.ts.map +0 -1
  249. package/storages/access_checking.js +0 -14
  250. package/storages/access_checking.js.map +0 -1
  251. package/storages/dataset.d.ts.map +0 -1
  252. package/storages/dataset.js.map +0 -1
  253. package/storages/index.d.ts.map +0 -1
  254. package/storages/index.js.map +0 -1
  255. package/storages/key_value_store.d.ts.map +0 -1
  256. package/storages/key_value_store.js.map +0 -1
  257. package/storages/request_list.d.ts.map +0 -1
  258. package/storages/request_list.js.map +0 -1
  259. package/storages/request_list_adapter.d.ts +0 -58
  260. package/storages/request_list_adapter.d.ts.map +0 -1
  261. package/storages/request_list_adapter.js +0 -81
  262. package/storages/request_list_adapter.js.map +0 -1
  263. package/storages/request_manager_tandem.d.ts.map +0 -1
  264. package/storages/request_manager_tandem.js.map +0 -1
  265. package/storages/request_provider.d.ts +0 -371
  266. package/storages/request_provider.d.ts.map +0 -1
  267. package/storages/request_provider.js +0 -585
  268. package/storages/request_provider.js.map +0 -1
  269. package/storages/request_queue.d.ts.map +0 -1
  270. package/storages/request_queue.js.map +0 -1
  271. package/storages/request_queue_v2.d.ts +0 -87
  272. package/storages/request_queue_v2.d.ts.map +0 -1
  273. package/storages/request_queue_v2.js +0 -438
  274. package/storages/request_queue_v2.js.map +0 -1
  275. package/storages/sitemap_request_list.d.ts.map +0 -1
  276. package/storages/sitemap_request_list.js +0 -430
  277. package/storages/sitemap_request_list.js.map +0 -1
  278. package/storages/storage_manager.d.ts +0 -58
  279. package/storages/storage_manager.d.ts.map +0 -1
  280. package/storages/storage_manager.js +0 -105
  281. package/storages/storage_manager.js.map +0 -1
  282. package/storages/utils.d.ts.map +0 -1
  283. package/storages/utils.js.map +0 -1
  284. package/typedefs.d.ts.map +0 -1
  285. package/typedefs.js.map +0 -1
  286. package/validators.d.ts.map +0 -1
  287. package/validators.js.map +0 -1
@@ -0,0 +1,260 @@
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
+ * Registers a callback to run once a commit has been attempted, whether it succeeded (`error` is
167
+ * `undefined`) or failed - the only point at which a deferred write can be reacted to where it was
168
+ * made. Callbacks run in registration order; the first to throw propagates, the rest do not run, and
169
+ * on a failed commit its error replaces the commit error. Not run on rollback: nothing was written.
170
+ */
171
+ afterCommit(callback: (error?: Error) => Awaitable<void>): void;
172
+ /**
173
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
174
+ *
175
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
176
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
177
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
178
+ * partway may have applied some of the writes already.
179
+ */
180
+ commit(): Promise<void>;
181
+ private flush;
182
+ /**
183
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
184
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
185
+ * and never throws.
186
+ */
187
+ rollback(): void;
188
+ /**
189
+ * Releases the journal, the write-time snapshots it holds and any registered commit callbacks. Must
190
+ * be called for *every* terminal state, `failed` included. Idempotent, never throws, and does not
191
+ * change `state`. Any {@link StorageTransactionView} of this transaction is only valid until this
192
+ * is called.
193
+ */
194
+ dispose(): void;
195
+ get datasetItems(): {
196
+ item: Dictionary;
197
+ datasetId: string;
198
+ }[];
199
+ get enqueuedUrls(): {
200
+ url: string;
201
+ label?: string;
202
+ }[];
203
+ get keyValueStoreChanges(): Record<string, Record<string, {
204
+ changedValue: unknown;
205
+ options?: RecordOptions;
206
+ }>>;
207
+ }
208
+ /**
209
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
210
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
211
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
212
+ */
213
+ export declare function createStorageTransaction(options?: StorageTransactionOptions): StorageTransaction;
214
+ /**
215
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
216
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
217
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
218
+ * — there are no nested transaction semantics.
219
+ */
220
+ export declare function withStorageTransaction<T>(callback: (transaction: StorageTransaction) => Awaitable<T>, options?: StorageTransactionOptions): Promise<T>;
221
+ /**
222
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
223
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
224
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
225
+ */
226
+ export declare function withDirectStorageAccess<T>(callback: () => Awaitable<T>): Promise<T>;
227
+ /**
228
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
229
+ * that aborts storage operations when the request handler times out, and returns the active storage
230
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
231
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
232
+ * @internal
233
+ */
234
+ export declare function activeStorageTransaction(): StorageTransaction | undefined;
235
+ /**
236
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
237
+ * crawler to drive the outcome of the transaction it opened.
238
+ * @internal
239
+ */
240
+ export declare function currentStorageTransaction(): StorageTransaction | undefined;
241
+ /**
242
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
243
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
244
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
245
+ * backends perform anyway.
246
+ * @internal
247
+ */
248
+ export declare function snapshotValue<T>(value: T): T;
249
+ /**
250
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
251
+ * active, and performs the per-operation cancellation check either way.
252
+ * @internal
253
+ */
254
+ export declare function rejectOperationInTransaction(operation: string, reason?: string): void;
255
+ /**
256
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
257
+ * established a transaction is active and so wants to `throw` unconditionally.
258
+ * @internal
259
+ */
260
+ export declare function operationRejectedInTransaction(operation: string, reason?: string): Error;
@@ -0,0 +1,287 @@
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
+ import { AfterCommitError, NonRetryableError } from '../errors.js';
5
+ const DEFAULT_STORAGE_WRITE_POLICY = { requestQueue: 'writeThrough' };
6
+ const DEFAULT_COMMIT_TIMEOUT_MILLIS = 300_000;
7
+ const transactionStorage = new AsyncLocalStorage();
8
+ const COMMIT_ORDER = ['keyValueStore', 'requestQueue', 'dataset'];
9
+ /**
10
+ * A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
11
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
12
+ * are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
13
+ * into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
14
+ * the recorded writes first, so a handler sees its own writes.
15
+ *
16
+ * Create one with {@link createStorageTransaction} (explicit commit/rollback) or
17
+ * {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
18
+ * handler unless `transactionalStorage: false` is set.
19
+ */
20
+ export class StorageTransaction {
21
+ /** The ordered, append-only journal — the source of truth for commit, introspection and reads. */
22
+ journal = [];
23
+ /** Per-storage-type write policy. */
24
+ policy;
25
+ #commitTimeoutMillis;
26
+ #state = 'open';
27
+ #disposed = false;
28
+ /** Callbacks registered via `afterCommit()`, run in registration order once a commit has been attempted. */
29
+ #afterCommitCallbacks = [];
30
+ /** @internal */
31
+ constructor(options = {}) {
32
+ this.policy = { ...DEFAULT_STORAGE_WRITE_POLICY, ...options.policy };
33
+ this.#commitTimeoutMillis = options.commitTimeoutMillis ?? DEFAULT_COMMIT_TIMEOUT_MILLIS;
34
+ }
35
+ get state() {
36
+ return this.#state;
37
+ }
38
+ /**
39
+ * `true` only while `state === 'open'`. This is the single predicate every storage operation
40
+ * consults — operations performed after the transaction is closed pass through to the real backend.
41
+ */
42
+ get isActive() {
43
+ return this.#state === 'open';
44
+ }
45
+ /** Runs `callback` with this transaction installed in the async context. */
46
+ async run(callback) {
47
+ return transactionStorage.run(this, async () => callback());
48
+ }
49
+ /**
50
+ * Records a write operation in the journal.
51
+ * @internal
52
+ */
53
+ recordJournalEntry(entry) {
54
+ if (!this.isActive) {
55
+ throw new Error(`Cannot record a journal entry on a transaction in the '${this.#state}' state`);
56
+ }
57
+ this.journal.push(entry);
58
+ }
59
+ /**
60
+ * Registers a callback to run once a commit has been attempted, whether it succeeded (`error` is
61
+ * `undefined`) or failed - the only point at which a deferred write can be reacted to where it was
62
+ * made. Callbacks run in registration order; the first to throw propagates, the rest do not run, and
63
+ * on a failed commit its error replaces the commit error. Not run on rollback: nothing was written.
64
+ */
65
+ afterCommit(callback) {
66
+ if (!this.isActive) {
67
+ throw new Error(`Cannot register a commit callback on a transaction in the '${this.#state}' state`);
68
+ }
69
+ this.#afterCommitCallbacks.push(callback);
70
+ }
71
+ /**
72
+ * Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
73
+ *
74
+ * The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
75
+ * partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
76
+ * rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
77
+ * partway may have applied some of the writes already.
78
+ */
79
+ async commit() {
80
+ if (this.#state !== 'open') {
81
+ return;
82
+ }
83
+ this.#state = 'committing';
84
+ try {
85
+ // The replay re-drives the frontend write path, which checks for cancellation (`tryCancel`)
86
+ // on every operation - and `@apify/timeout` shares one `AbortController` across nested
87
+ // frames, so a request-handler timeout that already fired would abort the commit of a
88
+ // handler that succeeded. Hence a fresh timeout context, which also provides the time bound.
89
+ await timeoutStorage.exit(async () => addTimeoutToPromise(async () => this.flush(), this.#commitTimeoutMillis, `Committing the storage transaction timed out after ${this.#commitTimeoutMillis / 1000} seconds.`));
90
+ }
91
+ catch (error) {
92
+ this.#state = 'failed';
93
+ // Callbacks are handed an `Error`, so a backend that rejects with anything else gets wrapped.
94
+ const commitError = error instanceof Error ? error : new Error(String(error), { cause: error });
95
+ // A callback that throws here propagates instead: it was handed the failure and decided what
96
+ // the request should fail with.
97
+ await this.#runAfterCommitCallbacks(commitError);
98
+ throw commitError;
99
+ }
100
+ this.#state = 'committed';
101
+ try {
102
+ await this.#runAfterCommitCallbacks();
103
+ }
104
+ catch (error) {
105
+ throw error instanceof NonRetryableError ? error : new AfterCommitError(error);
106
+ }
107
+ }
108
+ /** Fresh timeout context for the same reason as the flush. */
109
+ async #runAfterCommitCallbacks(error) {
110
+ await timeoutStorage.exit(async () => {
111
+ for (const callback of this.#afterCommitCallbacks) {
112
+ await callback(error);
113
+ }
114
+ });
115
+ }
116
+ async flush() {
117
+ // Each participating frontend replays all of its buffered entries in one call. Frontends are
118
+ // ordered by storage type: key-value stores and request queues first (idempotent under retry),
119
+ // datasets last (not idempotent), minimizing the blast radius of a partial commit failure.
120
+ const groups = new Map();
121
+ for (const entry of this.journal) {
122
+ if (entry.type === 'requestQueue' && entry.writeThrough)
123
+ continue;
124
+ const group = groups.get(entry.participant);
125
+ if (group)
126
+ group.push(entry);
127
+ else
128
+ groups.set(entry.participant, [entry]);
129
+ }
130
+ // A participant only records entries of its own storage type, so the first entry determines
131
+ // the group's place in the commit order.
132
+ const orderedGroups = [...groups.values()].sort((a, b) => COMMIT_ORDER.indexOf(a[0].type) - COMMIT_ORDER.indexOf(b[0].type));
133
+ for (const entries of orderedGroups) {
134
+ await entries[0].participant.commitJournalEntries(entries);
135
+ }
136
+ }
137
+ /**
138
+ * Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
139
+ * after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
140
+ * and never throws.
141
+ */
142
+ rollback() {
143
+ if (this.#state !== 'open') {
144
+ return;
145
+ }
146
+ this.#state = 'rolledBack';
147
+ }
148
+ /**
149
+ * Releases the journal, the write-time snapshots it holds and any registered commit callbacks. Must
150
+ * be called for *every* terminal state, `failed` included. Idempotent, never throws, and does not
151
+ * change `state`. Any {@link StorageTransactionView} of this transaction is only valid until this
152
+ * is called.
153
+ */
154
+ dispose() {
155
+ if (this.#disposed) {
156
+ return;
157
+ }
158
+ if (this.#state === 'open') {
159
+ // Disposing an open transaction is an internal invariant violation - roll back first.
160
+ try {
161
+ serviceLocator
162
+ .getLogger()
163
+ .warning('Internal error: a storage transaction was disposed while still open; rolling it back.');
164
+ }
165
+ catch {
166
+ // Never throw from dispose.
167
+ }
168
+ this.rollback();
169
+ }
170
+ this.#disposed = true;
171
+ this.journal.length = 0;
172
+ this.#afterCommitCallbacks.length = 0;
173
+ }
174
+ get datasetItems() {
175
+ return this.journal.flatMap((entry) => entry.type === 'dataset' ? entry.items.map((item) => ({ item, datasetId: entry.storageId })) : []);
176
+ }
177
+ get enqueuedUrls() {
178
+ return this.journal.flatMap((entry) => entry.type === 'requestQueue' ? entry.requests.map(({ url, label }) => ({ url, label })) : []);
179
+ }
180
+ get keyValueStoreChanges() {
181
+ const result = {};
182
+ for (const entry of this.journal) {
183
+ if (entry.type !== 'keyValueStore')
184
+ continue;
185
+ result[entry.storageId] ??= {};
186
+ result[entry.storageId][entry.key] = { changedValue: entry.value, options: entry.options };
187
+ }
188
+ return result;
189
+ }
190
+ }
191
+ /**
192
+ * Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
193
+ * `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
194
+ * open-run-commit flow, prefer {@link withStorageTransaction}.
195
+ */
196
+ export function createStorageTransaction(options = {}) {
197
+ return new StorageTransaction(options);
198
+ }
199
+ /**
200
+ * Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
201
+ * committed when it returns and rolled back when it throws. If a transaction is already active in the
202
+ * current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
203
+ * — there are no nested transaction semantics.
204
+ */
205
+ export async function withStorageTransaction(callback, options = {}) {
206
+ const existing = transactionStorage.getStore();
207
+ if (existing?.isActive) {
208
+ return callback(existing);
209
+ }
210
+ const transaction = createStorageTransaction(options);
211
+ try {
212
+ const result = await transaction.run(async () => callback(transaction));
213
+ await transaction.commit();
214
+ return result;
215
+ }
216
+ catch (error) {
217
+ transaction.rollback();
218
+ throw error;
219
+ }
220
+ finally {
221
+ transaction.dispose();
222
+ }
223
+ }
224
+ /**
225
+ * Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
226
+ * made inside it hit the real backend directly, are not rolled back, and operations that a transaction
227
+ * rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
228
+ */
229
+ export async function withDirectStorageAccess(callback) {
230
+ return transactionStorage.exit(async () => callback());
231
+ }
232
+ /**
233
+ * The per-operation hook consulted by every storage frontend method: performs the cancellation check
234
+ * that aborts storage operations when the request handler times out, and returns the active storage
235
+ * transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
236
+ * longer open — operations on a closed transaction deliberately pass through to the real backend.
237
+ * @internal
238
+ */
239
+ export function activeStorageTransaction() {
240
+ tryCancel();
241
+ const transaction = transactionStorage.getStore();
242
+ return transaction?.isActive ? transaction : undefined;
243
+ }
244
+ /**
245
+ * Returns the transaction installed in the current async context, regardless of its state. Used by the
246
+ * crawler to drive the outcome of the transaction it opened.
247
+ * @internal
248
+ */
249
+ export function currentStorageTransaction() {
250
+ return transactionStorage.getStore();
251
+ }
252
+ /**
253
+ * Captures a value at write time, so that later mutations of the caller's object affect neither the
254
+ * read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
255
+ * typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
256
+ * backends perform anyway.
257
+ * @internal
258
+ */
259
+ export function snapshotValue(value) {
260
+ try {
261
+ return structuredClone(value);
262
+ }
263
+ catch {
264
+ return JSON.parse(JSON.stringify(value));
265
+ }
266
+ }
267
+ /**
268
+ * The guard for operations that cannot be performed inside a storage transaction: throws when one is
269
+ * active, and performs the per-operation cancellation check either way.
270
+ * @internal
271
+ */
272
+ export function rejectOperationInTransaction(operation, reason = 'it cannot be rolled back.') {
273
+ if (activeStorageTransaction() === undefined) {
274
+ return;
275
+ }
276
+ throw operationRejectedInTransaction(operation, reason);
277
+ }
278
+ /**
279
+ * Builds the "operation not allowed in a transaction" error, for a call site that has already
280
+ * established a transaction is active and so wants to `throw` unconditionally.
281
+ * @internal
282
+ */
283
+ export function operationRejectedInTransaction(operation, reason = 'it cannot be rolled back.') {
284
+ return new Error(`${operation} cannot be used inside a storage transaction: ${reason} ` +
285
+ 'If you really need it, wrap the call in withDirectStorageAccess(() => ...) - operations ' +
286
+ 'performed there are applied immediately and are not rolled back.');
287
+ }
@@ -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