@crawlee/core 4.0.0-beta.11 → 4.0.0-beta.111

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 (271) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +105 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +1 -4
  35. package/crawlers/error_snapshotter.js +3 -6
  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 +91 -41
  43. package/crawlers/statistics.js +83 -72
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +40 -27
  51. package/enqueue_links/shared.js +90 -68
  52. package/errors.d.ts +41 -4
  53. package/errors.js +50 -5
  54. package/events/event_manager.d.ts +34 -8
  55. package/events/event_manager.js +8 -10
  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 +37 -11
  60. package/index.d.ts +6 -4
  61. package/index.js +5 -3
  62. package/iterables.d.ts +79 -0
  63. package/iterables.js +134 -0
  64. package/log.d.ts +82 -3
  65. package/log.js +106 -1
  66. package/memory-storage/consts.d.ts +4 -0
  67. package/memory-storage/consts.js +4 -0
  68. package/memory-storage/index.d.ts +1 -0
  69. package/memory-storage/index.js +1 -0
  70. package/memory-storage/memory-storage.d.ts +42 -0
  71. package/memory-storage/memory-storage.js +136 -0
  72. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  73. package/memory-storage/resource-clients/common/base-client.js +6 -0
  74. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  75. package/memory-storage/resource-clients/dataset.js +114 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +204 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  79. package/memory-storage/resource-clients/request-queue.js +422 -0
  80. package/memory-storage/utils.d.ts +16 -0
  81. package/memory-storage/utils.js +41 -0
  82. package/owned_or_injected.d.ts +58 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +27 -152
  86. package/proxy_configuration.js +27 -179
  87. package/recoverable_state.d.ts +111 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +86 -17
  90. package/request.js +117 -41
  91. package/router.d.ts +193 -21
  92. package/router.js +188 -43
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +9 -11
  95. package/service_locator.d.ts +147 -0
  96. package/service_locator.js +244 -0
  97. package/session_pool/consts.d.ts +1 -2
  98. package/session_pool/consts.js +1 -2
  99. package/session_pool/errors.d.ts +0 -1
  100. package/session_pool/errors.js +0 -1
  101. package/session_pool/fingerprint.d.ts +9 -0
  102. package/session_pool/fingerprint.js +30 -0
  103. package/session_pool/index.d.ts +0 -2
  104. package/session_pool/index.js +0 -2
  105. package/session_pool/session.d.ts +37 -86
  106. package/session_pool/session.js +85 -138
  107. package/session_pool/session_pool.d.ts +77 -91
  108. package/session_pool/session_pool.js +159 -147
  109. package/storages/dataset.d.ts +114 -54
  110. package/storages/dataset.js +285 -144
  111. package/storages/index.d.ts +9 -8
  112. package/storages/index.js +7 -8
  113. package/storages/key_value_store.d.ts +185 -42
  114. package/storages/key_value_store.js +424 -151
  115. package/storages/key_value_store_codec.d.ts +32 -0
  116. package/storages/key_value_store_codec.js +113 -0
  117. package/storages/request_dedup_cache.d.ts +22 -0
  118. package/storages/request_dedup_cache.js +48 -0
  119. package/storages/request_list.d.ts +52 -116
  120. package/storages/request_list.js +158 -133
  121. package/storages/request_loader.d.ts +96 -0
  122. package/storages/request_loader.js +1 -0
  123. package/storages/request_manager.d.ts +33 -0
  124. package/storages/request_manager.js +1 -0
  125. package/storages/request_manager_tandem.d.ts +97 -0
  126. package/storages/request_manager_tandem.js +197 -0
  127. package/storages/request_queue.d.ts +290 -47
  128. package/storages/request_queue.js +825 -216
  129. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  130. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +136 -143
  131. package/storages/storage_instance_manager.d.ts +87 -0
  132. package/storages/storage_instance_manager.js +256 -0
  133. package/storages/storage_stats.d.ts +48 -0
  134. package/storages/storage_stats.js +29 -0
  135. package/storages/transaction.d.ts +252 -0
  136. package/storages/transaction.js +251 -0
  137. package/storages/utils.d.ts +54 -9
  138. package/storages/utils.js +64 -13
  139. package/system-info/cpu-info.d.ts +67 -0
  140. package/system-info/cpu-info.js +216 -0
  141. package/system-info/memory-info.d.ts +31 -0
  142. package/system-info/memory-info.js +115 -0
  143. package/system-info/ps-tree.d.ts +17 -0
  144. package/system-info/ps-tree.js +144 -0
  145. package/system-info/runtime.d.ts +14 -0
  146. package/system-info/runtime.js +80 -0
  147. package/typedefs.d.ts +0 -6
  148. package/typedefs.js +0 -1
  149. package/validators.d.ts +8 -1
  150. package/validators.js +10 -3
  151. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  152. package/autoscaling/autoscaled_pool.js.map +0 -1
  153. package/autoscaling/index.d.ts.map +0 -1
  154. package/autoscaling/index.js.map +0 -1
  155. package/autoscaling/snapshotter.d.ts.map +0 -1
  156. package/autoscaling/snapshotter.js.map +0 -1
  157. package/autoscaling/system_status.d.ts.map +0 -1
  158. package/autoscaling/system_status.js.map +0 -1
  159. package/configuration.d.ts.map +0 -1
  160. package/configuration.js.map +0 -1
  161. package/cookie_utils.d.ts.map +0 -1
  162. package/cookie_utils.js.map +0 -1
  163. package/crawlers/context_pipeline.d.ts.map +0 -1
  164. package/crawlers/context_pipeline.js.map +0 -1
  165. package/crawlers/crawler_commons.d.ts.map +0 -1
  166. package/crawlers/crawler_commons.js.map +0 -1
  167. package/crawlers/crawler_utils.d.ts +0 -10
  168. package/crawlers/crawler_utils.d.ts.map +0 -1
  169. package/crawlers/crawler_utils.js +0 -12
  170. package/crawlers/crawler_utils.js.map +0 -1
  171. package/crawlers/error_snapshotter.d.ts.map +0 -1
  172. package/crawlers/error_snapshotter.js.map +0 -1
  173. package/crawlers/error_tracker.d.ts.map +0 -1
  174. package/crawlers/error_tracker.js.map +0 -1
  175. package/crawlers/index.d.ts.map +0 -1
  176. package/crawlers/index.js.map +0 -1
  177. package/crawlers/internals/types.d.ts.map +0 -1
  178. package/crawlers/internals/types.js.map +0 -1
  179. package/crawlers/statistics.d.ts.map +0 -1
  180. package/crawlers/statistics.js.map +0 -1
  181. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  182. package/enqueue_links/enqueue_links.js.map +0 -1
  183. package/enqueue_links/index.d.ts.map +0 -1
  184. package/enqueue_links/index.js.map +0 -1
  185. package/enqueue_links/shared.d.ts.map +0 -1
  186. package/enqueue_links/shared.js.map +0 -1
  187. package/errors.d.ts.map +0 -1
  188. package/errors.js.map +0 -1
  189. package/events/event_manager.d.ts.map +0 -1
  190. package/events/event_manager.js.map +0 -1
  191. package/events/index.d.ts.map +0 -1
  192. package/events/index.js.map +0 -1
  193. package/events/local_event_manager.d.ts.map +0 -1
  194. package/events/local_event_manager.js.map +0 -1
  195. package/http_clients/base-http-client.d.ts +0 -134
  196. package/http_clients/base-http-client.d.ts.map +0 -1
  197. package/http_clients/base-http-client.js +0 -33
  198. package/http_clients/base-http-client.js.map +0 -1
  199. package/http_clients/form-data-like.d.ts +0 -67
  200. package/http_clients/form-data-like.d.ts.map +0 -1
  201. package/http_clients/form-data-like.js +0 -5
  202. package/http_clients/form-data-like.js.map +0 -1
  203. package/http_clients/got-scraping-http-client.d.ts +0 -15
  204. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  205. package/http_clients/got-scraping-http-client.js +0 -69
  206. package/http_clients/got-scraping-http-client.js.map +0 -1
  207. package/http_clients/index.d.ts +0 -3
  208. package/http_clients/index.d.ts.map +0 -1
  209. package/http_clients/index.js +0 -3
  210. package/http_clients/index.js.map +0 -1
  211. package/index.d.ts.map +0 -1
  212. package/index.js.map +0 -1
  213. package/log.d.ts.map +0 -1
  214. package/log.js.map +0 -1
  215. package/proxy_configuration.d.ts.map +0 -1
  216. package/proxy_configuration.js.map +0 -1
  217. package/request.d.ts.map +0 -1
  218. package/request.js.map +0 -1
  219. package/router.d.ts.map +0 -1
  220. package/router.js.map +0 -1
  221. package/serialization.d.ts.map +0 -1
  222. package/serialization.js.map +0 -1
  223. package/session_pool/consts.d.ts.map +0 -1
  224. package/session_pool/consts.js.map +0 -1
  225. package/session_pool/errors.d.ts.map +0 -1
  226. package/session_pool/errors.js.map +0 -1
  227. package/session_pool/events.d.ts +0 -3
  228. package/session_pool/events.d.ts.map +0 -1
  229. package/session_pool/events.js +0 -3
  230. package/session_pool/events.js.map +0 -1
  231. package/session_pool/index.d.ts.map +0 -1
  232. package/session_pool/index.js.map +0 -1
  233. package/session_pool/session.d.ts.map +0 -1
  234. package/session_pool/session.js.map +0 -1
  235. package/session_pool/session_pool.d.ts.map +0 -1
  236. package/session_pool/session_pool.js.map +0 -1
  237. package/storages/access_checking.d.ts +0 -13
  238. package/storages/access_checking.d.ts.map +0 -1
  239. package/storages/access_checking.js +0 -14
  240. package/storages/access_checking.js.map +0 -1
  241. package/storages/dataset.d.ts.map +0 -1
  242. package/storages/dataset.js.map +0 -1
  243. package/storages/index.d.ts.map +0 -1
  244. package/storages/index.js.map +0 -1
  245. package/storages/key_value_store.d.ts.map +0 -1
  246. package/storages/key_value_store.js.map +0 -1
  247. package/storages/request_list.d.ts.map +0 -1
  248. package/storages/request_list.js.map +0 -1
  249. package/storages/request_provider.d.ts +0 -308
  250. package/storages/request_provider.d.ts.map +0 -1
  251. package/storages/request_provider.js +0 -555
  252. package/storages/request_provider.js.map +0 -1
  253. package/storages/request_queue.d.ts.map +0 -1
  254. package/storages/request_queue.js.map +0 -1
  255. package/storages/request_queue_v2.d.ts +0 -87
  256. package/storages/request_queue_v2.d.ts.map +0 -1
  257. package/storages/request_queue_v2.js +0 -438
  258. package/storages/request_queue_v2.js.map +0 -1
  259. package/storages/sitemap_request_list.d.ts.map +0 -1
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/tsconfig.build.tsbuildinfo +0 -1
  268. package/typedefs.d.ts.map +0 -1
  269. package/typedefs.js.map +0 -1
  270. package/validators.d.ts.map +0 -1
  271. package/validators.js.map +0 -1
@@ -0,0 +1,422 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { AsyncQueue } from '@sapphire/async-queue';
3
+ import { s } from '@sapphire/shapeshift';
4
+ import { purgeNullsFromObject, uniqueKeyToRequestId } from '../utils.js';
5
+ import { BaseClient } from './common/base-client.js';
6
+ const requestShape = s
7
+ .object({
8
+ id: s.string(),
9
+ url: s.string().url({ allowedProtocols: ['http:', 'https:'] }),
10
+ uniqueKey: s.string(),
11
+ method: s.string().optional(),
12
+ retryCount: s.number().int().optional(),
13
+ handledAt: s.union([s.string(), s.date().valid()]).optional(),
14
+ })
15
+ .passthrough();
16
+ const requestShapeWithoutId = requestShape.omit(['id']);
17
+ const batchRequestShapeWithoutId = requestShapeWithoutId.array();
18
+ const requestOptionsShape = s.object({
19
+ forefront: s.boolean().optional(),
20
+ });
21
+ export class RequestQueueBackend extends BaseClient {
22
+ name;
23
+ /**
24
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
25
+ * storages, this is the alias string. Falls back to id.
26
+ */
27
+ cacheKey;
28
+ createdAt = new Date();
29
+ accessedAt = new Date();
30
+ modifiedAt = new Date();
31
+ handledRequestCount = 0;
32
+ pendingRequestCount = 0;
33
+ /**
34
+ * Serializes every operation that reads-then-writes this backend's shared queue state — the
35
+ * `requests` map, the `forefrontRequestIds` array, the `inProgressRequestIds` set and the request
36
+ * counts. Those mutations span `await` points, so without this mutex a concurrent operation could
37
+ * interleave and corrupt them (e.g. a head scan pruning `forefrontRequestIds` while
38
+ * `addBatchOfRequests` pushes to it). Held by every mutating method as well as by `isEmpty`/
39
+ * `isFinished`, whose head scan also prunes `forefrontRequestIds`.
40
+ */
41
+ #queueStateMutex = new AsyncQueue();
42
+ #forefrontRequestIds = [];
43
+ /**
44
+ * IDs of requests currently fetched but not yet handled or reclaimed. A request in this set is
45
+ * "in progress" and will not be handed out again by {@link fetchNextRequest}.
46
+ *
47
+ * Unlike the file-system / platform clients, the in-memory queue lives entirely within a single
48
+ * process and is never shared with another consumer, so there is no need for an expiring,
49
+ * cross-process-visible lock — tracking in-progress requests in this set is enough.
50
+ */
51
+ #inProgressRequestIds = new Set();
52
+ #requests = new Map();
53
+ // kept as TS-private: storage-backend tests read this field at runtime
54
+ storageBackend;
55
+ constructor(options) {
56
+ super(options.id ?? randomUUID());
57
+ this.name = options.name;
58
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
59
+ this.storageBackend = options.storageBackend;
60
+ }
61
+ async getMetadata() {
62
+ this.updateTimestamps(false);
63
+ return this.toRequestQueueInfo();
64
+ }
65
+ async drop() {
66
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
67
+ // operation cannot observe half-cleared state — e.g. a forefront id whose request has already been
68
+ // removed, which `listPendingHead` would then dereference as `undefined`.
69
+ await this.#queueStateMutex.wait();
70
+ try {
71
+ const storeIndex = this.storageBackend.requestQueueBackendCache.findIndex((queue) => queue.id === this.id);
72
+ if (storeIndex !== -1) {
73
+ const [oldBackend] = this.storageBackend.requestQueueBackendCache.splice(storeIndex, 1);
74
+ oldBackend.pendingRequestCount = 0;
75
+ // Clear all in-memory state, consistent with `purge`. Clearing `requests` alone would
76
+ // leave dangling ids in `forefrontRequestIds`/`inProgressRequestIds`, which a later head
77
+ // scan would resolve to a missing request and dereference.
78
+ oldBackend.#requests.clear();
79
+ oldBackend.#forefrontRequestIds = [];
80
+ oldBackend.#inProgressRequestIds.clear();
81
+ }
82
+ }
83
+ finally {
84
+ this.#queueStateMutex.shift();
85
+ }
86
+ }
87
+ async purge() {
88
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
89
+ // operation cannot observe or repopulate half-cleared state across the `await` below.
90
+ await this.#queueStateMutex.wait();
91
+ try {
92
+ // Clear all in-memory state
93
+ this.#requests.clear();
94
+ this.#forefrontRequestIds = [];
95
+ this.#inProgressRequestIds.clear();
96
+ this.handledRequestCount = 0;
97
+ this.pendingRequestCount = 0;
98
+ this.updateTimestamps(true);
99
+ }
100
+ finally {
101
+ this.#queueStateMutex.shift();
102
+ }
103
+ }
104
+ *requestKeyIterator() {
105
+ for (let i = this.#forefrontRequestIds.length - 1; i >= 0; i--) {
106
+ yield this.#forefrontRequestIds[i];
107
+ }
108
+ for (const key of this.#requests.keys()) {
109
+ yield key;
110
+ }
111
+ }
112
+ /**
113
+ * Scans the queue and returns the pending head — requests that are neither handled nor currently
114
+ * in progress — ordered by `orderNo`, deduplicated.
115
+ *
116
+ * When `detectInProgressRequests` is set, the result also carries an `hasInProgressRequests` flag
117
+ * telling whether any unhandled-but-in-progress request was skipped along the way. It lets
118
+ * {@link isFinished} distinguish "no work left at all" from "work remains, but it is currently being
119
+ * processed". Without it, a consumer with concurrency could consider the queue finished and shut the
120
+ * crawler down while it is still handling the last requests.
121
+ *
122
+ * Computing the flag is expensive: because an in-progress request may sit anywhere in the queue, it
123
+ * forces a scan of every pending entry even when only `limit` items are wanted. Callers that only
124
+ * need the head (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as
125
+ * soon as the page is filled, keeping those calls O(head) instead of O(N).
126
+ */
127
+ async listPendingHead(limit, detectInProgressRequests = false) {
128
+ const items = [];
129
+ let hasInProgressRequests = false;
130
+ // Tracks processed request IDs to avoid duplicates (request in both `forefrontRequestIds` and `requests`).
131
+ const seenRequestIds = new Set();
132
+ // Tracks handled request IDs from `forefrontRequestIds` to be removed.
133
+ const handledForefrontIds = new Set();
134
+ for (const requestId of this.requestKeyIterator()) {
135
+ // Once the requested page is filled we can stop — unless the caller asked us to detect
136
+ // in-progress requests and we have not yet seen one, in which case we must keep scanning.
137
+ if (items.length >= limit && (!detectInProgressRequests || hasInProgressRequests)) {
138
+ break;
139
+ }
140
+ if (seenRequestIds.has(requestId)) {
141
+ continue;
142
+ }
143
+ seenRequestIds.add(requestId);
144
+ const request = this.#requests.get(requestId);
145
+ // Permanently-handled requests (`orderNo === null`) are in a terminal state and can be skipped.
146
+ if (request.orderNo === null) {
147
+ if (this.#forefrontRequestIds.includes(requestId)) {
148
+ handledForefrontIds.add(requestId);
149
+ }
150
+ continue;
151
+ }
152
+ // In progress (fetched but not yet handled or reclaimed) — skip it, but remember that the
153
+ // queue is not truly empty.
154
+ if (this.#inProgressRequestIds.has(requestId)) {
155
+ hasInProgressRequests = true;
156
+ continue;
157
+ }
158
+ if (items.length < limit) {
159
+ items.push(request);
160
+ }
161
+ }
162
+ this.#forefrontRequestIds = this.#forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
163
+ return {
164
+ items: items.sort((a, b) => a.orderNo - b.orderNo),
165
+ hasInProgressRequests: detectInProgressRequests ? hasInProgressRequests : undefined,
166
+ };
167
+ }
168
+ async fetchNextRequest() {
169
+ this.updateTimestamps(false);
170
+ await this.#queueStateMutex.wait();
171
+ try {
172
+ const { items: [head], } = await this.listPendingHead(1);
173
+ if (!head) {
174
+ return undefined;
175
+ }
176
+ // Mark the request as in progress so it is not handed out again until it is handled or
177
+ // reclaimed. The request keeps its `orderNo` (and thus its forefront / normal ordering).
178
+ this.#inProgressRequestIds.add(head.id);
179
+ return this.jsonToRequest(head.json) ?? undefined;
180
+ }
181
+ finally {
182
+ this.#queueStateMutex.shift();
183
+ }
184
+ }
185
+ async addBatchOfRequests(requests, options = {}) {
186
+ batchRequestShapeWithoutId.parse(requests);
187
+ requestOptionsShape.parse(options);
188
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
189
+ // shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
190
+ // concurrent operation interleaving at one of the `await` points below.
191
+ await this.#queueStateMutex.wait();
192
+ try {
193
+ const result = {
194
+ processedRequests: [],
195
+ unprocessedRequests: [],
196
+ };
197
+ for (const model of requests) {
198
+ const requestModel = this.createInternalRequest(model, options.forefront);
199
+ const existingRequestWithId = this.#requests.get(requestModel.id);
200
+ if (existingRequestWithId) {
201
+ result.processedRequests.push({
202
+ requestId: existingRequestWithId.id,
203
+ uniqueKey: existingRequestWithId.uniqueKey,
204
+ wasAlreadyHandled: existingRequestWithId.orderNo === null,
205
+ wasAlreadyPresent: true,
206
+ });
207
+ continue;
208
+ }
209
+ this.#requests.set(requestModel.id, requestModel);
210
+ if (requestModel.orderNo) {
211
+ this.pendingRequestCount += 1;
212
+ }
213
+ else {
214
+ this.handledRequestCount += 1;
215
+ }
216
+ if (options.forefront) {
217
+ this.#forefrontRequestIds.push(requestModel.id);
218
+ }
219
+ result.processedRequests.push({
220
+ requestId: requestModel.id,
221
+ uniqueKey: requestModel.uniqueKey,
222
+ // We return wasAlreadyHandled: false even though the request may
223
+ // have been added as handled, because that's how API behaves.
224
+ wasAlreadyHandled: false,
225
+ wasAlreadyPresent: false,
226
+ });
227
+ }
228
+ this.updateTimestamps(true);
229
+ return result;
230
+ }
231
+ finally {
232
+ this.#queueStateMutex.shift();
233
+ }
234
+ }
235
+ async getRequest(uniqueKey) {
236
+ s.string().parse(uniqueKey);
237
+ this.updateTimestamps(false);
238
+ const id = uniqueKeyToRequestId(uniqueKey);
239
+ const json = this.#requests.get(id)?.json;
240
+ return this.jsonToRequest(json);
241
+ }
242
+ async markRequestAsHandled(request) {
243
+ requestShape.parse(request);
244
+ this.updateTimestamps(false);
245
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
246
+ // `requests` map, `inProgressRequestIds` set and request counts stay consistent across the
247
+ // `await` points below.
248
+ await this.#queueStateMutex.wait();
249
+ try {
250
+ const id = uniqueKeyToRequestId(request.uniqueKey);
251
+ const existingRequest = this.#requests.get(id);
252
+ // The request must exist to be marked as handled. We intentionally do NOT require it to still
253
+ // be in progress: marking an already-released request handled must still succeed, otherwise
254
+ // the request could be handed out again and the queue would never finish.
255
+ if (!existingRequest) {
256
+ return undefined;
257
+ }
258
+ // A handled request has `orderNo === null`. Marking it again is an idempotent no-op.
259
+ const wasAlreadyHandled = existingRequest.orderNo === null;
260
+ const handledAt = request.handledAt ?? new Date().toISOString();
261
+ const requestModel = this.createInternalRequest({ ...request, handledAt }, false);
262
+ this.#requests.set(id, requestModel);
263
+ // The request is no longer in progress for this client.
264
+ this.#inProgressRequestIds.delete(id);
265
+ if (!wasAlreadyHandled) {
266
+ this.pendingRequestCount -= 1;
267
+ this.handledRequestCount += 1;
268
+ }
269
+ this.updateTimestamps(true);
270
+ return {
271
+ requestId: id,
272
+ wasAlreadyHandled,
273
+ wasAlreadyPresent: true,
274
+ };
275
+ }
276
+ finally {
277
+ this.#queueStateMutex.shift();
278
+ }
279
+ }
280
+ async reclaimRequest(request, options = {}) {
281
+ requestShape.parse(request);
282
+ requestOptionsShape.parse(options);
283
+ this.updateTimestamps(false);
284
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
285
+ // `requests` map, `forefrontRequestIds` array and `inProgressRequestIds` set stay consistent
286
+ // across the `await` points below.
287
+ await this.#queueStateMutex.wait();
288
+ try {
289
+ const id = uniqueKeyToRequestId(request.uniqueKey);
290
+ const existingRequest = this.#requests.get(id);
291
+ // The request must exist and not already be handled to be reclaimed. As with
292
+ // `markRequestAsHandled`, we do NOT require it to still be in progress — returning an
293
+ // already-released request to the queue (e.g. to honor a `forefront` reorder) must still
294
+ // work, rather than have the reclaim silently dropped.
295
+ if (!existingRequest || existingRequest.orderNo === null) {
296
+ return undefined;
297
+ }
298
+ // Reclaiming resets the `orderNo` to a fresh timestamp, restoring the request to the queue
299
+ // (at the front if `forefront`).
300
+ const requestModel = this.createInternalRequest(request, options.forefront);
301
+ this.#requests.set(id, requestModel);
302
+ // The request is no longer in progress for this client.
303
+ this.#inProgressRequestIds.delete(id);
304
+ if (options.forefront) {
305
+ this.#forefrontRequestIds.push(id);
306
+ }
307
+ this.updateTimestamps(true);
308
+ return {
309
+ requestId: id,
310
+ wasAlreadyHandled: false,
311
+ wasAlreadyPresent: true,
312
+ };
313
+ }
314
+ finally {
315
+ this.#queueStateMutex.shift();
316
+ }
317
+ }
318
+ async isEmpty() {
319
+ this.updateTimestamps(false);
320
+ // "Empty" means there is nothing left to fetch right now — i.e. the next `fetchNextRequest`
321
+ // would return `null`. Requests that are currently in progress are intentionally NOT counted
322
+ // here: they are not fetchable, so the queue is empty from a consumer's point of view. Whether
323
+ // those in-progress requests mean crawling is not yet done is a separate question, answered by
324
+ // `isFinished`.
325
+ //
326
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
327
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
328
+ await this.#queueStateMutex.wait();
329
+ try {
330
+ const { items } = await this.listPendingHead(1);
331
+ return items.length === 0;
332
+ }
333
+ finally {
334
+ this.#queueStateMutex.shift();
335
+ }
336
+ }
337
+ async isFinished() {
338
+ this.updateTimestamps(false);
339
+ // The queue is finished only when there is nothing left to fetch AND nothing currently in
340
+ // progress. Counting in-progress requests is what allows a crawler with concurrency to keep
341
+ // waiting while it still holds the last requests, instead of finishing prematurely.
342
+ //
343
+ // Detecting in-progress requests requires a full scan, hence the `detectInProgressRequests`
344
+ // flag — unlike `fetchNextRequest`/`isEmpty`, which only need the head and can stop early.
345
+ //
346
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
347
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
348
+ await this.#queueStateMutex.wait();
349
+ try {
350
+ const { items, hasInProgressRequests } = await this.listPendingHead(1, true);
351
+ return items.length === 0 && !hasInProgressRequests;
352
+ }
353
+ finally {
354
+ this.#queueStateMutex.shift();
355
+ }
356
+ }
357
+ /**
358
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
359
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
360
+ * nothing is marked in progress.
361
+ */
362
+ async listItems() {
363
+ this.updateTimestamps(false);
364
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state
365
+ // mutex to avoid racing a concurrent mutator at its `await` points.
366
+ await this.#queueStateMutex.wait();
367
+ try {
368
+ const { items } = await this.listPendingHead(Number.POSITIVE_INFINITY);
369
+ return items.map((request) => this.jsonToRequest(request.json));
370
+ }
371
+ finally {
372
+ this.#queueStateMutex.shift();
373
+ }
374
+ }
375
+ toRequestQueueInfo() {
376
+ return {
377
+ accessedAt: this.accessedAt,
378
+ createdAt: this.createdAt,
379
+ handledRequestCount: this.handledRequestCount,
380
+ id: this.id,
381
+ modifiedAt: this.modifiedAt,
382
+ name: this.name,
383
+ pendingRequestCount: this.pendingRequestCount,
384
+ totalRequestCount: this.#requests.size,
385
+ };
386
+ }
387
+ updateTimestamps(hasBeenModified) {
388
+ this.accessedAt = new Date();
389
+ if (hasBeenModified) {
390
+ this.modifiedAt = new Date();
391
+ }
392
+ }
393
+ jsonToRequest(requestJson) {
394
+ if (!requestJson)
395
+ return undefined;
396
+ const request = JSON.parse(requestJson);
397
+ return purgeNullsFromObject(request);
398
+ }
399
+ createInternalRequest(request, forefront) {
400
+ const orderNo = this.calculateOrderNo(request, forefront);
401
+ const id = uniqueKeyToRequestId(request.uniqueKey);
402
+ if (request.id && request.id !== id) {
403
+ throw new Error('Request ID does not match its uniqueKey.');
404
+ }
405
+ const json = JSON.stringify({ ...request, id });
406
+ return {
407
+ id,
408
+ json,
409
+ method: request.method,
410
+ orderNo,
411
+ retryCount: request.retryCount ?? 0,
412
+ uniqueKey: request.uniqueKey,
413
+ url: request.url,
414
+ };
415
+ }
416
+ calculateOrderNo(request, forefront) {
417
+ if (request.handledAt)
418
+ return null;
419
+ const timestamp = Date.now();
420
+ return forefront ? -timestamp : timestamp;
421
+ }
422
+ }
@@ -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
+ }