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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +362 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -129
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +68 -154
  47. package/enqueue_links/enqueue_links.js +38 -210
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +52 -26
  51. package/enqueue_links/shared.js +115 -66
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +108 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +201 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +409 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +14 -13
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +32 -147
  89. package/recoverable_state.d.ts +155 -0
  90. package/recoverable_state.js +231 -0
  91. package/request.d.ts +80 -16
  92. package/request.js +147 -68
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +73 -91
  110. package/session_pool/session_pool.js +172 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +291 -148
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +445 -169
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -115
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -82
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js +0 -430
  269. package/storages/sitemap_request_list.js.map +0 -1
  270. package/storages/storage_manager.d.ts +0 -58
  271. package/storages/storage_manager.d.ts.map +0 -1
  272. package/storages/storage_manager.js +0 -105
  273. package/storages/storage_manager.js.map +0 -1
  274. package/storages/utils.d.ts.map +0 -1
  275. package/storages/utils.js.map +0 -1
  276. package/tsconfig.build.tsbuildinfo +0 -1
  277. package/typedefs.d.ts.map +0 -1
  278. package/typedefs.js.map +0 -1
  279. package/validators.d.ts.map +0 -1
  280. package/validators.js.map +0 -1
@@ -0,0 +1,87 @@
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
+ type Hashable = string;
11
+ /**
12
+ * Unified manager for opening and caching storage instances (Dataset, KeyValueStore, RequestQueue).
13
+ *
14
+ * A single instance manages all storage types. Instances are cached by
15
+ * `(storageClass, id/name/alias, backendCacheKey)` so the same storage is never opened twice.
16
+ *
17
+ * The manager itself does not resolve identifiers — callers pass explicit `id`, `name`, or `alias` (at most one),
18
+ * and a pre-bound `backendOpener` promise. When none of `id`, `name`, `alias` are provided, the manager automatically
19
+ * assigns a reserved default alias.
20
+ */
21
+ export declare class StorageInstanceManager {
22
+ #private;
23
+ /**
24
+ * Open (or retrieve from cache) a storage instance.
25
+ *
26
+ * @param cls The storage class constructor (e.g. `Dataset`, `KeyValueStore`, `RequestQueue`).
27
+ * @param id Storage ID (mutually exclusive with `name` and `alias`).
28
+ * @param name Storage name (mutually exclusive with `id` and `alias`).
29
+ * @param alias Run-scoped alias (mutually exclusive with `id` and `name`).
30
+ * Automatically assigned when no identifier is provided.
31
+ * @param backendOpener A **lazy** factory that creates the sub-backend.
32
+ * Only called on a cache miss.
33
+ * @param backendCacheKey Opaque key identifying the storage backend, so that the same logical
34
+ * storage opened through different clients is cached separately.
35
+ */
36
+ openStorage<TStorage extends IStorage>(cls: Constructor<TStorage>, { id, name, alias, backendOpener, backendCacheKey, }: (ExplicitStorageIdentifier | DefaultStorageIdentifier) & {
37
+ backendOpener: () => Promise<DatasetBackend | KeyValueStoreBackend | RequestQueueBackend>;
38
+ backendCacheKey: Hashable;
39
+ }): Promise<TStorage>;
40
+ /**
41
+ * Remove a storage instance from the cache (called from `storage.drop()`).
42
+ */
43
+ removeFromCache(instance: IStorage): void;
44
+ /**
45
+ * Clear the entire cache. Also calls `clearCache()` on any cached KeyValueStore
46
+ * instances (duck-typed to avoid importing KeyValueStore and circular dependencies).
47
+ * Called during service locator reset.
48
+ */
49
+ clearCache(): void;
50
+ }
51
+ /**
52
+ * A storage identifier where exactly one of `id`, `name`, or `alias` is specified.
53
+ * Produced by {@link resolveStorageIdentifier} from ambiguous user input.
54
+ */
55
+ export type ExplicitStorageIdentifier = {
56
+ id: string;
57
+ name?: never;
58
+ alias?: never;
59
+ } | {
60
+ id?: never;
61
+ name: string;
62
+ alias?: never;
63
+ } | {
64
+ id?: never;
65
+ name?: never;
66
+ alias: string;
67
+ };
68
+ /**
69
+ * Represents the case where no identifier was provided — the caller wants the default storage.
70
+ */
71
+ export interface DefaultStorageIdentifier {
72
+ id?: never;
73
+ name?: never;
74
+ alias?: never;
75
+ }
76
+ /**
77
+ * Decompose a user-provided `identifier` (the `Dataset.open()` / `KeyValueStore.open()` /
78
+ * `RequestQueue.open()` argument) into separate `id`, `name`, and `alias` fields that
79
+ * the `StorageInstanceManager` and `StorageBackend.create*Client` expect.
80
+ *
81
+ * - `null` / `undefined` / `{}` → default storage alias
82
+ * - `string` → resolved via `storageExists` (ID-first, then name)
83
+ * - `{ id }` → `{ id }`
84
+ * - `{ name }` → `{ name }`
85
+ * - `{ alias }` → `{ alias }`
86
+ */
87
+ 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
+ }
@@ -0,0 +1,239 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ import type { Configuration } from '../configuration.js';
3
+ import type { Request, Source } from '../request.js';
4
+ import type { IRequestManager, RequestsLike } from './request_manager.js';
5
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
6
+ import type { StorageIdentifier } from './storage_instance_manager.js';
7
+ import type { StorageOpenOptions } from './utils.js';
8
+ /**
9
+ * Opens a request manager, matching the shape of storage `open` methods such as
10
+ * {@link RequestQueue.open|`RequestQueue.open`}.
11
+ *
12
+ * {@link ThrottlingRequestManager} calls this once per configured domain, so every per-domain queue shares the
13
+ * concrete type and storage backend of the manager being wrapped.
14
+ */
15
+ export type RequestManagerOpener<T extends IRequestManager = IRequestManager> = (identifier: string | StorageIdentifier, options?: StorageOpenOptions) => Promise<T>;
16
+ /**
17
+ * A request manager that can pace requests per domain, as {@link ThrottlingRequestManager} does.
18
+ *
19
+ * The crawlers detect this structurally rather than by type, so a wrapper can opt in by forwarding these three
20
+ * methods without {@link IRequestManager} having to know that throttling exists.
21
+ */
22
+ export interface SupportsDomainThrottling {
23
+ /** @see {@link ThrottlingRequestManager.recordDomainDelay} */
24
+ recordDomainDelay(url: string, retryAfterMs?: number | null): boolean;
25
+ /** @see {@link ThrottlingRequestManager.setCrawlDelay} */
26
+ setCrawlDelay(url: string, delaySeconds: number): boolean;
27
+ /** @see {@link ThrottlingRequestManager.assertNoStalledDomains} */
28
+ assertNoStalledDomains(): Promise<void>;
29
+ }
30
+ /** Whether `manager` can pace requests per domain. */
31
+ export declare function supportsDomainThrottling(manager: unknown): manager is SupportsDomainThrottling;
32
+ /** Options for {@link ThrottlingRequestManager}. */
33
+ export interface ThrottlingRequestManagerOptions<T extends IRequestManager = IRequestManager> {
34
+ /**
35
+ * The request manager to wrap, usually a {@link RequestQueue}. Requests for domains that are not throttled
36
+ * are stored here.
37
+ */
38
+ inner: T;
39
+ /**
40
+ * Which domains to throttle: a list of hostnames, or `'all'` for every domain the crawl encounters.
41
+ *
42
+ * Matching a listed hostname is case-insensitive and exact - wildcards such as `*.example.com` are not
43
+ * supported, so list each subdomain you care about (or set
44
+ * {@link ThrottlingRequestManagerOptions.throttleBy|`throttleBy: 'registrableDomain'`}). An
45
+ * internationalized domain may be given in either its unicode or its punycode form, and an IPv6 address has
46
+ * to be bracketed (`[::1]`). Requests for any other domain bypass throttling entirely.
47
+ *
48
+ * `'all'` gives each domain a queue of its own the first time it is seen, so that it can be held back
49
+ * without its requests being repeatedly popped and re-enqueued. One request queue per domain is not free,
50
+ * which is what {@link ThrottlingRequestManagerOptions.maxThrottledDomains|`maxThrottledDomains`} is
51
+ * there to bound.
52
+ */
53
+ domains: string[] | 'all';
54
+ /**
55
+ * A floor under the crawl delay of every throttled domain, in seconds - the proactive clock described on
56
+ * {@link ThrottlingRequestManager}. A domain whose robots.txt asks for a longer `Crawl-delay` gets the
57
+ * longer one; this is a minimum, not an override.
58
+ * @default 0
59
+ */
60
+ minCrawlDelaySecs?: number;
61
+ /**
62
+ * What counts as "the same domain": the exact hostname, or the registrable domain it belongs to
63
+ * (`example.com` for `www.example.com`, `a.example.co.uk` and so on). Hosts with no registrable domain -
64
+ * IP addresses, `localhost` - are always throttled per hostname.
65
+ *
66
+ * Grouping by registrable domain gives subdomains a single pair of clocks and a single queue, which is what
67
+ * you want when the pacing is there to be polite to one server rather than to satisfy a specific host's
68
+ * rate limit.
69
+ * @default 'hostname'
70
+ */
71
+ throttleBy?: 'hostname' | 'registrableDomain';
72
+ /**
73
+ * The most domains a run may throttle at once. Exceeding it throws, rather than silently letting the
74
+ * throttling lapse - one request queue per domain is not free, and a crawl that discovers domains without
75
+ * bound would drown the storage backend in them.
76
+ *
77
+ * Only domains discovered under `domains: 'all'` count against this; an explicit list is taken at face value.
78
+ * @default 100
79
+ */
80
+ maxThrottledDomains?: number;
81
+ /**
82
+ * The key under which the discovered domain list is kept in the default key-value store, so that a restart
83
+ * with `purgeOnStart` disabled reopens their queues instead of stranding whatever they still hold. Only
84
+ * written under `domains: 'all'`.
85
+ *
86
+ * Give each manager its own key when running several of them against the same storage.
87
+ * @default 'CRAWLEE_THROTTLED_DOMAINS'
88
+ */
89
+ persistStateKey?: string;
90
+ /**
91
+ * Opens the per-domain queues, one per throttled domain, each under the alias `throttled-<domain>`.
92
+ * @default RequestQueue.open
93
+ */
94
+ requestManagerOpener?: RequestManagerOpener<T>;
95
+ /**
96
+ * The delay applied after a domain's first HTTP 429, doubled on each subsequent one.
97
+ * @default 2
98
+ */
99
+ baseDelaySecs?: number;
100
+ /**
101
+ * Upper bound on the delay between requests to a rate-limited domain, applied to both the exponential
102
+ * backoff and a `Retry-After` value.
103
+ * @default 60
104
+ */
105
+ maxDelaySecs?: number;
106
+ /**
107
+ * How long a domain may rate-limit us without a single request getting through before the crawl is
108
+ * abandoned with a {@link PersistentRateLimitError}.
109
+ *
110
+ * A domain that keeps answering 429 for this long is not going to be crawled by waiting longer - the
111
+ * concurrency is too high for it, or it has blocked us outright. Its requests are deliberately left in
112
+ * their queue, so re-running the crawl with `purgeOnStart` disabled picks them up once the domain recovers.
113
+ *
114
+ * A crawler running with `keepAlive` is exempt - outliving a domain that will not let us through is the
115
+ * whole point there.
116
+ * @default 900
117
+ */
118
+ maxDomainStallSecs?: number;
119
+ }
120
+ /**
121
+ * A request manager that wraps another one and paces requests per domain.
122
+ *
123
+ * Requests for a throttled domain are routed into their own queue when they are added, so each request lives in
124
+ * exactly one place and deduplication keeps working. Everything else goes to the wrapped manager untouched.
125
+ *
126
+ * {@link ThrottlingRequestManager.fetchNextRequest|`fetchNextRequest()`} serves the domain that has been waiting
127
+ * longest and skips any that are backing off, falling back to the wrapped manager. It never blocks: while every
128
+ * remaining request belongs to a throttled domain it returns `null` and {@link ThrottlingRequestManager.isEmpty}
129
+ * reports `true`, so the crawler idles instead of holding a concurrency slot open.
130
+ *
131
+ * Each throttled domain runs two independent clocks, and may be dispatched to once **both** have run out:
132
+ * - **Backoff**, set by HTTP 429 responses - honouring `Retry-After`, and otherwise doubling from `baseDelaySecs`.
133
+ * Reactive and temporary: it decays once the domain stops turning us away. The crawlers report the 429s
134
+ * themselves; a request held back this way is retried later without counting against `maxRequestRetries` and
135
+ * without penalising its session.
136
+ * - **Crawl delay**, the minimum interval between two dispatches to the domain, armed after each one. Proactive
137
+ * and constant: whatever the domain's robots.txt asks for, floored by
138
+ * {@link ThrottlingRequestManagerOptions.minCrawlDelaySecs|`minCrawlDelaySecs`}. Either may be absent, in
139
+ * which case the other one is the delay.
140
+ *
141
+ * Which domains get those clocks is {@link ThrottlingRequestManagerOptions.domains|`domains`} - a list, or
142
+ * `'all'` for every domain the crawl encounters.
143
+ *
144
+ * **Example usage:**
145
+ *
146
+ * ```ts
147
+ * const crawler = new CheerioCrawler({
148
+ * requestManager: new ThrottlingRequestManager({
149
+ * inner: await RequestQueue.open(),
150
+ * domains: ['api.example.com', 'slow-site.org'],
151
+ * }),
152
+ * requestHandler: async ({ request }) => { ... },
153
+ * });
154
+ * ```
155
+ *
156
+ * @category Sources
157
+ */
158
+ export declare class ThrottlingRequestManager<T extends IRequestManager = IRequestManager> implements IRequestManager, SupportsDomainThrottling {
159
+ #private;
160
+ private readonly config;
161
+ private readonly domainStates;
162
+ private readonly log;
163
+ constructor(options: ThrottlingRequestManagerOptions<T>, config?: Configuration);
164
+ /** The wrapped manager, holding every request whose domain is not throttled. */
165
+ get innerManager(): T;
166
+ /**
167
+ * Records a 429 response and puts the URL's domain into backoff.
168
+ *
169
+ * @returns `false` if the domain is not configured for throttling, in which case this is a no-op.
170
+ */
171
+ recordDomainDelay(url: string, retryAfterMs?: number | null): boolean;
172
+ /**
173
+ * Records the `Crawl-delay` a domain's robots.txt asked for, which becomes its crawl delay unless
174
+ * {@link ThrottlingRequestManagerOptions.minCrawlDelaySecs|`minCrawlDelaySecs`} asks for longer.
175
+ *
176
+ * The first value wins, so a robots.txt re-fetch cannot change the cadence mid-crawl.
177
+ *
178
+ * @returns `false` if the domain is not throttled, in which case this is a no-op.
179
+ */
180
+ setCrawlDelay(url: string, delaySeconds: number): boolean;
181
+ /**
182
+ * Throws {@link PersistentRateLimitError} if any domain has been rate-limiting us past
183
+ * {@link ThrottlingRequestManagerOptions.maxDomainStallSecs|`maxDomainStallSecs`} without letting a single
184
+ * request through.
185
+ *
186
+ * A domain qualifies only while it still has queued requests and is actively rate-limiting - a domain that
187
+ * has simply run out of work is finished, not stalled, and one being waited out under a long robots.txt
188
+ * `Crawl-delay` is being obeyed, not stonewalled.
189
+ */
190
+ assertNoStalledDomains(): Promise<void>;
191
+ addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
192
+ /**
193
+ * Adds requests in batches, routing each one to the manager that owns its domain.
194
+ *
195
+ * Batching, validation, deduplication and `Retry-After`-free bookkeeping are all delegated to the target
196
+ * managers - this only decides where each request goes, one batch at a time, so a lazy or unbounded input
197
+ * iterable is never fully materialized.
198
+ */
199
+ addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
200
+ reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
201
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
202
+ getTotalCount(): Promise<number>;
203
+ getPendingCount(): Promise<number>;
204
+ getHandledCount(): Promise<number>;
205
+ /**
206
+ * Whether the next {@link ThrottlingRequestManager.fetchNextRequest} would return `null`.
207
+ *
208
+ * Requests waiting on a throttled domain count as unavailable, so a crawler whose task loop is gated on
209
+ * this idles for the backoff instead of spinning on a fetch that cannot succeed yet.
210
+ */
211
+ isEmpty(): Promise<boolean>;
212
+ /** Unlike {@link ThrottlingRequestManager.isEmpty}, throttled requests still count as outstanding work. */
213
+ isFinished(): Promise<boolean>;
214
+ /**
215
+ * Empties every manager and clears the accumulated backoff. A robots.txt `Crawl-delay` is a property of the
216
+ * site rather than of the run, so it survives.
217
+ */
218
+ purge(): Promise<void>;
219
+ /**
220
+ * Empties the per-domain queues, leaving the wrapped manager alone.
221
+ *
222
+ * Those queues are this manager's own no matter who owns the one it wraps, which is what makes this safe to
223
+ * call where a full {@link ThrottlingRequestManager.purge|`purge()`} would not be.
224
+ */
225
+ purgeDomainQueues(): Promise<void>;
226
+ setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
227
+ /**
228
+ * Returns the next request from a domain that is not backing off, or from the inner manager.
229
+ *
230
+ * Returns `null` while every remaining request belongs to a throttled domain - it never waits the backoff
231
+ * out, because a consumer parked in here holds a concurrency slot, which the autoscaler reads as spare
232
+ * capacity and answers by scaling up. Callers poll instead, and {@link ThrottlingRequestManager.isEmpty}
233
+ * reports `true` meanwhile so the crawler's task loop idles rather than spins.
234
+ */
235
+ fetchNextRequest<R extends Dictionary = Dictionary>(): Promise<Request<R> | null>;
236
+ [Symbol.asyncIterator](): AsyncGenerator<Request<Dictionary>, void, unknown>;
237
+ persistState(): Promise<void>;
238
+ drop(): Promise<void>;
239
+ }