@crawlee/core 4.0.0-beta.13 → 4.0.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +362 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -129
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +68 -154
  47. package/enqueue_links/enqueue_links.js +38 -210
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +52 -26
  51. package/enqueue_links/shared.js +115 -66
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +108 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +201 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +409 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +14 -13
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +32 -147
  89. package/recoverable_state.d.ts +155 -0
  90. package/recoverable_state.js +231 -0
  91. package/request.d.ts +80 -16
  92. package/request.js +147 -68
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +73 -91
  110. package/session_pool/session_pool.js +172 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +291 -148
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +445 -169
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -115
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -82
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js +0 -430
  269. package/storages/sitemap_request_list.js.map +0 -1
  270. package/storages/storage_manager.d.ts +0 -58
  271. package/storages/storage_manager.d.ts.map +0 -1
  272. package/storages/storage_manager.js +0 -105
  273. package/storages/storage_manager.js.map +0 -1
  274. package/storages/utils.d.ts.map +0 -1
  275. package/storages/utils.js.map +0 -1
  276. package/tsconfig.build.tsbuildinfo +0 -1
  277. package/typedefs.d.ts.map +0 -1
  278. package/typedefs.js.map +0 -1
  279. package/validators.d.ts.map +0 -1
  280. package/validators.js.map +0 -1
@@ -0,0 +1,101 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ import type { Request } from '../request.js';
3
+ import type { IRequestManager } from './request_manager.js';
4
+ import type { RequestQueueOperationInfo } from './request_queue.js';
5
+ /**
6
+ * An abstract interface defining a read-only stream of requests to crawl.
7
+ *
8
+ * Request loaders are used to manage and provide access to a storage of crawling requests.
9
+ *
10
+ * Key responsibilities:
11
+ * - Fetching the next request to be processed.
12
+ * - Marking requests as handled once they are no longer in progress.
13
+ * - Managing state information such as the total and handled request counts.
14
+ *
15
+ * ## Request lifecycle contract
16
+ *
17
+ * Every request returned by {@link IRequestLoader.fetchNextRequest} is considered **in progress**
18
+ * until it is passed to {@link IRequestLoader.markRequestAsHandled}. Once you fetch a request, you are
19
+ * obligated to eventually mark it as handled — there is no way to hand a request back to a loader
20
+ * (only an {@link IRequestManager} can reclaim requests for a retry). "Handled" therefore means
21
+ * "finished with this request", whether processing succeeded or was abandoned after exhausting retries.
22
+ *
23
+ * Honoring this contract matters for three reasons:
24
+ * - **Restarts and migrations:** loaders that persist their state (see {@link IRequestLoader.persistState})
25
+ * treat in-progress requests as interrupted and re-serve them after a restart. A request that is fetched
26
+ * but never marked handled will be crawled again.
27
+ * - **Termination detection:** {@link IRequestLoader.isFinished} only resolves to `true` once nothing is
28
+ * in progress. Leaving a request unmarked keeps the crawler running indefinitely.
29
+ * - **Bookkeeping:** the handled and pending counts are derived from the set of in-progress requests, so
30
+ * skipping {@link IRequestLoader.markRequestAsHandled} corrupts {@link IRequestLoader.getHandledCount}
31
+ * and {@link IRequestLoader.getPendingCount}.
32
+ *
33
+ * Concrete implementations such as {@link RequestList} or {@link SitemapRequestLoader} build on this interface.
34
+ * The {@link IRequestManager} interface extends it with the capability to enqueue and reclaim requests.
35
+ */
36
+ export interface IRequestLoader {
37
+ /**
38
+ * Returns an approximation of the total number of requests in the loader (i.e. pending + handled).
39
+ */
40
+ getTotalCount(): Promise<number>;
41
+ /**
42
+ * Returns an approximation of the number of pending requests in the loader.
43
+ */
44
+ getPendingCount(): Promise<number>;
45
+ /**
46
+ * Returns the number of requests in the loader that have been handled.
47
+ */
48
+ getHandledCount(): Promise<number>;
49
+ /**
50
+ * Returns `true` if all requests were already handled and there are no more left.
51
+ */
52
+ isFinished(): Promise<boolean>;
53
+ /**
54
+ * Resolves to `true` if the next call to {@link IRequestLoader.fetchNextRequest} function
55
+ * would return `null`, otherwise it resolves to `false`.
56
+ * Note that even if the loader is empty, there might be some pending requests currently being processed.
57
+ *
58
+ * This is a statement about what the *next fetch* would return, not about how much work is left, so it
59
+ * may report `true` while {@link IRequestLoader.getPendingCount} is non-zero - a loader that withholds
60
+ * requests for a while (as {@link ThrottlingRequestManager} does for a rate-limited domain) is empty
61
+ * for as long as it will not hand anything over. Use `isFinished()` to ask whether the work is done.
62
+ */
63
+ isEmpty(): Promise<boolean>;
64
+ /**
65
+ * Gets the next {@link Request} to process, or `null` if there are no more pending requests.
66
+ *
67
+ * The returned request is marked as **in progress** and remains so until it is passed to
68
+ * {@link IRequestLoader.markRequestAsHandled}. The caller is responsible for eventually marking
69
+ * every fetched request as handled; otherwise the loader never considers itself finished and the
70
+ * request may be re-served after a restart. See the request lifecycle contract on {@link IRequestLoader}.
71
+ */
72
+ fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
73
+ /**
74
+ * Can be used to iterate over the loader instance in a `for await .. of` loop.
75
+ * Provides an alternative for the repeated use of `fetchNextRequest`.
76
+ */
77
+ [Symbol.asyncIterator](): AsyncGenerator<Request>;
78
+ /**
79
+ * Marks a request previously returned by {@link IRequestLoader.fetchNextRequest} as handled,
80
+ * removing it from the set of in-progress requests.
81
+ *
82
+ * Call this once you are done with the request — whether processing succeeded or was abandoned after
83
+ * exhausting retries. Because a loader cannot take a request back, marking it handled is the only way to
84
+ * signal completion; failing to do so prevents {@link IRequestLoader.isFinished} from ever resolving to
85
+ * `true` and skews the handled and pending counts. See the request lifecycle contract on {@link IRequestLoader}.
86
+ */
87
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
88
+ /**
89
+ * Persists the current state of the loader into the default {@link KeyValueStore}.
90
+ *
91
+ * Not all loaders support persistence; implementations that do not should leave this `undefined`.
92
+ */
93
+ persistState?(): Promise<void>;
94
+ /**
95
+ * Combines the loader with a request manager to support adding and reclaiming requests.
96
+ *
97
+ * @param requestManager Request manager to combine the loader with. If not provided, the default
98
+ * {@link RequestQueue} is used.
99
+ */
100
+ toTandem?(requestManager?: IRequestManager): Promise<IRequestManager>;
101
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ import type { Request, Source } from '../request.js';
2
+ import type { IRequestLoader } from './request_loader.js';
3
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
4
+ export type RequestsLike = AsyncIterable<Source | string> | Iterable<Source | string> | (Source | string)[];
5
+ /**
6
+ * Extends the read-only {@link IRequestLoader} interface with the capability to enqueue new requests
7
+ * and reclaim failed ones.
8
+ */
9
+ export interface IRequestManager extends IRequestLoader {
10
+ /**
11
+ * Reclaims request to the provider if its processing failed.
12
+ * The request will be returned by some subsequent `fetchNextRequest()` call.
13
+ */
14
+ reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
15
+ addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
16
+ addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
17
+ /**
18
+ * Remove all requests from the queue but keep the queue itself, resetting it
19
+ * so it can be reused (e.g. across multiple `crawler.run()` calls).
20
+ *
21
+ * Implementations that do not support purging may leave this `undefined`.
22
+ */
23
+ purge?(): Promise<void>;
24
+ /**
25
+ * Tells the manager how long a consumer expects to hold a request fetched via `fetchNextRequest()`
26
+ * before marking it handled or reclaiming it (typically the request-handler timeout plus padding).
27
+ *
28
+ * Managers backed by a storage backend that reserves requests via locking use this to avoid handing
29
+ * the same request out again while it is still being processed. Implementations that do not need
30
+ * this hint may leave it `undefined`.
31
+ */
32
+ setExpectedRequestProcessingTimeSecs?(secs: number): Promise<void>;
33
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,97 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ import type { Request, Source } from '../request.js';
3
+ import type { IRequestLoader } from './request_loader.js';
4
+ import type { IRequestManager, RequestsLike } from './request_manager.js';
5
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
6
+ /**
7
+ * A request manager that combines a {@link IRequestLoader} (such as a `RequestList`) with a writable
8
+ * {@link IRequestManager} (such as a `RequestQueue`).
9
+ * It first reads requests from the loader and then, when needed, transfers them in batches to the manager.
10
+ */
11
+ export declare class RequestManagerTandem implements IRequestManager {
12
+ #private;
13
+ /**
14
+ * @param requestLoader The read-only loader to read requests from first.
15
+ * @param requestManager The writable manager to transfer requests into and enqueue new ones. May be passed as a
16
+ * factory function so that the tandem can be constructed synchronously and the manager opened lazily on first use
17
+ * (e.g. a lazily-opened default {@link RequestQueue}).
18
+ */
19
+ constructor(requestLoader: IRequestLoader, requestManager: IRequestManager | (() => IRequestManager | Promise<IRequestManager>));
20
+ /**
21
+ * Resolves the writable request manager, opening it lazily (via the factory) on first use and memoizing the result.
22
+ * @private
23
+ */
24
+ private getRequestManager;
25
+ /**
26
+ * Transfers a single request from the read-only loader to the writable manager.
27
+ * If the transfer fails, the request is dropped (and logged) rather than reclaimed.
28
+ *
29
+ * @returns `true` if a request was successfully transferred (or there was nothing to transfer), and `false` if a
30
+ * transfer was attempted but failed - in which case the caller should not fetch from the manager this round.
31
+ * @private
32
+ */
33
+ private transferNextRequestToQueue;
34
+ /**
35
+ * Fetches the next request from the request manager. If the manager is empty and the loader
36
+ * is not finished, it will transfer a request from the loader to the manager first.
37
+ * @inheritdoc
38
+ */
39
+ fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
40
+ /**
41
+ * @inheritdoc
42
+ */
43
+ isFinished(): Promise<boolean>;
44
+ /**
45
+ * @inheritdoc
46
+ */
47
+ isEmpty(): Promise<boolean>;
48
+ /**
49
+ * @inheritdoc
50
+ */
51
+ getHandledCount(): Promise<number>;
52
+ /**
53
+ * @inheritdoc
54
+ */
55
+ getTotalCount(): Promise<number>;
56
+ /**
57
+ * @inheritdoc
58
+ */
59
+ getPendingCount(): Promise<number>;
60
+ /**
61
+ * @inheritdoc
62
+ */
63
+ [Symbol.asyncIterator](): AsyncGenerator<Request<Dictionary>, void, unknown>;
64
+ /**
65
+ * @inheritdoc
66
+ */
67
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
68
+ /**
69
+ * @inheritdoc
70
+ */
71
+ reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
72
+ /**
73
+ * @inheritdoc
74
+ */
75
+ addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
76
+ /**
77
+ * @inheritdoc
78
+ */
79
+ addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
80
+ /**
81
+ * Persists the state of the underlying read-only loader, if it supports persistence.
82
+ * @inheritdoc
83
+ */
84
+ persistState(): Promise<void>;
85
+ /**
86
+ * Purges the writable request manager so the tandem can be reused (e.g. across repeated `crawler.run()` calls).
87
+ * The read-only loader is immutable and cannot be purged, so only the manager side is reset.
88
+ * @inheritdoc
89
+ */
90
+ purge(): Promise<void>;
91
+ /**
92
+ * Forwards the hint to the writable request manager — that is where requests are fetched from and
93
+ * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
94
+ * @inheritdoc
95
+ */
96
+ setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
97
+ }
@@ -0,0 +1,197 @@
1
+ import { serviceLocator } from '../service_locator.js';
2
+ /**
3
+ * A request manager that combines a {@link IRequestLoader} (such as a `RequestList`) with a writable
4
+ * {@link IRequestManager} (such as a `RequestQueue`).
5
+ * It first reads requests from the loader and then, when needed, transfers them in batches to the manager.
6
+ */
7
+ export class RequestManagerTandem {
8
+ #log;
9
+ #requestLoader;
10
+ #requestManagerPromise;
11
+ #resolvedRequestManager;
12
+ #requestManagerFactory;
13
+ /**
14
+ * The latest expected request-processing time hinted via {@link setExpectedRequestProcessingTimeSecs}.
15
+ * Remembered so it can be applied to the writable manager once it is lazily resolved.
16
+ */
17
+ #expectedRequestProcessingSecs;
18
+ /**
19
+ * @param requestLoader The read-only loader to read requests from first.
20
+ * @param requestManager The writable manager to transfer requests into and enqueue new ones. May be passed as a
21
+ * factory function so that the tandem can be constructed synchronously and the manager opened lazily on first use
22
+ * (e.g. a lazily-opened default {@link RequestQueue}).
23
+ */
24
+ constructor(requestLoader, requestManager) {
25
+ this.#log = serviceLocator.getLogger().child({ prefix: 'RequestManagerTandem' });
26
+ this.#requestLoader = requestLoader;
27
+ this.#requestManagerFactory = typeof requestManager === 'function' ? requestManager : () => requestManager;
28
+ }
29
+ /**
30
+ * Resolves the writable request manager, opening it lazily (via the factory) on first use and memoizing the result.
31
+ * @private
32
+ */
33
+ async getRequestManager() {
34
+ if (this.#resolvedRequestManager === undefined) {
35
+ this.#requestManagerPromise ??= Promise.resolve(this.#requestManagerFactory());
36
+ this.#resolvedRequestManager = await this.#requestManagerPromise;
37
+ // Apply any hint received before the manager was resolved.
38
+ if (this.#expectedRequestProcessingSecs !== undefined) {
39
+ await this.#resolvedRequestManager.setExpectedRequestProcessingTimeSecs?.(this.#expectedRequestProcessingSecs);
40
+ }
41
+ }
42
+ return this.#resolvedRequestManager;
43
+ }
44
+ /**
45
+ * Transfers a single request from the read-only loader to the writable manager.
46
+ * If the transfer fails, the request is dropped (and logged) rather than reclaimed.
47
+ *
48
+ * @returns `true` if a request was successfully transferred (or there was nothing to transfer), and `false` if a
49
+ * transfer was attempted but failed - in which case the caller should not fetch from the manager this round.
50
+ * @private
51
+ */
52
+ async transferNextRequestToQueue() {
53
+ const request = await this.#requestLoader.fetchNextRequest();
54
+ if (request === null) {
55
+ return true;
56
+ }
57
+ const requestManager = await this.getRequestManager();
58
+ try {
59
+ await requestManager.addRequest(request, { forefront: true });
60
+ return true;
61
+ }
62
+ catch (error) {
63
+ this.#log.exception(error, 'Adding request from the RequestLoader to the RequestManager failed, the request has been dropped.', { url: request.url, uniqueKey: request.uniqueKey });
64
+ return false;
65
+ }
66
+ finally {
67
+ // Mark it as handled so that the request doesn't get stuck in the `inProgress` state in the loader.
68
+ await this.#requestLoader.markRequestAsHandled(request);
69
+ }
70
+ }
71
+ /**
72
+ * Fetches the next request from the request manager. If the manager is empty and the loader
73
+ * is not finished, it will transfer a request from the loader to the manager first.
74
+ * @inheritdoc
75
+ */
76
+ async fetchNextRequest() {
77
+ // First, try to transfer a request from the requestList
78
+ const [listEmpty, listFinished] = await Promise.all([
79
+ this.#requestLoader.isEmpty(),
80
+ this.#requestLoader.isFinished(),
81
+ ]);
82
+ if (!listEmpty && !listFinished) {
83
+ // If the transfer failed, the request was dropped; don't fetch from the manager this round (matching
84
+ // crawlee-python behaviour). The next `fetchNextRequest()` call will pick up where we left off.
85
+ if (!(await this.transferNextRequestToQueue())) {
86
+ return null;
87
+ }
88
+ }
89
+ // Try to fetch from manager after the transfer
90
+ return (await this.getRequestManager()).fetchNextRequest();
91
+ }
92
+ /**
93
+ * @inheritdoc
94
+ */
95
+ async isFinished() {
96
+ const requestManager = await this.getRequestManager();
97
+ const storagesFinished = await Promise.all([this.#requestLoader.isFinished(), requestManager.isFinished()]);
98
+ return storagesFinished.every(Boolean);
99
+ }
100
+ /**
101
+ * @inheritdoc
102
+ */
103
+ async isEmpty() {
104
+ const requestManager = await this.getRequestManager();
105
+ const storagesEmpty = await Promise.all([this.#requestLoader.isEmpty(), requestManager.isEmpty()]);
106
+ return storagesEmpty.every(Boolean);
107
+ }
108
+ /**
109
+ * @inheritdoc
110
+ */
111
+ async getHandledCount() {
112
+ // Since one of the stores needs to have priority when both are present, we query the request manager - the request loader will first be dumped into the manager and then left empty.
113
+ return (await this.getRequestManager()).getHandledCount();
114
+ }
115
+ /**
116
+ * @inheritdoc
117
+ */
118
+ async getTotalCount() {
119
+ const requestManager = await this.getRequestManager();
120
+ const [managerTotal, loaderTotal] = await Promise.all([
121
+ requestManager.getTotalCount(),
122
+ // count only pending to avoid double counting, requests marked as "handled" have been moved to requestManager
123
+ this.#requestLoader.getPendingCount(),
124
+ ]);
125
+ return managerTotal + loaderTotal;
126
+ }
127
+ /**
128
+ * @inheritdoc
129
+ */
130
+ async getPendingCount() {
131
+ const requestManager = await this.getRequestManager();
132
+ const [managerPending, loaderPending] = await Promise.all([
133
+ requestManager.getPendingCount(),
134
+ this.#requestLoader.getPendingCount(),
135
+ ]);
136
+ return managerPending + loaderPending;
137
+ }
138
+ /**
139
+ * @inheritdoc
140
+ */
141
+ async *[Symbol.asyncIterator]() {
142
+ while (true) {
143
+ const req = await this.fetchNextRequest();
144
+ if (!req)
145
+ break;
146
+ yield req;
147
+ }
148
+ }
149
+ /**
150
+ * @inheritdoc
151
+ */
152
+ async markRequestAsHandled(request) {
153
+ return (await this.getRequestManager()).markRequestAsHandled(request);
154
+ }
155
+ /**
156
+ * @inheritdoc
157
+ */
158
+ async reclaimRequest(request, options) {
159
+ return (await this.getRequestManager()).reclaimRequest(request, options);
160
+ }
161
+ /**
162
+ * @inheritdoc
163
+ */
164
+ async addRequest(requestLike, options) {
165
+ return (await this.getRequestManager()).addRequest(requestLike, options);
166
+ }
167
+ /**
168
+ * @inheritdoc
169
+ */
170
+ async addRequestsBatched(requests, options) {
171
+ return (await this.getRequestManager()).addRequestsBatched(requests, options);
172
+ }
173
+ /**
174
+ * Persists the state of the underlying read-only loader, if it supports persistence.
175
+ * @inheritdoc
176
+ */
177
+ async persistState() {
178
+ await this.#requestLoader.persistState?.();
179
+ }
180
+ /**
181
+ * Purges the writable request manager so the tandem can be reused (e.g. across repeated `crawler.run()` calls).
182
+ * The read-only loader is immutable and cannot be purged, so only the manager side is reset.
183
+ * @inheritdoc
184
+ */
185
+ async purge() {
186
+ await (await this.getRequestManager()).purge?.();
187
+ }
188
+ /**
189
+ * Forwards the hint to the writable request manager — that is where requests are fetched from and
190
+ * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
191
+ * @inheritdoc
192
+ */
193
+ async setExpectedRequestProcessingTimeSecs(secs) {
194
+ this.#expectedRequestProcessingSecs = secs;
195
+ await this.#resolvedRequestManager?.setExpectedRequestProcessingTimeSecs?.(secs);
196
+ }
197
+ }