@crawlee/core 4.0.0-beta.14 → 4.0.0-beta.140

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