@crawlee/core 4.0.0-beta.15 → 4.0.0-beta.150

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 +73 -177
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +364 -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 +98 -0
  13. package/autoscaling/load_signal.js +103 -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 -64
  43. package/crawlers/statistics.js +354 -165
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +61 -154
  47. package/enqueue_links/enqueue_links.js +40 -232
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +55 -28
  51. package/enqueue_links/shared.js +116 -69
  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 +77 -1
  67. package/log.js +104 -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 +39 -89
  108. package/session_pool/session.js +102 -159
  109. package/session_pool/session_pool.d.ts +67 -91
  110. package/session_pool/session_pool.js +196 -187
  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 +284 -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 +444 -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 +53 -115
  124. package/storages/request_list.js +194 -167
  125. package/storages/request_loader.d.ts +133 -0
  126. package/storages/request_loader.js +36 -0
  127. package/storages/request_manager.d.ts +109 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +55 -23
  130. package/storages/request_manager_tandem.js +139 -57
  131. package/storages/request_queue.d.ts +286 -48
  132. package/storages/request_queue.js +757 -218
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +43 -91
  134. package/storages/sitemap_request_loader.js +439 -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 +222 -0
  140. package/storages/throttling_request_manager.js +780 -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,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
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
3
+ * Storage names and record keys are used as filesystem path components, so a value containing `..`
4
+ * or an absolute path could otherwise escape the intended directory.
5
+ */
6
+ export declare function resolveWithinDirectory(baseDirectory: string, segment: string): string;
7
+ /**
8
+ * Removes all properties with a null value
9
+ * from the provided object.
10
+ */
11
+ export declare function purgeNullsFromObject<T>(object: T): T;
12
+ /**
13
+ * Creates a standard request ID (same as Platform).
14
+ */
15
+ export declare function uniqueKeyToRequestId(uniqueKey: string): string;
16
+ export { isBuffer, isStream, toBuffer } from '../byte_utils.js';
@@ -0,0 +1,41 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { resolve, sep } from 'node:path';
3
+ import { REQUEST_ID_LENGTH } from './consts.js';
4
+ /**
5
+ * Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
6
+ * Storage names and record keys are used as filesystem path components, so a value containing `..`
7
+ * or an absolute path could otherwise escape the intended directory.
8
+ */
9
+ export function resolveWithinDirectory(baseDirectory, segment) {
10
+ const base = resolve(baseDirectory);
11
+ const resolved = resolve(base, segment);
12
+ if (resolved !== base && !resolved.startsWith(`${base}${sep}`)) {
13
+ throw new Error(`"${segment}" is not allowed because it would resolve outside of the storage directory. ` +
14
+ `Storage names and record keys must not contain path traversal segments ("..") or absolute paths.`);
15
+ }
16
+ return resolved;
17
+ }
18
+ /**
19
+ * Removes all properties with a null value
20
+ * from the provided object.
21
+ */
22
+ export function purgeNullsFromObject(object) {
23
+ if (object && typeof object === 'object' && !Array.isArray(object)) {
24
+ for (const [key, value] of Object.entries(object)) {
25
+ if (value === null)
26
+ Reflect.deleteProperty(object, key);
27
+ }
28
+ }
29
+ return object;
30
+ }
31
+ /**
32
+ * Creates a standard request ID (same as Platform).
33
+ */
34
+ export function uniqueKeyToRequestId(uniqueKey) {
35
+ const str = createHash('sha256')
36
+ .update(uniqueKey)
37
+ .digest('base64')
38
+ .replace(/(\+|\/|=)/g, '');
39
+ return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;
40
+ }
41
+ export { isBuffer, isStream, toBuffer } from '../byte_utils.js';
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Captures the "inject-or-default" ownership pattern for a crawler's stateful collaborators (session pool, browser
3
+ * pool, the crawler-opened request queue, ...). A collaborator is either **injected** by the user (borrowed — the
4
+ * crawler never drives its lifecycle) or **built by the crawler** as a default (owned — the crawler sequences its
5
+ * lifecycle). Owned-only lifecycle hooks are gated through a single {@link OwnedOrInjected.ifOwned|`ifOwned()`}.
6
+ *
7
+ * This is the deliberate complement to the {@link ServiceLocator}: ambient infrastructure (config/events/storage/
8
+ * logger) stays in the locator, while crawler-scoped stateful collaborators the crawler sequences go through this.
9
+ *
10
+ * @internal
11
+ */
12
+ export declare class OwnedOrInjected<Injected, Owned extends Injected = Injected> {
13
+ #private;
14
+ private constructor();
15
+ /**
16
+ * Resolves a collaborator from an optionally-injected instance. `Injected` is the public/borrowed type exposed via
17
+ * {@link OwnedOrInjected.value|`value`}; `Owned` is the concrete type the crawler builds (a subtype with extra
18
+ * lifecycle methods), which {@link OwnedOrInjected.set|`set()`} and {@link OwnedOrInjected.ifOwned|`ifOwned()`}
19
+ * deal in — so owned-only lifecycle hooks are statically typed with no casts.
20
+ *
21
+ * - `injected` provided → borrowed (present, not owned).
22
+ * - `injected` omitted → owned; `buildDefault` fills the slot eagerly if given, otherwise it stays empty until a
23
+ * later {@link OwnedOrInjected.set|`set()`} (the lazy case, e.g. a request queue opened on first use).
24
+ */
25
+ static resolve<Injected, Owned extends Injected = Injected>(injected?: Injected, buildDefault?: () => Owned): OwnedOrInjected<Injected, Owned>;
26
+ /**
27
+ * Whether the crawler owns the instance and is therefore responsible for its lifecycle. `true` only for
28
+ * crawler-built defaults, `false` for user-injected instances.
29
+ */
30
+ get isOwned(): boolean;
31
+ /**
32
+ * Whether a value is currently available. `false` for an owned slot whose default hasn't been built yet
33
+ * (e.g. a lazily-opened request queue before its first use).
34
+ */
35
+ get isPresent(): boolean;
36
+ /**
37
+ * The resolved instance, typed as the public `Injected` type. Throws if the value is not present yet — callers that
38
+ * expect a lazily-filled owned slot should read {@link OwnedOrInjected.maybeValue|`maybeValue`} instead.
39
+ */
40
+ get value(): Injected;
41
+ /**
42
+ * The resolved instance, or `undefined` when a lazily-filled owned slot hasn't been built yet. The non-throwing
43
+ * counterpart to {@link OwnedOrInjected.value|`value`} — pairs naturally with `?? fallback` so callers can read
44
+ * a possibly-empty slot without the `isPresent ? value : …` dance.
45
+ */
46
+ get maybeValue(): Injected | undefined;
47
+ /**
48
+ * Fills the (owned) slot with the crawler-built default, returning it for convenience. Only valid on an owned,
49
+ * not-yet-filled slot: borrowed instances are never replaced and an owned slot is filled exactly once (re-setting
50
+ * would silently orphan the previous instance's lifecycle).
51
+ */
52
+ set(value: Owned): Owned;
53
+ /**
54
+ * Runs an owned-only lifecycle hook, invoked (with the value typed as the concrete `Owned`) only when the crawler
55
+ * owns a present instance — a no-op for a borrowed instance or an owned-but-not-yet-built slot.
56
+ */
57
+ ifOwned<R>(fn: (value: Owned) => R | Promise<R>): Promise<R | undefined>;
58
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Captures the "inject-or-default" ownership pattern for a crawler's stateful collaborators (session pool, browser
3
+ * pool, the crawler-opened request queue, ...). A collaborator is either **injected** by the user (borrowed — the
4
+ * crawler never drives its lifecycle) or **built by the crawler** as a default (owned — the crawler sequences its
5
+ * lifecycle). Owned-only lifecycle hooks are gated through a single {@link OwnedOrInjected.ifOwned|`ifOwned()`}.
6
+ *
7
+ * This is the deliberate complement to the {@link ServiceLocator}: ambient infrastructure (config/events/storage/
8
+ * logger) stays in the locator, while crawler-scoped stateful collaborators the crawler sequences go through this.
9
+ *
10
+ * @internal
11
+ */
12
+ export class OwnedOrInjected {
13
+ #value;
14
+ #owned;
15
+ #present;
16
+ constructor(value, owned, present) {
17
+ this.#value = value;
18
+ this.#owned = owned;
19
+ this.#present = present;
20
+ }
21
+ /**
22
+ * Resolves a collaborator from an optionally-injected instance. `Injected` is the public/borrowed type exposed via
23
+ * {@link OwnedOrInjected.value|`value`}; `Owned` is the concrete type the crawler builds (a subtype with extra
24
+ * lifecycle methods), which {@link OwnedOrInjected.set|`set()`} and {@link OwnedOrInjected.ifOwned|`ifOwned()`}
25
+ * deal in — so owned-only lifecycle hooks are statically typed with no casts.
26
+ *
27
+ * - `injected` provided → borrowed (present, not owned).
28
+ * - `injected` omitted → owned; `buildDefault` fills the slot eagerly if given, otherwise it stays empty until a
29
+ * later {@link OwnedOrInjected.set|`set()`} (the lazy case, e.g. a request queue opened on first use).
30
+ */
31
+ static resolve(injected, buildDefault) {
32
+ if (injected !== undefined) {
33
+ return new OwnedOrInjected(injected, false, true);
34
+ }
35
+ if (buildDefault !== undefined) {
36
+ return new OwnedOrInjected(buildDefault(), true, true);
37
+ }
38
+ return new OwnedOrInjected(undefined, true, false);
39
+ }
40
+ /**
41
+ * Whether the crawler owns the instance and is therefore responsible for its lifecycle. `true` only for
42
+ * crawler-built defaults, `false` for user-injected instances.
43
+ */
44
+ get isOwned() {
45
+ return this.#owned;
46
+ }
47
+ /**
48
+ * Whether a value is currently available. `false` for an owned slot whose default hasn't been built yet
49
+ * (e.g. a lazily-opened request queue before its first use).
50
+ */
51
+ get isPresent() {
52
+ return this.#present;
53
+ }
54
+ /**
55
+ * The resolved instance, typed as the public `Injected` type. Throws if the value is not present yet — callers that
56
+ * expect a lazily-filled owned slot should read {@link OwnedOrInjected.maybeValue|`maybeValue`} instead.
57
+ */
58
+ get value() {
59
+ if (!this.#present) {
60
+ throw new Error('OwnedOrInjected value is not initialized yet');
61
+ }
62
+ return this.#value;
63
+ }
64
+ /**
65
+ * The resolved instance, or `undefined` when a lazily-filled owned slot hasn't been built yet. The non-throwing
66
+ * counterpart to {@link OwnedOrInjected.value|`value`} — pairs naturally with `?? fallback` so callers can read
67
+ * a possibly-empty slot without the `isPresent ? value : …` dance.
68
+ */
69
+ get maybeValue() {
70
+ return this.#present ? this.#value : undefined;
71
+ }
72
+ /**
73
+ * Fills the (owned) slot with the crawler-built default, returning it for convenience. Only valid on an owned,
74
+ * not-yet-filled slot: borrowed instances are never replaced and an owned slot is filled exactly once (re-setting
75
+ * would silently orphan the previous instance's lifecycle).
76
+ */
77
+ set(value) {
78
+ if (!this.#owned) {
79
+ throw new Error('Cannot set() a borrowed OwnedOrInjected value');
80
+ }
81
+ if (this.#present) {
82
+ throw new Error('OwnedOrInjected value is already initialized');
83
+ }
84
+ this.#value = value;
85
+ this.#present = true;
86
+ return value;
87
+ }
88
+ /**
89
+ * Runs an owned-only lifecycle hook, invoked (with the value typed as the concrete `Owned`) only when the crawler
90
+ * owns a present instance — a no-op for a borrowed instance or an owned-but-not-yet-built slot.
91
+ */
92
+ async ifOwned(fn) {
93
+ if (!this.#owned || !this.#present) {
94
+ return undefined;
95
+ }
96
+ return fn(this.#value);
97
+ }
98
+ }