@crawlee/core 4.0.0-beta.12 → 4.0.0-beta.121

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 (279) 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 +47 -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 +106 -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 +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 +143 -59
  43. package/crawlers/statistics.js +243 -153
  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 +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +10 -12
  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 +114 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +204 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +422 -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 +13 -12
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +24 -143
  89. package/recoverable_state.d.ts +140 -0
  90. package/recoverable_state.js +212 -0
  91. package/request.d.ts +86 -17
  92. package/request.js +120 -41
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +9 -11
  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 -89
  108. package/session_pool/session.js +82 -142
  109. package/session_pool/session_pool.d.ts +69 -90
  110. package/session_pool/session_pool.js +151 -150
  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 +285 -144
  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 +424 -151
  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 -116
  124. package/storages/request_list.js +159 -133
  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 +757 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  134. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +137 -143
  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 +216 -0
  140. package/storages/throttling_request_manager.js +453 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +58 -11
  144. package/storages/utils.js +64 -13
  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 +8 -1
  158. package/validators.js +10 -3
  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 -134
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -33
  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 -15
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -69
  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.map +0 -1
  269. package/storages/storage_manager.d.ts +0 -58
  270. package/storages/storage_manager.d.ts.map +0 -1
  271. package/storages/storage_manager.js +0 -105
  272. package/storages/storage_manager.js.map +0 -1
  273. package/storages/utils.d.ts.map +0 -1
  274. package/storages/utils.js.map +0 -1
  275. package/tsconfig.build.tsbuildinfo +0 -1
  276. package/typedefs.d.ts.map +0 -1
  277. package/typedefs.js.map +0 -1
  278. package/validators.d.ts.map +0 -1
  279. package/validators.js.map +0 -1
@@ -0,0 +1,130 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { DatasetBackend } from './resource-clients/dataset.js';
3
+ import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
4
+ import { RequestQueueBackend } from './resource-clients/request-queue.js';
5
+ /** The alias the default (unnamed) storage is opened under. */
6
+ const DEFAULT_STORAGE_ALIAS = '__default__';
7
+ export class MemoryStorageBackend {
8
+ logger;
9
+ /**
10
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
11
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
12
+ */
13
+ #instanceCacheKey = `MemoryStorageBackend:${randomUUID()}`;
14
+ keyValueStoreBackendCache = [];
15
+ datasetBackendCache = [];
16
+ requestQueueBackendCache = [];
17
+ constructor(options = {}) {
18
+ this.logger = options.logger;
19
+ }
20
+ /**
21
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
22
+ * cache partitions in the storage backend cache.
23
+ */
24
+ getStorageBackendCacheKey() {
25
+ return this.#instanceCacheKey;
26
+ }
27
+ static #resolveStorageKey(options) {
28
+ // No identifier at all means the default storage, which is opened under the reserved alias —
29
+ // same rule as `resolveStorageIdentifier` in the storage frontends, so that a backend used
30
+ // directly lands on the very storage the frontends would have opened.
31
+ const alias = options.alias || (!options.id && !options.name ? DEFAULT_STORAGE_ALIAS : undefined);
32
+ // `alias` covers the identifier-less case, so one of the three is always set.
33
+ const rawKey = alias ?? options.name ?? options.id;
34
+ // Normalize the internal __default__ alias to the user-facing 'default' name.
35
+ const cacheKey = rawKey === DEFAULT_STORAGE_ALIAS ? 'default' : rawKey;
36
+ return { isAlias: alias !== undefined, cacheKey };
37
+ }
38
+ async createDatasetBackend(options = {}) {
39
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
40
+ const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
41
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
42
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
43
+ if (found) {
44
+ return found;
45
+ }
46
+ const newStore = new DatasetBackend({
47
+ name: isAlias ? undefined : cacheKey,
48
+ cacheKey,
49
+ storageBackend: this,
50
+ });
51
+ this.datasetBackendCache.push(newStore);
52
+ return newStore;
53
+ }
54
+ async createKeyValueStoreBackend(options = {}) {
55
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
56
+ const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
57
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
58
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
59
+ if (found) {
60
+ return found;
61
+ }
62
+ const newStore = new KeyValueStoreBackend({
63
+ name: isAlias ? undefined : cacheKey,
64
+ cacheKey,
65
+ storageBackend: this,
66
+ });
67
+ this.keyValueStoreBackendCache.push(newStore);
68
+ return newStore;
69
+ }
70
+ async createRequestQueueBackend(options = {}) {
71
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
72
+ const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
73
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
74
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
75
+ if (found) {
76
+ return found;
77
+ }
78
+ const newStore = new RequestQueueBackend({
79
+ name: isAlias ? undefined : cacheKey,
80
+ cacheKey,
81
+ storageBackend: this,
82
+ });
83
+ this.requestQueueBackendCache.push(newStore);
84
+ return newStore;
85
+ }
86
+ async storageExists(id, type) {
87
+ let backends;
88
+ switch (type) {
89
+ case 'Dataset':
90
+ backends = this.datasetBackendCache;
91
+ break;
92
+ case 'KeyValueStore':
93
+ backends = this.keyValueStoreBackendCache;
94
+ break;
95
+ case 'RequestQueue':
96
+ backends = this.requestQueueBackendCache;
97
+ break;
98
+ default:
99
+ return false;
100
+ }
101
+ // In-memory storage only knows about backends in its cache.
102
+ return backends.some((store) => store.id === id);
103
+ }
104
+ /**
105
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
106
+ * resets the in-memory state of the cached backends.
107
+ */
108
+ async purge() {
109
+ // `#resolveStorageKey` leaves `name` unset for the default and alias-keyed storages, which is what
110
+ // marks them as run-scoped. `'default'` is the exception — it collapses onto the default storage.
111
+ const isRunScoped = (store) => store.name === undefined || store.name === 'default';
112
+ const isDefault = (store) => store.name === 'default' || store.cacheKey === 'default';
113
+ const purgeRunScoped = async (cache, purgeStore) => {
114
+ await Promise.all(cache.filter(isRunScoped).map(async (store) => purgeStore(store)));
115
+ };
116
+ await Promise.all([
117
+ // Only the default store holds the run input, so it is the only one that keeps `INPUT`.
118
+ purgeRunScoped(this.keyValueStoreBackendCache, async (store) => isDefault(store) ? store.purgeExceptInput() : store.purge()),
119
+ purgeRunScoped(this.datasetBackendCache, async (store) => store.purge()),
120
+ purgeRunScoped(this.requestQueueBackendCache, async (store) => store.purge()),
121
+ ]);
122
+ }
123
+ /**
124
+ * This method should be called at the end of the process. The in-memory storage holds no resources
125
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
126
+ */
127
+ async teardown() {
128
+ // Nothing to tear down for in-memory storage.
129
+ }
130
+ }
@@ -0,0 +1,4 @@
1
+ export declare class BaseClient {
2
+ id: string;
3
+ constructor(id: string);
4
+ }
@@ -0,0 +1,6 @@
1
+ export class BaseClient {
2
+ id;
3
+ constructor(id) {
4
+ this.id = id;
5
+ }
6
+ }
@@ -0,0 +1,40 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { Dictionary } from '@crawlee/types';
3
+ import type { MemoryStorageBackend } from '../memory-storage.js';
4
+ import { BaseClient } from './common/base-client.js';
5
+ export interface DatasetBackendOptions {
6
+ id?: string;
7
+ name?: string;
8
+ /**
9
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
10
+ * This allows alias-opened storages to have a cache key that differs from their
11
+ * metadata `name` (which is `undefined` for unnamed storages).
12
+ */
13
+ cacheKey?: string;
14
+ storageBackend: MemoryStorageBackend;
15
+ }
16
+ export declare class DatasetBackend<Data extends Dictionary = Dictionary> extends BaseClient implements storage.DatasetBackend<Data> {
17
+ #private;
18
+ name?: string;
19
+ /**
20
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
21
+ * storages, this is the alias string. Falls back to id.
22
+ */
23
+ cacheKey: string;
24
+ createdAt: Date;
25
+ accessedAt: Date;
26
+ modifiedAt: Date;
27
+ itemCount: number;
28
+ private readonly storageBackend;
29
+ constructor(options: DatasetBackendOptions);
30
+ getMetadata(): Promise<storage.DatasetInfo>;
31
+ drop(): Promise<void>;
32
+ purge(): Promise<void>;
33
+ getData(options?: storage.DatasetBackendListOptions): Promise<storage.PaginatedList<Data>>;
34
+ private getDataPage;
35
+ pushData(items: Data[]): Promise<void>;
36
+ toDatasetInfo(): storage.DatasetInfo;
37
+ private generateLocalEntryName;
38
+ private getStartAndEndIndexes;
39
+ private updateTimestamps;
40
+ }
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { s } from '@sapphire/shapeshift';
3
+ import { BaseClient } from './common/base-client.js';
4
+ /**
5
+ * This is what API returns in the x-apify-pagination-limit
6
+ * header when no limit query parameter is used.
7
+ */
8
+ const LIST_ITEMS_LIMIT = 999_999_999_999;
9
+ /**
10
+ * Number of characters of the dataset item entry names.
11
+ * E.g.: 000000019 - 9 digits
12
+ */
13
+ const LOCAL_ENTRY_NAME_DIGITS = 9;
14
+ export class DatasetBackend extends BaseClient {
15
+ name;
16
+ /**
17
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
18
+ * storages, this is the alias string. Falls back to id.
19
+ */
20
+ cacheKey;
21
+ createdAt = new Date();
22
+ accessedAt = new Date();
23
+ modifiedAt = new Date();
24
+ itemCount = 0;
25
+ #datasetEntries = new Map();
26
+ // kept as TS-private: storage-backend tests read this field at runtime
27
+ storageBackend;
28
+ constructor(options) {
29
+ super(options.id ?? randomUUID());
30
+ this.name = options.name;
31
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
32
+ this.storageBackend = options.storageBackend;
33
+ }
34
+ async getMetadata() {
35
+ this.updateTimestamps(false);
36
+ return this.toDatasetInfo();
37
+ }
38
+ async drop() {
39
+ const storeIndex = this.storageBackend.datasetBackendCache.findIndex((store) => store.id === this.id);
40
+ if (storeIndex !== -1) {
41
+ const [oldBackend] = this.storageBackend.datasetBackendCache.splice(storeIndex, 1);
42
+ oldBackend.itemCount = 0;
43
+ oldBackend.#datasetEntries.clear();
44
+ }
45
+ }
46
+ async purge() {
47
+ this.itemCount = 0;
48
+ this.#datasetEntries.clear();
49
+ this.updateTimestamps(true);
50
+ }
51
+ getData(options = {}) {
52
+ const { desc, limit, offset } = s
53
+ .object({
54
+ desc: s.boolean().optional(),
55
+ limit: s.number().int().optional(),
56
+ offset: s.number().int().optional(),
57
+ })
58
+ .parse(options);
59
+ return this.getDataPage({
60
+ desc,
61
+ offset: offset ?? 0,
62
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
63
+ });
64
+ }
65
+ async getDataPage(options = {}) {
66
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
67
+ const [start, end] = this.getStartAndEndIndexes(desc ? Math.max(this.itemCount - offset - limit, 0) : offset, limit);
68
+ const items = [];
69
+ for (let idx = start; idx < end; idx++) {
70
+ const entryNumber = this.generateLocalEntryName(idx);
71
+ items.push(this.#datasetEntries.get(entryNumber));
72
+ }
73
+ this.updateTimestamps(false);
74
+ return {
75
+ count: items.length,
76
+ desc: desc ?? false,
77
+ items: desc ? items.reverse() : items,
78
+ limit,
79
+ offset,
80
+ total: this.itemCount,
81
+ };
82
+ }
83
+ async pushData(items) {
84
+ for (const entry of items) {
85
+ const idx = this.generateLocalEntryName(++this.itemCount);
86
+ this.#datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
87
+ }
88
+ this.updateTimestamps(true);
89
+ }
90
+ toDatasetInfo() {
91
+ return {
92
+ id: this.id,
93
+ accessedAt: this.accessedAt,
94
+ createdAt: this.createdAt,
95
+ itemCount: this.itemCount,
96
+ modifiedAt: this.modifiedAt,
97
+ name: this.name,
98
+ };
99
+ }
100
+ generateLocalEntryName(idx) {
101
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
102
+ }
103
+ getStartAndEndIndexes(offset, limit = this.itemCount) {
104
+ const start = offset + 1;
105
+ const end = Math.min(offset + limit, this.itemCount) + 1;
106
+ return [start, end];
107
+ }
108
+ updateTimestamps(hasBeenModified) {
109
+ this.accessedAt = new Date();
110
+ if (hasBeenModified) {
111
+ this.modifiedAt = new Date();
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,63 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { MemoryStorageBackend } from '../memory-storage.js';
3
+ import { BaseClient } from './common/base-client.js';
4
+ export interface KeyValueStoreBackendOptions {
5
+ name?: string;
6
+ id?: string;
7
+ /**
8
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
9
+ * This allows alias-opened storages to have a cache key that differs from their
10
+ * metadata `name` (which is `undefined` for unnamed storages).
11
+ */
12
+ cacheKey?: string;
13
+ storageBackend: MemoryStorageBackend;
14
+ }
15
+ export interface InternalKeyRecord {
16
+ key: string;
17
+ value: Buffer;
18
+ contentType?: string;
19
+ extension: string;
20
+ }
21
+ export declare class KeyValueStoreBackend extends BaseClient implements storage.KeyValueStoreBackend {
22
+ #private;
23
+ name?: string;
24
+ /**
25
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
26
+ * storages, this is the alias string. Falls back to id.
27
+ */
28
+ cacheKey: string;
29
+ createdAt: Date;
30
+ accessedAt: Date;
31
+ modifiedAt: Date;
32
+ private readonly storageBackend;
33
+ constructor(options: KeyValueStoreBackendOptions);
34
+ getMetadata(): Promise<storage.KeyValueStoreInfo>;
35
+ drop(): Promise<void>;
36
+ purge(): Promise<void>;
37
+ /**
38
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
39
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
40
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
41
+ * preserve the bare `INPUT` key only.
42
+ */
43
+ purgeExceptInput(): Promise<void>;
44
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
45
+ /**
46
+ * In-memory records are not file-backed, so there is no public file URL to return.
47
+ * Always resolves to `undefined`.
48
+ * @param key The key of the record to generate the public URL for.
49
+ */
50
+ getPublicUrl(key: string): Promise<string | undefined>;
51
+ /**
52
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
53
+ *
54
+ * @param key The queried record key.
55
+ * @returns `true` if the record exists, `false` if it does not.
56
+ */
57
+ recordExists(key: string): Promise<boolean>;
58
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
59
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
60
+ deleteValue(key: string): Promise<void>;
61
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
62
+ private updateTimestamps;
63
+ }
@@ -0,0 +1,204 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { s } from '@sapphire/shapeshift';
3
+ import { isStream, toBuffer } from '../utils.js';
4
+ import { BaseClient } from './common/base-client.js';
5
+ import mime from 'mime-types';
6
+ const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
7
+ /**
8
+ * Key under which a run's input is stored in the default key-value store. Matches Crawlee's default
9
+ * `inputKey` (`CRAWLEE_INPUT_KEY`) and the `INPUT` files `FileSystemStorageBackend` preserves on purge.
10
+ */
11
+ const KEY_VALUE_STORE_INPUT_KEY = 'INPUT';
12
+ export class KeyValueStoreBackend extends BaseClient {
13
+ name;
14
+ /**
15
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
16
+ * storages, this is the alias string. Falls back to id.
17
+ */
18
+ cacheKey;
19
+ createdAt = new Date();
20
+ accessedAt = new Date();
21
+ modifiedAt = new Date();
22
+ #keyValueEntries = new Map();
23
+ // kept as TS-private: storage-backend tests read this field at runtime
24
+ storageBackend;
25
+ constructor(options) {
26
+ super(options.id ?? randomUUID());
27
+ this.name = options.name;
28
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
29
+ this.storageBackend = options.storageBackend;
30
+ }
31
+ async getMetadata() {
32
+ this.updateTimestamps(false);
33
+ return this.toKeyValueStoreInfo();
34
+ }
35
+ async drop() {
36
+ const storeIndex = this.storageBackend.keyValueStoreBackendCache.findIndex((store) => store.id === this.id);
37
+ if (storeIndex !== -1) {
38
+ const [oldBackend] = this.storageBackend.keyValueStoreBackendCache.splice(storeIndex, 1);
39
+ oldBackend.#keyValueEntries.clear();
40
+ }
41
+ }
42
+ async purge() {
43
+ this.#keyValueEntries.clear();
44
+ this.updateTimestamps(true);
45
+ }
46
+ /**
47
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
48
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
49
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
50
+ * preserve the bare `INPUT` key only.
51
+ */
52
+ async purgeExceptInput() {
53
+ for (const key of this.#keyValueEntries.keys()) {
54
+ if (key !== KEY_VALUE_STORE_INPUT_KEY) {
55
+ this.#keyValueEntries.delete(key);
56
+ }
57
+ }
58
+ this.updateTimestamps(true);
59
+ }
60
+ async listKeys(options = {}) {
61
+ const { prefix, exclusiveStartKey, limit } = s
62
+ .object({
63
+ prefix: s.string().optional(),
64
+ exclusiveStartKey: s.string().optional(),
65
+ limit: s.number().int().greaterThan(0).optional(),
66
+ })
67
+ .parse(options);
68
+ const items = [];
69
+ for (const record of this.#keyValueEntries.values()) {
70
+ const size = Buffer.byteLength(record.value);
71
+ items.push({
72
+ key: record.key,
73
+ size,
74
+ contentType: record.contentType ?? 'application/octet-stream',
75
+ });
76
+ }
77
+ // Lexically sort to emulate API.
78
+ items.sort((a, b) => a.key.localeCompare(b.key));
79
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
80
+ if (exclusiveStartKey) {
81
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
82
+ if (keyPos === -1) {
83
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
84
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
85
+ }
86
+ filteredItems = filteredItems.slice(keyPos + 1);
87
+ }
88
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
89
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
90
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
91
+ this.updateTimestamps(false);
92
+ return {
93
+ items: pageItems,
94
+ count: pageItems.length,
95
+ limit: limit ?? pageItems.length,
96
+ exclusiveStartKey,
97
+ isTruncated,
98
+ nextExclusiveStartKey,
99
+ };
100
+ }
101
+ /**
102
+ * In-memory records are not file-backed, so there is no public file URL to return.
103
+ * Always resolves to `undefined`.
104
+ * @param key The key of the record to generate the public URL for.
105
+ */
106
+ async getPublicUrl(key) {
107
+ s.string().parse(key);
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
112
+ *
113
+ * @param key The queried record key.
114
+ * @returns `true` if the record exists, `false` if it does not.
115
+ */
116
+ async recordExists(key) {
117
+ s.string().parse(key);
118
+ return this.#keyValueEntries.has(key);
119
+ }
120
+ async getValue(key) {
121
+ s.string().parse(key);
122
+ const entry = this.#keyValueEntries.get(key);
123
+ if (!entry) {
124
+ return undefined;
125
+ }
126
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
127
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
128
+ const record = {
129
+ key: entry.key,
130
+ value: entry.value,
131
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
132
+ // frontend treats it as "no content type" rather than a bogus value.
133
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
134
+ };
135
+ this.updateTimestamps(false);
136
+ return record;
137
+ }
138
+ async setValue(record) {
139
+ s.object({
140
+ key: s.string().lengthGreaterThan(0),
141
+ value: s.union([
142
+ s.null(),
143
+ s.string(),
144
+ s.number(),
145
+ s.instance(Buffer),
146
+ s.instance(ArrayBuffer),
147
+ s.typedArray(),
148
+ // disabling validation will make shapeshift only check the object given is an actual object, not null, nor array
149
+ s.object({}).setValidationEnabled(false),
150
+ ]),
151
+ contentType: s.string().lengthGreaterThan(0).optional(),
152
+ }).parse(record);
153
+ const { key } = record;
154
+ let { value } = record;
155
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
156
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
157
+ const contentType = record.contentType ?? 'application/octet-stream';
158
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
159
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
160
+ if (isStream(value)) {
161
+ const chunks = [];
162
+ for await (const chunk of value) {
163
+ chunks.push(chunk);
164
+ }
165
+ value = Buffer.concat(chunks);
166
+ }
167
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
168
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
169
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
170
+ const normalizedValue = typeof value === 'string'
171
+ ? Buffer.from(value, 'utf-8')
172
+ : toBuffer(value);
173
+ const normalizedRecord = {
174
+ extension,
175
+ key,
176
+ value: normalizedValue,
177
+ contentType,
178
+ };
179
+ this.#keyValueEntries.set(key, normalizedRecord);
180
+ this.updateTimestamps(true);
181
+ }
182
+ async deleteValue(key) {
183
+ s.string().parse(key);
184
+ if (this.#keyValueEntries.has(key)) {
185
+ this.#keyValueEntries.delete(key);
186
+ this.updateTimestamps(true);
187
+ }
188
+ }
189
+ toKeyValueStoreInfo() {
190
+ return {
191
+ id: this.id,
192
+ name: this.name,
193
+ accessedAt: this.accessedAt,
194
+ createdAt: this.createdAt,
195
+ modifiedAt: this.modifiedAt,
196
+ };
197
+ }
198
+ updateTimestamps(hasBeenModified) {
199
+ this.accessedAt = new Date();
200
+ if (hasBeenModified) {
201
+ this.modifiedAt = new Date();
202
+ }
203
+ }
204
+ }
@@ -0,0 +1,77 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { MemoryStorageBackend } from '../memory-storage.js';
3
+ import { BaseClient } from './common/base-client.js';
4
+ export interface RequestQueueBackendOptions {
5
+ name?: string;
6
+ id?: string;
7
+ /**
8
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
9
+ * This allows alias-opened storages to have a cache key that differs from their
10
+ * metadata `name` (which is `undefined` for unnamed storages).
11
+ */
12
+ cacheKey?: string;
13
+ storageBackend: MemoryStorageBackend;
14
+ }
15
+ export interface InternalRequest {
16
+ id: string;
17
+ orderNo: number | null;
18
+ url: string;
19
+ uniqueKey: string;
20
+ method: storage.RequestSchema['method'];
21
+ retryCount: number;
22
+ json: string;
23
+ }
24
+ export declare class RequestQueueBackend extends BaseClient implements storage.RequestQueueBackend {
25
+ #private;
26
+ name?: string;
27
+ /**
28
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
29
+ * storages, this is the alias string. Falls back to id.
30
+ */
31
+ cacheKey: string;
32
+ createdAt: Date;
33
+ accessedAt: Date;
34
+ modifiedAt: Date;
35
+ handledRequestCount: number;
36
+ pendingRequestCount: number;
37
+ private readonly storageBackend;
38
+ constructor(options: RequestQueueBackendOptions);
39
+ getMetadata(): Promise<storage.RequestQueueInfo>;
40
+ drop(): Promise<void>;
41
+ purge(): Promise<void>;
42
+ private requestKeyIterator;
43
+ /**
44
+ * Scans the queue and returns the pending head — requests that are neither handled nor currently
45
+ * in progress — ordered by `orderNo`, deduplicated.
46
+ *
47
+ * When `detectInProgressRequests` is set, the result also carries an `hasInProgressRequests` flag
48
+ * telling whether any unhandled-but-in-progress request was skipped along the way. It lets
49
+ * {@link isFinished} distinguish "no work left at all" from "work remains, but it is currently being
50
+ * processed". Without it, a consumer with concurrency could consider the queue finished and shut the
51
+ * crawler down while it is still handling the last requests.
52
+ *
53
+ * Computing the flag is expensive: because an in-progress request may sit anywhere in the queue, it
54
+ * forces a scan of every pending entry even when only `limit` items are wanted. Callers that only
55
+ * need the head (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as
56
+ * soon as the page is filled, keeping those calls O(head) instead of O(N).
57
+ */
58
+ private listPendingHead;
59
+ fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined>;
60
+ addBatchOfRequests(requests: storage.RequestSchema[], options?: storage.RequestQueueOperationOptions): Promise<storage.BatchAddRequestsResult>;
61
+ getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined>;
62
+ markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined>;
63
+ reclaimRequest(request: storage.UpdateRequestSchema, options?: storage.RequestQueueOperationOptions): Promise<storage.QueueOperationInfo | undefined>;
64
+ isEmpty(): Promise<boolean>;
65
+ isFinished(): Promise<boolean>;
66
+ /**
67
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
68
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
69
+ * nothing is marked in progress.
70
+ */
71
+ listItems(): Promise<storage.UpdateRequestSchema[]>;
72
+ toRequestQueueInfo(): storage.RequestQueueInfo;
73
+ private updateTimestamps;
74
+ private jsonToRequest;
75
+ private createInternalRequest;
76
+ private calculateOrderNo;
77
+ }