@crawlee/core 4.0.0-beta.23 → 4.0.0-beta.231

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 (265) hide show
  1. package/README.md +15 -15
  2. package/byte-utils.d.ts +17 -0
  3. package/byte-utils.js +42 -0
  4. package/configuration.d.ts +77 -235
  5. package/configuration.js +157 -227
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +45 -18
  9. package/errors.js +58 -27
  10. package/events/event-manager.d.ts +78 -0
  11. package/events/{event_manager.js → event-manager.js} +12 -13
  12. package/events/index.d.ts +3 -3
  13. package/events/index.js +2 -3
  14. package/events/local-event-manager.d.ts +32 -0
  15. package/events/local-event-manager.js +101 -0
  16. package/events/system-info.d.ts +38 -0
  17. package/events/system-info.js +1 -0
  18. package/index.d.ts +9 -12
  19. package/index.js +10 -11
  20. package/internal.d.ts +8 -0
  21. package/internal.js +9 -0
  22. package/iterables.d.ts +79 -0
  23. package/iterables.js +134 -0
  24. package/log.d.ts +77 -1
  25. package/log.js +134 -1
  26. package/memory-storage/consts.d.ts +4 -0
  27. package/memory-storage/consts.js +4 -0
  28. package/memory-storage/index.d.ts +1 -0
  29. package/memory-storage/index.js +1 -0
  30. package/memory-storage/memory-storage.d.ts +43 -0
  31. package/memory-storage/memory-storage.js +158 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +35 -0
  35. package/memory-storage/resource-clients/dataset.js +105 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +54 -0
  37. package/memory-storage/resource-clients/key-value-store.js +179 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +55 -0
  39. package/memory-storage/resource-clients/request-queue.js +413 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned-or-injected.d.ts +58 -0
  43. package/owned-or-injected.js +98 -0
  44. package/package.json +20 -20
  45. package/proxy-configuration.d.ts +118 -0
  46. package/proxy-configuration.js +141 -0
  47. package/recoverable-state.d.ts +177 -0
  48. package/recoverable-state.js +268 -0
  49. package/request.d.ts +48 -93
  50. package/request.js +112 -230
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service-locator.d.ts +168 -0
  54. package/service-locator.js +255 -0
  55. package/storages/batched-adds.d.ts +37 -0
  56. package/storages/batched-adds.js +73 -0
  57. package/storages/dataset.d.ts +105 -58
  58. package/storages/dataset.js +292 -150
  59. package/storages/index.d.ts +11 -12
  60. package/storages/index.js +7 -12
  61. package/storages/key-value-store-codec.d.ts +32 -0
  62. package/storages/key-value-store-codec.js +108 -0
  63. package/storages/{key_value_store.d.ts → key-value-store.d.ts} +169 -72
  64. package/storages/key-value-store.js +767 -0
  65. package/storages/request-dedup-cache.d.ts +20 -0
  66. package/storages/request-dedup-cache.js +48 -0
  67. package/storages/{request_list.d.ts → request-list.d.ts} +33 -173
  68. package/storages/{request_list.js → request-list.js} +276 -255
  69. package/storages/request-loader.d.ts +127 -0
  70. package/storages/request-loader.js +36 -0
  71. package/storages/request-manager-tandem.d.ts +82 -0
  72. package/storages/request-manager-tandem.js +200 -0
  73. package/storages/request-manager.d.ts +119 -0
  74. package/storages/request-manager.js +1 -0
  75. package/storages/{request_provider.d.ts → request-queue.d.ts} +128 -159
  76. package/storages/request-queue.js +870 -0
  77. package/storages/storage-instance-manager.d.ts +86 -0
  78. package/storages/storage-instance-manager.js +256 -0
  79. package/storages/storage-stats.d.ts +48 -0
  80. package/storages/storage-stats.js +29 -0
  81. package/storages/transaction.d.ts +270 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +76 -16
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -285
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -191
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -60
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -55
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -213
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -349
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts +0 -52
  168. package/events/event_manager.d.ts.map +0 -1
  169. package/events/event_manager.js.map +0 -1
  170. package/events/index.d.ts.map +0 -1
  171. package/events/index.js.map +0 -1
  172. package/events/local_event_manager.d.ts +0 -27
  173. package/events/local_event_manager.d.ts.map +0 -1
  174. package/events/local_event_manager.js +0 -75
  175. package/events/local_event_manager.js.map +0 -1
  176. package/index.d.ts.map +0 -1
  177. package/index.js.map +0 -1
  178. package/log.d.ts.map +0 -1
  179. package/log.js.map +0 -1
  180. package/proxy_configuration.d.ts +0 -169
  181. package/proxy_configuration.d.ts.map +0 -1
  182. package/proxy_configuration.js +0 -247
  183. package/proxy_configuration.js.map +0 -1
  184. package/recoverable_state.d.ts +0 -123
  185. package/recoverable_state.d.ts.map +0 -1
  186. package/recoverable_state.js +0 -140
  187. package/recoverable_state.js.map +0 -1
  188. package/request.d.ts.map +0 -1
  189. package/request.js.map +0 -1
  190. package/router.d.ts +0 -134
  191. package/router.d.ts.map +0 -1
  192. package/router.js +0 -164
  193. package/router.js.map +0 -1
  194. package/serialization.d.ts.map +0 -1
  195. package/serialization.js.map +0 -1
  196. package/session_pool/consts.d.ts +0 -4
  197. package/session_pool/consts.d.ts.map +0 -1
  198. package/session_pool/consts.js +0 -4
  199. package/session_pool/consts.js.map +0 -1
  200. package/session_pool/errors.d.ts +0 -8
  201. package/session_pool/errors.d.ts.map +0 -1
  202. package/session_pool/errors.js +0 -12
  203. package/session_pool/errors.js.map +0 -1
  204. package/session_pool/events.d.ts +0 -3
  205. package/session_pool/events.d.ts.map +0 -1
  206. package/session_pool/events.js +0 -3
  207. package/session_pool/events.js.map +0 -1
  208. package/session_pool/index.d.ts +0 -6
  209. package/session_pool/index.d.ts.map +0 -1
  210. package/session_pool/index.js +0 -6
  211. package/session_pool/index.js.map +0 -1
  212. package/session_pool/session.d.ts +0 -186
  213. package/session_pool/session.d.ts.map +0 -1
  214. package/session_pool/session.js +0 -278
  215. package/session_pool/session.js.map +0 -1
  216. package/session_pool/session_pool.d.ts +0 -258
  217. package/session_pool/session_pool.d.ts.map +0 -1
  218. package/session_pool/session_pool.js +0 -387
  219. package/session_pool/session_pool.js.map +0 -1
  220. package/storages/access_checking.d.ts +0 -13
  221. package/storages/access_checking.d.ts.map +0 -1
  222. package/storages/access_checking.js +0 -14
  223. package/storages/access_checking.js.map +0 -1
  224. package/storages/dataset.d.ts.map +0 -1
  225. package/storages/dataset.js.map +0 -1
  226. package/storages/index.d.ts.map +0 -1
  227. package/storages/index.js.map +0 -1
  228. package/storages/key_value_store.d.ts.map +0 -1
  229. package/storages/key_value_store.js +0 -512
  230. package/storages/key_value_store.js.map +0 -1
  231. package/storages/request_list.d.ts.map +0 -1
  232. package/storages/request_list.js.map +0 -1
  233. package/storages/request_list_adapter.d.ts +0 -58
  234. package/storages/request_list_adapter.d.ts.map +0 -1
  235. package/storages/request_list_adapter.js +0 -81
  236. package/storages/request_list_adapter.js.map +0 -1
  237. package/storages/request_manager_tandem.d.ts +0 -68
  238. package/storages/request_manager_tandem.d.ts.map +0 -1
  239. package/storages/request_manager_tandem.js +0 -124
  240. package/storages/request_manager_tandem.js.map +0 -1
  241. package/storages/request_provider.d.ts.map +0 -1
  242. package/storages/request_provider.js +0 -591
  243. package/storages/request_provider.js.map +0 -1
  244. package/storages/request_queue.d.ts +0 -128
  245. package/storages/request_queue.d.ts.map +0 -1
  246. package/storages/request_queue.js +0 -320
  247. package/storages/request_queue.js.map +0 -1
  248. package/storages/request_queue_v2.d.ts +0 -87
  249. package/storages/request_queue_v2.d.ts.map +0 -1
  250. package/storages/request_queue_v2.js +0 -438
  251. package/storages/request_queue_v2.js.map +0 -1
  252. package/storages/sitemap_request_list.d.ts +0 -250
  253. package/storages/sitemap_request_list.d.ts.map +0 -1
  254. package/storages/sitemap_request_list.js +0 -431
  255. package/storages/sitemap_request_list.js.map +0 -1
  256. package/storages/storage_manager.d.ts +0 -62
  257. package/storages/storage_manager.d.ts.map +0 -1
  258. package/storages/storage_manager.js +0 -105
  259. package/storages/storage_manager.js.map +0 -1
  260. package/storages/utils.d.ts.map +0 -1
  261. package/storages/utils.js.map +0 -1
  262. package/typedefs.d.ts.map +0 -1
  263. package/typedefs.js.map +0 -1
  264. package/validators.d.ts.map +0 -1
  265. package/validators.js.map +0 -1
@@ -0,0 +1,86 @@
1
+ import type { Constructor, DatasetBackend, KeyValueStoreBackend, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
2
+ export type { StorageIdentifier } from '@crawlee/types';
3
+ /**
4
+ * Matches an `IStorage` – a storage "frontend" (Dataset, KeyValueStore, RequestQueue).
5
+ */
6
+ export interface IStorage {
7
+ id: string;
8
+ name?: string;
9
+ }
10
+ /**
11
+ * Unified manager for opening and caching storage instances (Dataset, KeyValueStore, RequestQueue).
12
+ *
13
+ * A single instance manages all storage types. Instances are cached by
14
+ * `(storageClass, id/name/alias, backendCacheKey)` so the same storage is never opened twice.
15
+ *
16
+ * The manager itself does not resolve identifiers — callers pass explicit `id`, `name`, or `alias` (at most one),
17
+ * and a pre-bound `backendOpener` promise. When none of `id`, `name`, `alias` are provided, the manager automatically
18
+ * assigns a reserved default alias.
19
+ */
20
+ export declare class StorageInstanceManager {
21
+ #private;
22
+ /**
23
+ * Open (or retrieve from cache) a storage instance.
24
+ *
25
+ * @param cls The storage class constructor (e.g. `Dataset`, `KeyValueStore`, `RequestQueue`).
26
+ * @param id Storage ID (mutually exclusive with `name` and `alias`).
27
+ * @param name Storage name (mutually exclusive with `id` and `alias`).
28
+ * @param alias Run-scoped alias (mutually exclusive with `id` and `name`).
29
+ * Automatically assigned when no identifier is provided.
30
+ * @param backendOpener A **lazy** factory that creates the sub-backend.
31
+ * Only called on a cache miss.
32
+ * @param backendCacheKey Opaque key identifying the storage backend, so that the same logical
33
+ * storage opened through different clients is cached separately.
34
+ */
35
+ openStorage<TStorage extends IStorage>(cls: Constructor<TStorage>, { id, name, alias, backendOpener, backendCacheKey, }: (ExplicitStorageIdentifier | DefaultStorageIdentifier) & {
36
+ backendOpener: () => Promise<DatasetBackend | KeyValueStoreBackend | RequestQueueBackend>;
37
+ backendCacheKey: string;
38
+ }): Promise<TStorage>;
39
+ /**
40
+ * Remove a storage instance from the cache (called from `storage.drop()`).
41
+ */
42
+ removeFromCache(instance: IStorage): void;
43
+ /**
44
+ * Clear the entire cache. Also calls `clearCache()` on any cached KeyValueStore
45
+ * instances (duck-typed to avoid importing KeyValueStore and circular dependencies).
46
+ * Called during service locator reset.
47
+ */
48
+ clearCache(): void;
49
+ }
50
+ /**
51
+ * A storage identifier where exactly one of `id`, `name`, or `alias` is specified.
52
+ * Produced by {@link resolveStorageIdentifier} from ambiguous user input.
53
+ */
54
+ export type ExplicitStorageIdentifier = {
55
+ id: string;
56
+ name?: never;
57
+ alias?: never;
58
+ } | {
59
+ id?: never;
60
+ name: string;
61
+ alias?: never;
62
+ } | {
63
+ id?: never;
64
+ name?: never;
65
+ alias: string;
66
+ };
67
+ /**
68
+ * Represents the case where no identifier was provided — the caller wants the default storage.
69
+ */
70
+ export interface DefaultStorageIdentifier {
71
+ id?: never;
72
+ name?: never;
73
+ alias?: never;
74
+ }
75
+ /**
76
+ * Decompose a user-provided `identifier` (the `Dataset.open()` / `KeyValueStore.open()` /
77
+ * `RequestQueue.open()` argument) into separate `id`, `name`, and `alias` fields that
78
+ * the `StorageInstanceManager` and `StorageBackend.create*Client` expect.
79
+ *
80
+ * - `null` / `undefined` / `{}` → default storage alias
81
+ * - `string` → resolved via `storageExists` (ID-first, then name)
82
+ * - `{ id }` → `{ id }`
83
+ * - `{ name }` → `{ name }`
84
+ * - `{ alias }` → `{ alias }`
85
+ */
86
+ export declare function resolveStorageIdentifier(identifier: string | StorageIdentifier | null | undefined, storageBackend: StorageBackend, storageType: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<ExplicitStorageIdentifier>;
@@ -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
+ }