@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,201 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { isStream, toBuffer } from '../utils.js';
5
+ import { BaseClient } from './common/base-client.js';
6
+ import mime from 'mime-types';
7
+ const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
8
+ const keySchema = z.string();
9
+ const inputRecordSchema = z.object({
10
+ key: z.string().min(1),
11
+ value: z.union([
12
+ z.null(),
13
+ z.string(),
14
+ z.number(),
15
+ z.instanceof(Buffer),
16
+ z.instanceof(ArrayBuffer),
17
+ schemas.typedArray,
18
+ // only checks the value is an actual object, not null, nor array
19
+ schemas.plainObject,
20
+ ]),
21
+ contentType: z.string().min(1).optional(),
22
+ });
23
+ /**
24
+ * Key under which a run's input is stored in the default key-value store. Matches Crawlee's default
25
+ * `inputKey` (`CRAWLEE_INPUT_KEY`) and the `INPUT` files `FileSystemStorageBackend` preserves on purge.
26
+ */
27
+ const KEY_VALUE_STORE_INPUT_KEY = 'INPUT';
28
+ export class KeyValueStoreBackend extends BaseClient {
29
+ name;
30
+ /**
31
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
32
+ * storages, this is the alias string. Falls back to id.
33
+ */
34
+ cacheKey;
35
+ createdAt = new Date();
36
+ accessedAt = new Date();
37
+ modifiedAt = new Date();
38
+ #keyValueEntries = new Map();
39
+ // kept as TS-private: storage-backend tests read this field at runtime
40
+ storageBackend;
41
+ constructor(options) {
42
+ super(options.id ?? randomUUID());
43
+ this.name = options.name;
44
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
45
+ this.storageBackend = options.storageBackend;
46
+ }
47
+ async getMetadata() {
48
+ this.updateTimestamps(false);
49
+ return this.toKeyValueStoreInfo();
50
+ }
51
+ async drop() {
52
+ const storeIndex = this.storageBackend.keyValueStoreBackendCache.findIndex((store) => store.id === this.id);
53
+ if (storeIndex !== -1) {
54
+ const [oldBackend] = this.storageBackend.keyValueStoreBackendCache.splice(storeIndex, 1);
55
+ oldBackend.#keyValueEntries.clear();
56
+ }
57
+ }
58
+ async purge() {
59
+ this.#keyValueEntries.clear();
60
+ this.updateTimestamps(true);
61
+ }
62
+ /**
63
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
64
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
65
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
66
+ * preserve the bare `INPUT` key only.
67
+ */
68
+ async purgeExceptInput() {
69
+ for (const key of this.#keyValueEntries.keys()) {
70
+ if (key !== KEY_VALUE_STORE_INPUT_KEY) {
71
+ this.#keyValueEntries.delete(key);
72
+ }
73
+ }
74
+ this.updateTimestamps(true);
75
+ }
76
+ async listKeys(options = {}) {
77
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
78
+ const items = [];
79
+ for (const record of this.#keyValueEntries.values()) {
80
+ const size = Buffer.byteLength(record.value);
81
+ items.push({
82
+ key: record.key,
83
+ size,
84
+ contentType: record.contentType ?? 'application/octet-stream',
85
+ });
86
+ }
87
+ // Lexically sort to emulate API.
88
+ items.sort((a, b) => a.key.localeCompare(b.key));
89
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
90
+ if (exclusiveStartKey) {
91
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
92
+ if (keyPos === -1) {
93
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
94
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
95
+ }
96
+ filteredItems = filteredItems.slice(keyPos + 1);
97
+ }
98
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
99
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
100
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
101
+ this.updateTimestamps(false);
102
+ return {
103
+ items: pageItems,
104
+ count: pageItems.length,
105
+ limit: limit ?? pageItems.length,
106
+ exclusiveStartKey,
107
+ isTruncated,
108
+ nextExclusiveStartKey,
109
+ };
110
+ }
111
+ /**
112
+ * In-memory records are not file-backed, so there is no public file URL to return.
113
+ * Always resolves to `undefined`.
114
+ * @param key The key of the record to generate the public URL for.
115
+ */
116
+ async getPublicUrl(key) {
117
+ parseArgument(key, keySchema);
118
+ return undefined;
119
+ }
120
+ /**
121
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
122
+ *
123
+ * @param key The queried record key.
124
+ * @returns `true` if the record exists, `false` if it does not.
125
+ */
126
+ async recordExists(key) {
127
+ parseArgument(key, keySchema);
128
+ return this.#keyValueEntries.has(key);
129
+ }
130
+ async getValue(key) {
131
+ parseArgument(key, keySchema);
132
+ const entry = this.#keyValueEntries.get(key);
133
+ if (!entry) {
134
+ return undefined;
135
+ }
136
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
137
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
138
+ const record = {
139
+ key: entry.key,
140
+ value: entry.value,
141
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
142
+ // frontend treats it as "no content type" rather than a bogus value.
143
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
144
+ };
145
+ this.updateTimestamps(false);
146
+ return record;
147
+ }
148
+ async setValue(record) {
149
+ parseArgument(record, inputRecordSchema);
150
+ const { key } = record;
151
+ let { value } = record;
152
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
153
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
154
+ const contentType = record.contentType ?? 'application/octet-stream';
155
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
156
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
157
+ if (isStream(value)) {
158
+ const chunks = [];
159
+ for await (const chunk of value) {
160
+ chunks.push(chunk);
161
+ }
162
+ value = Buffer.concat(chunks);
163
+ }
164
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
165
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
166
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
167
+ const normalizedValue = typeof value === 'string'
168
+ ? Buffer.from(value, 'utf-8')
169
+ : toBuffer(value);
170
+ const normalizedRecord = {
171
+ extension,
172
+ key,
173
+ value: normalizedValue,
174
+ contentType,
175
+ };
176
+ this.#keyValueEntries.set(key, normalizedRecord);
177
+ this.updateTimestamps(true);
178
+ }
179
+ async deleteValue(key) {
180
+ parseArgument(key, keySchema);
181
+ if (this.#keyValueEntries.has(key)) {
182
+ this.#keyValueEntries.delete(key);
183
+ this.updateTimestamps(true);
184
+ }
185
+ }
186
+ toKeyValueStoreInfo() {
187
+ return {
188
+ id: this.id,
189
+ name: this.name,
190
+ accessedAt: this.accessedAt,
191
+ createdAt: this.createdAt,
192
+ modifiedAt: this.modifiedAt,
193
+ };
194
+ }
195
+ updateTimestamps(hasBeenModified) {
196
+ this.accessedAt = new Date();
197
+ if (hasBeenModified) {
198
+ this.modifiedAt = new Date();
199
+ }
200
+ }
201
+ }
@@ -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
+ }
@@ -0,0 +1,409 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { AsyncQueue } from '@sapphire/async-queue';
4
+ import { z } from 'zod';
5
+ import { purgeNullsFromObject, uniqueKeyToRequestId } from '../utils.js';
6
+ import { BaseClient } from './common/base-client.js';
7
+ const uniqueKeySchema = z.string();
8
+ export class RequestQueueBackend extends BaseClient {
9
+ name;
10
+ /**
11
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
12
+ * storages, this is the alias string. Falls back to id.
13
+ */
14
+ cacheKey;
15
+ createdAt = new Date();
16
+ accessedAt = new Date();
17
+ modifiedAt = new Date();
18
+ handledRequestCount = 0;
19
+ pendingRequestCount = 0;
20
+ /**
21
+ * Serializes every operation that reads-then-writes this backend's shared queue state — the
22
+ * `requests` map, the `forefrontRequestIds` array, the `inProgressRequestIds` set and the request
23
+ * counts. Those mutations span `await` points, so without this mutex a concurrent operation could
24
+ * interleave and corrupt them (e.g. a head scan pruning `forefrontRequestIds` while
25
+ * `addBatchOfRequests` pushes to it). Held by every mutating method as well as by `isEmpty`/
26
+ * `isFinished`, whose head scan also prunes `forefrontRequestIds`.
27
+ */
28
+ #queueStateMutex = new AsyncQueue();
29
+ #forefrontRequestIds = [];
30
+ /**
31
+ * IDs of requests currently fetched but not yet handled or reclaimed. A request in this set is
32
+ * "in progress" and will not be handed out again by {@link fetchNextRequest}.
33
+ *
34
+ * Unlike the file-system / platform clients, the in-memory queue lives entirely within a single
35
+ * process and is never shared with another consumer, so there is no need for an expiring,
36
+ * cross-process-visible lock — tracking in-progress requests in this set is enough.
37
+ */
38
+ #inProgressRequestIds = new Set();
39
+ #requests = new Map();
40
+ // kept as TS-private: storage-backend tests read this field at runtime
41
+ storageBackend;
42
+ constructor(options) {
43
+ super(options.id ?? randomUUID());
44
+ this.name = options.name;
45
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
46
+ this.storageBackend = options.storageBackend;
47
+ }
48
+ async getMetadata() {
49
+ this.updateTimestamps(false);
50
+ return this.toRequestQueueInfo();
51
+ }
52
+ async drop() {
53
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
54
+ // operation cannot observe half-cleared state — e.g. a forefront id whose request has already been
55
+ // removed, which `listPendingHead` would then dereference as `undefined`.
56
+ await this.#queueStateMutex.wait();
57
+ try {
58
+ const storeIndex = this.storageBackend.requestQueueBackendCache.findIndex((queue) => queue.id === this.id);
59
+ if (storeIndex !== -1) {
60
+ const [oldBackend] = this.storageBackend.requestQueueBackendCache.splice(storeIndex, 1);
61
+ oldBackend.pendingRequestCount = 0;
62
+ // Clear all in-memory state, consistent with `purge`. Clearing `requests` alone would
63
+ // leave dangling ids in `forefrontRequestIds`/`inProgressRequestIds`, which a later head
64
+ // scan would resolve to a missing request and dereference.
65
+ oldBackend.#requests.clear();
66
+ oldBackend.#forefrontRequestIds = [];
67
+ oldBackend.#inProgressRequestIds.clear();
68
+ }
69
+ }
70
+ finally {
71
+ this.#queueStateMutex.shift();
72
+ }
73
+ }
74
+ async purge() {
75
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
76
+ // operation cannot observe or repopulate half-cleared state across the `await` below.
77
+ await this.#queueStateMutex.wait();
78
+ try {
79
+ // Clear all in-memory state
80
+ this.#requests.clear();
81
+ this.#forefrontRequestIds = [];
82
+ this.#inProgressRequestIds.clear();
83
+ this.handledRequestCount = 0;
84
+ this.pendingRequestCount = 0;
85
+ this.updateTimestamps(true);
86
+ }
87
+ finally {
88
+ this.#queueStateMutex.shift();
89
+ }
90
+ }
91
+ *requestKeyIterator() {
92
+ for (let i = this.#forefrontRequestIds.length - 1; i >= 0; i--) {
93
+ yield this.#forefrontRequestIds[i];
94
+ }
95
+ for (const key of this.#requests.keys()) {
96
+ yield key;
97
+ }
98
+ }
99
+ /**
100
+ * Scans the queue and returns the pending head — requests that are neither handled nor currently
101
+ * in progress — ordered by `orderNo`, deduplicated.
102
+ *
103
+ * When `detectInProgressRequests` is set, the result also carries an `hasInProgressRequests` flag
104
+ * telling whether any unhandled-but-in-progress request was skipped along the way. It lets
105
+ * {@link isFinished} distinguish "no work left at all" from "work remains, but it is currently being
106
+ * processed". Without it, a consumer with concurrency could consider the queue finished and shut the
107
+ * crawler down while it is still handling the last requests.
108
+ *
109
+ * Computing the flag is expensive: because an in-progress request may sit anywhere in the queue, it
110
+ * forces a scan of every pending entry even when only `limit` items are wanted. Callers that only
111
+ * need the head (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as
112
+ * soon as the page is filled, keeping those calls O(head) instead of O(N).
113
+ */
114
+ async listPendingHead(limit, detectInProgressRequests = false) {
115
+ const items = [];
116
+ let hasInProgressRequests = false;
117
+ // Tracks processed request IDs to avoid duplicates (request in both `forefrontRequestIds` and `requests`).
118
+ const seenRequestIds = new Set();
119
+ // Tracks handled request IDs from `forefrontRequestIds` to be removed.
120
+ const handledForefrontIds = new Set();
121
+ for (const requestId of this.requestKeyIterator()) {
122
+ // Once the requested page is filled we can stop — unless the caller asked us to detect
123
+ // in-progress requests and we have not yet seen one, in which case we must keep scanning.
124
+ if (items.length >= limit && (!detectInProgressRequests || hasInProgressRequests)) {
125
+ break;
126
+ }
127
+ if (seenRequestIds.has(requestId)) {
128
+ continue;
129
+ }
130
+ seenRequestIds.add(requestId);
131
+ const request = this.#requests.get(requestId);
132
+ // Permanently-handled requests (`orderNo === null`) are in a terminal state and can be skipped.
133
+ if (request.orderNo === null) {
134
+ if (this.#forefrontRequestIds.includes(requestId)) {
135
+ handledForefrontIds.add(requestId);
136
+ }
137
+ continue;
138
+ }
139
+ // In progress (fetched but not yet handled or reclaimed) — skip it, but remember that the
140
+ // queue is not truly empty.
141
+ if (this.#inProgressRequestIds.has(requestId)) {
142
+ hasInProgressRequests = true;
143
+ continue;
144
+ }
145
+ if (items.length < limit) {
146
+ items.push(request);
147
+ }
148
+ }
149
+ this.#forefrontRequestIds = this.#forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
150
+ return {
151
+ items: items.sort((a, b) => a.orderNo - b.orderNo),
152
+ hasInProgressRequests: detectInProgressRequests ? hasInProgressRequests : undefined,
153
+ };
154
+ }
155
+ async fetchNextRequest() {
156
+ this.updateTimestamps(false);
157
+ await this.#queueStateMutex.wait();
158
+ try {
159
+ const { items: [head], } = await this.listPendingHead(1);
160
+ if (!head) {
161
+ return undefined;
162
+ }
163
+ // Mark the request as in progress so it is not handed out again until it is handled or
164
+ // reclaimed. The request keeps its `orderNo` (and thus its forefront / normal ordering).
165
+ this.#inProgressRequestIds.add(head.id);
166
+ return this.jsonToRequest(head.json) ?? undefined;
167
+ }
168
+ finally {
169
+ this.#queueStateMutex.shift();
170
+ }
171
+ }
172
+ async addBatchOfRequests(requests, options = {}) {
173
+ parseArgument(requests, schemas.storageRequestBatch);
174
+ parseArgument(options, schemas.requestQueueOperationOptions);
175
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
176
+ // shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
177
+ // concurrent operation interleaving at one of the `await` points below.
178
+ await this.#queueStateMutex.wait();
179
+ try {
180
+ const result = {
181
+ processedRequests: [],
182
+ unprocessedRequests: [],
183
+ };
184
+ for (const model of requests) {
185
+ const requestModel = this.createInternalRequest(model, options.forefront);
186
+ const existingRequestWithId = this.#requests.get(requestModel.id);
187
+ if (existingRequestWithId) {
188
+ result.processedRequests.push({
189
+ requestId: existingRequestWithId.id,
190
+ uniqueKey: existingRequestWithId.uniqueKey,
191
+ wasAlreadyHandled: existingRequestWithId.orderNo === null,
192
+ wasAlreadyPresent: true,
193
+ });
194
+ continue;
195
+ }
196
+ this.#requests.set(requestModel.id, requestModel);
197
+ if (requestModel.orderNo) {
198
+ this.pendingRequestCount += 1;
199
+ }
200
+ else {
201
+ this.handledRequestCount += 1;
202
+ }
203
+ if (options.forefront) {
204
+ this.#forefrontRequestIds.push(requestModel.id);
205
+ }
206
+ result.processedRequests.push({
207
+ requestId: requestModel.id,
208
+ uniqueKey: requestModel.uniqueKey,
209
+ // We return wasAlreadyHandled: false even though the request may
210
+ // have been added as handled, because that's how API behaves.
211
+ wasAlreadyHandled: false,
212
+ wasAlreadyPresent: false,
213
+ });
214
+ }
215
+ this.updateTimestamps(true);
216
+ return result;
217
+ }
218
+ finally {
219
+ this.#queueStateMutex.shift();
220
+ }
221
+ }
222
+ async getRequest(uniqueKey) {
223
+ parseArgument(uniqueKey, uniqueKeySchema);
224
+ this.updateTimestamps(false);
225
+ const id = uniqueKeyToRequestId(uniqueKey);
226
+ const json = this.#requests.get(id)?.json;
227
+ return this.jsonToRequest(json);
228
+ }
229
+ async markRequestAsHandled(request) {
230
+ parseArgument(request, schemas.storageRequest);
231
+ this.updateTimestamps(false);
232
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
233
+ // `requests` map, `inProgressRequestIds` set and request counts stay consistent across the
234
+ // `await` points below.
235
+ await this.#queueStateMutex.wait();
236
+ try {
237
+ const id = uniqueKeyToRequestId(request.uniqueKey);
238
+ const existingRequest = this.#requests.get(id);
239
+ // The request must exist to be marked as handled. We intentionally do NOT require it to still
240
+ // be in progress: marking an already-released request handled must still succeed, otherwise
241
+ // the request could be handed out again and the queue would never finish.
242
+ if (!existingRequest) {
243
+ return undefined;
244
+ }
245
+ // A handled request has `orderNo === null`. Marking it again is an idempotent no-op.
246
+ const wasAlreadyHandled = existingRequest.orderNo === null;
247
+ const handledAt = request.handledAt ?? new Date().toISOString();
248
+ const requestModel = this.createInternalRequest({ ...request, handledAt }, false);
249
+ this.#requests.set(id, requestModel);
250
+ // The request is no longer in progress for this client.
251
+ this.#inProgressRequestIds.delete(id);
252
+ if (!wasAlreadyHandled) {
253
+ this.pendingRequestCount -= 1;
254
+ this.handledRequestCount += 1;
255
+ }
256
+ this.updateTimestamps(true);
257
+ return {
258
+ requestId: id,
259
+ wasAlreadyHandled,
260
+ wasAlreadyPresent: true,
261
+ };
262
+ }
263
+ finally {
264
+ this.#queueStateMutex.shift();
265
+ }
266
+ }
267
+ async reclaimRequest(request, options = {}) {
268
+ parseArgument(request, schemas.storageRequest);
269
+ parseArgument(options, schemas.requestQueueOperationOptions);
270
+ this.updateTimestamps(false);
271
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
272
+ // `requests` map, `forefrontRequestIds` array and `inProgressRequestIds` set stay consistent
273
+ // across the `await` points below.
274
+ await this.#queueStateMutex.wait();
275
+ try {
276
+ const id = uniqueKeyToRequestId(request.uniqueKey);
277
+ const existingRequest = this.#requests.get(id);
278
+ // The request must exist and not already be handled to be reclaimed. As with
279
+ // `markRequestAsHandled`, we do NOT require it to still be in progress — returning an
280
+ // already-released request to the queue (e.g. to honor a `forefront` reorder) must still
281
+ // work, rather than have the reclaim silently dropped.
282
+ if (!existingRequest || existingRequest.orderNo === null) {
283
+ return undefined;
284
+ }
285
+ // Reclaiming resets the `orderNo` to a fresh timestamp, restoring the request to the queue
286
+ // (at the front if `forefront`).
287
+ const requestModel = this.createInternalRequest(request, options.forefront);
288
+ this.#requests.set(id, requestModel);
289
+ // The request is no longer in progress for this client.
290
+ this.#inProgressRequestIds.delete(id);
291
+ if (options.forefront) {
292
+ this.#forefrontRequestIds.push(id);
293
+ }
294
+ this.updateTimestamps(true);
295
+ return {
296
+ requestId: id,
297
+ wasAlreadyHandled: false,
298
+ wasAlreadyPresent: true,
299
+ };
300
+ }
301
+ finally {
302
+ this.#queueStateMutex.shift();
303
+ }
304
+ }
305
+ async isEmpty() {
306
+ this.updateTimestamps(false);
307
+ // "Empty" means there is nothing left to fetch right now — i.e. the next `fetchNextRequest`
308
+ // would return `null`. Requests that are currently in progress are intentionally NOT counted
309
+ // here: they are not fetchable, so the queue is empty from a consumer's point of view. Whether
310
+ // those in-progress requests mean crawling is not yet done is a separate question, answered by
311
+ // `isFinished`.
312
+ //
313
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
314
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
315
+ await this.#queueStateMutex.wait();
316
+ try {
317
+ const { items } = await this.listPendingHead(1);
318
+ return items.length === 0;
319
+ }
320
+ finally {
321
+ this.#queueStateMutex.shift();
322
+ }
323
+ }
324
+ async isFinished() {
325
+ this.updateTimestamps(false);
326
+ // The queue is finished only when there is nothing left to fetch AND nothing currently in
327
+ // progress. Counting in-progress requests is what allows a crawler with concurrency to keep
328
+ // waiting while it still holds the last requests, instead of finishing prematurely.
329
+ //
330
+ // Detecting in-progress requests requires a full scan, hence the `detectInProgressRequests`
331
+ // flag — unlike `fetchNextRequest`/`isEmpty`, which only need the head and can stop early.
332
+ //
333
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
334
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
335
+ await this.#queueStateMutex.wait();
336
+ try {
337
+ const { items, hasInProgressRequests } = await this.listPendingHead(1, true);
338
+ return items.length === 0 && !hasInProgressRequests;
339
+ }
340
+ finally {
341
+ this.#queueStateMutex.shift();
342
+ }
343
+ }
344
+ /**
345
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
346
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
347
+ * nothing is marked in progress.
348
+ */
349
+ async listItems() {
350
+ this.updateTimestamps(false);
351
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state
352
+ // mutex to avoid racing a concurrent mutator at its `await` points.
353
+ await this.#queueStateMutex.wait();
354
+ try {
355
+ const { items } = await this.listPendingHead(Number.POSITIVE_INFINITY);
356
+ return items.map((request) => this.jsonToRequest(request.json));
357
+ }
358
+ finally {
359
+ this.#queueStateMutex.shift();
360
+ }
361
+ }
362
+ toRequestQueueInfo() {
363
+ return {
364
+ accessedAt: this.accessedAt,
365
+ createdAt: this.createdAt,
366
+ handledRequestCount: this.handledRequestCount,
367
+ id: this.id,
368
+ modifiedAt: this.modifiedAt,
369
+ name: this.name,
370
+ pendingRequestCount: this.pendingRequestCount,
371
+ totalRequestCount: this.#requests.size,
372
+ };
373
+ }
374
+ updateTimestamps(hasBeenModified) {
375
+ this.accessedAt = new Date();
376
+ if (hasBeenModified) {
377
+ this.modifiedAt = new Date();
378
+ }
379
+ }
380
+ jsonToRequest(requestJson) {
381
+ if (!requestJson)
382
+ return undefined;
383
+ const request = JSON.parse(requestJson);
384
+ return purgeNullsFromObject(request);
385
+ }
386
+ createInternalRequest(request, forefront) {
387
+ const orderNo = this.calculateOrderNo(request, forefront);
388
+ const id = uniqueKeyToRequestId(request.uniqueKey);
389
+ if (request.id && request.id !== id) {
390
+ throw new Error('Request ID does not match its uniqueKey.');
391
+ }
392
+ const json = JSON.stringify({ ...request, id });
393
+ return {
394
+ id,
395
+ json,
396
+ method: request.method,
397
+ orderNo,
398
+ retryCount: request.retryCount ?? 0,
399
+ uniqueKey: request.uniqueKey,
400
+ url: request.url,
401
+ };
402
+ }
403
+ calculateOrderNo(request, forefront) {
404
+ if (request.handledAt)
405
+ return null;
406
+ const timestamp = Date.now();
407
+ return forefront ? -timestamp : timestamp;
408
+ }
409
+ }