@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,256 @@
1
+ import { AsyncQueue } from '@sapphire/async-queue';
2
+ /** Reserved alias for the default (unnamed) storage. */
3
+ const DEFAULT_STORAGE_ALIAS = '__default__';
4
+ /**
5
+ * Three-tier cache for storage instances, modelled after crawlee-python's `_StorageCache`.
6
+ *
7
+ * Each tier maps `[storageClass][key][backendCacheKey] → instance`:
8
+ * - `byId` — keyed by the backend-assigned storage id
9
+ * - `byName` — keyed by the persistent storage name
10
+ * - `byAlias` — keyed by a run-scoped alias (e.g. `'__default__'` for unnamed storages)
11
+ */
12
+ class StorageCache {
13
+ byId = new Map();
14
+ byName = new Map();
15
+ byAlias = new Map();
16
+ get(cls, { id, name, alias, backendCacheKey, }) {
17
+ for (const [tier, key] of [
18
+ [this.byId, id],
19
+ [this.byName, name],
20
+ [this.byAlias, alias],
21
+ ]) {
22
+ if (key === undefined)
23
+ continue;
24
+ const cached = tier.get(cls)?.get(key)?.get(backendCacheKey);
25
+ if (cached) {
26
+ if (cached instanceof cls) {
27
+ return cached;
28
+ }
29
+ throw new Error('Cached storage instance type mismatch.');
30
+ }
31
+ }
32
+ return undefined;
33
+ }
34
+ /** Write a single entry into a given tier. */
35
+ setInMap(tier, cls, key, instance, backendCacheKey) {
36
+ if (!tier.has(cls))
37
+ tier.set(cls, new Map());
38
+ const keyMap = tier.get(cls);
39
+ if (!keyMap.has(key))
40
+ keyMap.set(key, new Map());
41
+ keyMap.get(key).set(backendCacheKey, instance);
42
+ }
43
+ /**
44
+ * Cache an instance under its actual id, name, and an optional alias.
45
+ */
46
+ set(cls, instance, backendCacheKey, alias) {
47
+ // Always cache by id.
48
+ this.setInMap(this.byId, cls, instance.id, instance, backendCacheKey);
49
+ // Cache by name — only for named storages.
50
+ if (instance.name) {
51
+ this.setInMap(this.byName, cls, instance.name, instance, backendCacheKey);
52
+ }
53
+ // Cache by alias — only for unnamed storages opened via alias.
54
+ if (alias !== undefined) {
55
+ this.setInMap(this.byAlias, cls, alias, instance, backendCacheKey);
56
+ }
57
+ }
58
+ removeFromCache(instance) {
59
+ const storageType = instance.constructor;
60
+ for (const tier of [this.byId, this.byName, this.byAlias]) {
61
+ const classMap = tier.get(storageType);
62
+ if (!classMap)
63
+ continue;
64
+ for (const keyMap of classMap.values()) {
65
+ for (const [cacheKey, cached] of keyMap) {
66
+ if (cached === instance) {
67
+ keyMap.delete(cacheKey);
68
+ }
69
+ }
70
+ }
71
+ }
72
+ }
73
+ /**
74
+ * Ensure that the same string is not used as both a name and an alias for the same
75
+ * storage class + backend combination. Mirrors crawlee-python's `_check_name_alias_conflict`.
76
+ */
77
+ checkNameAliasConflict(cls, { name, alias, backendCacheKey }) {
78
+ if (alias) {
79
+ const existingByName = this.byName.get(cls)?.get(alias)?.get(backendCacheKey);
80
+ if (existingByName) {
81
+ throw new Error(`Cannot open storage with alias "${alias}" because a named storage with the same identifier already exists.`);
82
+ }
83
+ }
84
+ if (name) {
85
+ const existingByAlias = this.byAlias.get(cls)?.get(name)?.get(backendCacheKey);
86
+ if (existingByAlias) {
87
+ throw new Error(`Cannot open storage with name "${name}" because an alias storage with the same identifier already exists.` +
88
+ ` If you meant to open the alias storage, use { alias: "${name}" } instead.`);
89
+ }
90
+ }
91
+ }
92
+ /** Iterate all cached instances across all storage types. */
93
+ *allValues() {
94
+ const seen = new Set();
95
+ for (const classMap of this.byId.values()) {
96
+ for (const keyMap of classMap.values()) {
97
+ for (const instance of keyMap.values()) {
98
+ if (!seen.has(instance)) {
99
+ seen.add(instance);
100
+ yield instance;
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+ clear() {
107
+ this.byId.clear();
108
+ this.byName.clear();
109
+ this.byAlias.clear();
110
+ }
111
+ }
112
+ /**
113
+ * Unified manager for opening and caching storage instances (Dataset, KeyValueStore, RequestQueue).
114
+ *
115
+ * A single instance manages all storage types. Instances are cached by
116
+ * `(storageClass, id/name/alias, backendCacheKey)` so the same storage is never opened twice.
117
+ *
118
+ * The manager itself does not resolve identifiers — callers pass explicit `id`, `name`, or `alias` (at most one),
119
+ * and a pre-bound `backendOpener` promise. When none of `id`, `name`, `alias` are provided, the manager automatically
120
+ * assigns a reserved default alias.
121
+ */
122
+ export class StorageInstanceManager {
123
+ #cache = new StorageCache();
124
+ #openerLocks = new Map();
125
+ /**
126
+ * Open (or retrieve from cache) a storage instance.
127
+ *
128
+ * @param cls The storage class constructor (e.g. `Dataset`, `KeyValueStore`, `RequestQueue`).
129
+ * @param id Storage ID (mutually exclusive with `name` and `alias`).
130
+ * @param name Storage name (mutually exclusive with `id` and `alias`).
131
+ * @param alias Run-scoped alias (mutually exclusive with `id` and `name`).
132
+ * Automatically assigned when no identifier is provided.
133
+ * @param backendOpener A **lazy** factory that creates the sub-backend.
134
+ * Only called on a cache miss.
135
+ * @param backendCacheKey Opaque key identifying the storage backend, so that the same logical
136
+ * storage opened through different clients is cached separately.
137
+ */
138
+ async openStorage(cls, { id, name, alias, backendOpener, backendCacheKey, }) {
139
+ // Auto-set alias='__default__' when no parameters are specified (mirrors crawlee-python).
140
+ if (!id && !name && !alias) {
141
+ alias = DEFAULT_STORAGE_ALIAS;
142
+ }
143
+ // Fast-path cache check (no lock).
144
+ if (alias !== undefined) {
145
+ const cached = this.#cache.get(cls, { alias, backendCacheKey });
146
+ if (cached)
147
+ return cached;
148
+ }
149
+ else if (id) {
150
+ const cached = this.#cache.get(cls, { id, backendCacheKey });
151
+ if (cached)
152
+ return cached;
153
+ }
154
+ else if (name) {
155
+ const cached = this.#cache.get(cls, { name, backendCacheKey });
156
+ if (cached)
157
+ return cached;
158
+ }
159
+ const identifierKey = id ?? name ?? alias ?? DEFAULT_STORAGE_ALIAS;
160
+ const lockKey = `${cls.name}:${identifierKey}:${backendCacheKey}`;
161
+ if (!this.#openerLocks.has(lockKey)) {
162
+ this.#openerLocks.set(lockKey, new AsyncQueue());
163
+ }
164
+ const queue = this.#openerLocks.get(lockKey);
165
+ await queue.wait();
166
+ try {
167
+ // Double-check cache under lock (another caller may have filled it while we waited).
168
+ if (alias !== undefined) {
169
+ const cached = this.#cache.get(cls, { alias, backendCacheKey });
170
+ if (cached)
171
+ return cached;
172
+ }
173
+ else if (id) {
174
+ const cached = this.#cache.get(cls, { id, backendCacheKey });
175
+ if (cached)
176
+ return cached;
177
+ }
178
+ else if (name) {
179
+ const cached = this.#cache.get(cls, { name, backendCacheKey });
180
+ if (cached)
181
+ return cached;
182
+ }
183
+ // Prevent the same string from being used as both a name and an alias.
184
+ this.#cache.checkNameAliasConflict(cls, { name, alias, backendCacheKey });
185
+ // Cache miss — create the sub-backend and storage instance.
186
+ const subBackend = await backendOpener();
187
+ const storageInfo = await subBackend.getMetadata();
188
+ // Storage frontends are thin wrappers over the backend. We hand them the resolved metadata
189
+ // we just fetched (so `id`/`name` etc. are available synchronously) along with the backend.
190
+ const instance = new cls({ metadata: storageInfo, backend: subBackend });
191
+ // Atomic cache writes (no awaits between these).
192
+ this.#cache.set(cls, instance, backendCacheKey, alias);
193
+ return instance;
194
+ }
195
+ finally {
196
+ queue.shift();
197
+ // Clean up idle locks so the map doesn't grow unboundedly
198
+ // (mirrors crawlee-python's WeakValueDictionary behaviour).
199
+ if (queue.remaining === 0) {
200
+ this.#openerLocks.delete(lockKey);
201
+ }
202
+ }
203
+ }
204
+ /**
205
+ * Remove a storage instance from the cache (called from `storage.drop()`).
206
+ */
207
+ removeFromCache(instance) {
208
+ this.#cache.removeFromCache(instance);
209
+ }
210
+ /**
211
+ * Clear the entire cache. Also calls `clearCache()` on any cached KeyValueStore
212
+ * instances (duck-typed to avoid importing KeyValueStore and circular dependencies).
213
+ * Called during service locator reset.
214
+ */
215
+ clearCache() {
216
+ for (const instance of this.#cache.allValues()) {
217
+ if ('clearCache' in instance && typeof instance.clearCache === 'function') {
218
+ instance.clearCache();
219
+ }
220
+ }
221
+ this.#cache.clear();
222
+ }
223
+ }
224
+ /**
225
+ * Decompose a user-provided `identifier` (the `Dataset.open()` / `KeyValueStore.open()` /
226
+ * `RequestQueue.open()` argument) into separate `id`, `name`, and `alias` fields that
227
+ * the `StorageInstanceManager` and `StorageBackend.create*Client` expect.
228
+ *
229
+ * - `null` / `undefined` / `{}` → default storage alias
230
+ * - `string` → resolved via `storageExists` (ID-first, then name)
231
+ * - `{ id }` → `{ id }`
232
+ * - `{ name }` → `{ name }`
233
+ * - `{ alias }` → `{ alias }`
234
+ */
235
+ export async function resolveStorageIdentifier(identifier, storageBackend, storageType) {
236
+ if (identifier === null || identifier === undefined) {
237
+ return { alias: DEFAULT_STORAGE_ALIAS };
238
+ }
239
+ if (typeof identifier === 'string') {
240
+ if (storageBackend.storageExists && (await storageBackend.storageExists(identifier, storageType))) {
241
+ return { id: identifier };
242
+ }
243
+ return { name: identifier };
244
+ }
245
+ if (identifier.id) {
246
+ return { id: identifier.id };
247
+ }
248
+ if (identifier.name) {
249
+ return { name: identifier.name };
250
+ }
251
+ if ('alias' in identifier && identifier.alias) {
252
+ return { alias: identifier.alias };
253
+ }
254
+ // Empty object — treated as default storage.
255
+ return { alias: DEFAULT_STORAGE_ALIAS };
256
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Backend-independent usage counters tracked by the storage frontend classes
3
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
4
+ *
5
+ * These count the operations the frontend issues against its underlying storage backend, so they are
6
+ * meaningful for any storage backend (memory, file system, cloud). They are tallied per client call
7
+ * — e.g. iterating a key-value store increments `readCount` once per record fetched and `listCount`
8
+ * once per listed page. Backend-specific figures that the frontend cannot compute (such as the number
9
+ * of bytes stored) are intentionally not included here; read those from the backend's own API instead.
10
+ */
11
+ /** Usage counters for a {@link Dataset}. */
12
+ export interface DatasetStats {
13
+ /** Number of read operations issued to the dataset client (e.g. `getData`). */
14
+ readCount: number;
15
+ /** Number of write operations issued to the dataset client (e.g. `pushData`). */
16
+ writeCount: number;
17
+ }
18
+ /** Usage counters for a {@link KeyValueStore}. */
19
+ export interface KeyValueStoreStats {
20
+ /** Number of read operations issued to the key-value store client (e.g. `getValue`). */
21
+ readCount: number;
22
+ /** Number of write operations issued to the key-value store client (e.g. `setValue`). */
23
+ writeCount: number;
24
+ /** Number of delete operations issued to the key-value store client (e.g. `deleteValue`). */
25
+ deleteCount: number;
26
+ /** Number of listing operations issued to the key-value store client (e.g. `listKeys`). */
27
+ listCount: number;
28
+ }
29
+ /** Usage counters for a {@link RequestQueue}. */
30
+ export interface RequestQueueStats {
31
+ /** Number of write operations issued to the request queue client (add / handle / reclaim). */
32
+ writeCount: number;
33
+ /** Number of queue-head reads issued to the request queue client (`fetchNextRequest`). */
34
+ headItemReadCount: number;
35
+ }
36
+ /**
37
+ * A tiny mutable counter that the storage frontends increment on each client call and expose through
38
+ * a read-only `stats` snapshot. Generic over the concrete counter shape so each storage type gets only
39
+ * the buckets that make sense for it.
40
+ */
41
+ export declare class StorageStatsTracker<T extends Record<keyof T, number>> {
42
+ #private;
43
+ constructor(initial: T);
44
+ /** Increment a counter bucket by `by` (default `1`). */
45
+ add(key: keyof T, by?: number): void;
46
+ /** Return a snapshot of the current counters. The returned object is a copy and safe to keep. */
47
+ get current(): T;
48
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Backend-independent usage counters tracked by the storage frontend classes
3
+ * ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
4
+ *
5
+ * These count the operations the frontend issues against its underlying storage backend, so they are
6
+ * meaningful for any storage backend (memory, file system, cloud). They are tallied per client call
7
+ * — e.g. iterating a key-value store increments `readCount` once per record fetched and `listCount`
8
+ * once per listed page. Backend-specific figures that the frontend cannot compute (such as the number
9
+ * of bytes stored) are intentionally not included here; read those from the backend's own API instead.
10
+ */
11
+ /**
12
+ * A tiny mutable counter that the storage frontends increment on each client call and expose through
13
+ * a read-only `stats` snapshot. Generic over the concrete counter shape so each storage type gets only
14
+ * the buckets that make sense for it.
15
+ */
16
+ export class StorageStatsTracker {
17
+ #counters;
18
+ constructor(initial) {
19
+ this.#counters = { ...initial };
20
+ }
21
+ /** Increment a counter bucket by `by` (default `1`). */
22
+ add(key, by = 1) {
23
+ this.#counters[key] += by;
24
+ }
25
+ /** Return a snapshot of the current counters. The returned object is a copy and safe to keep. */
26
+ get current() {
27
+ return { ...this.#counters };
28
+ }
29
+ }
@@ -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;