@crawlee/core 4.0.0-beta.20 → 4.0.0-beta.200

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 (270) hide show
  1. package/README.md +14 -14
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +88 -227
  5. package/configuration.js +162 -226
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +40 -19
  9. package/errors.js +53 -28
  10. package/events/event_manager.d.ts +35 -9
  11. package/events/event_manager.js +12 -13
  12. package/events/index.d.ts +1 -1
  13. package/events/index.js +0 -1
  14. package/events/local_event_manager.d.ts +15 -3
  15. package/events/local_event_manager.js +39 -13
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +7 -11
  19. package/index.js +8 -10
  20. package/internal.d.ts +8 -0
  21. package/internal.js +9 -0
  22. package/iterables.d.ts +79 -0
  23. package/iterables.js +134 -0
  24. package/log.d.ts +77 -1
  25. package/log.js +134 -1
  26. package/memory-storage/consts.d.ts +4 -0
  27. package/memory-storage/consts.js +4 -0
  28. package/memory-storage/index.d.ts +1 -0
  29. package/memory-storage/index.js +1 -0
  30. package/memory-storage/memory-storage.d.ts +43 -0
  31. package/memory-storage/memory-storage.js +158 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +56 -0
  37. package/memory-storage/resource-clients/key-value-store.js +180 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned_or_injected.d.ts +58 -0
  43. package/owned_or_injected.js +98 -0
  44. package/package.json +19 -20
  45. package/proxy_configuration.d.ts +28 -135
  46. package/proxy_configuration.js +37 -146
  47. package/recoverable_state.d.ts +106 -52
  48. package/recoverable_state.js +200 -72
  49. package/request.d.ts +48 -93
  50. package/request.js +112 -230
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service_locator.d.ts +168 -0
  54. package/service_locator.js +255 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +115 -58
  58. package/storages/dataset.js +291 -149
  59. package/storages/index.d.ts +8 -9
  60. package/storages/index.js +4 -9
  61. package/storages/key_value_store.d.ts +186 -71
  62. package/storages/key_value_store.js +449 -194
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +113 -0
  65. package/storages/request_dedup_cache.d.ts +22 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +55 -131
  68. package/storages/request_list.js +272 -245
  69. package/storages/request_loader.d.ts +127 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +119 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +50 -24
  74. package/storages/request_manager_tandem.js +134 -58
  75. package/storages/request_queue.d.ts +293 -48
  76. package/storages/request_queue.js +766 -216
  77. package/storages/storage_instance_manager.d.ts +86 -0
  78. package/storages/storage_instance_manager.js +256 -0
  79. package/storages/storage_stats.d.ts +48 -0
  80. package/storages/storage_stats.js +29 -0
  81. package/storages/transaction.d.ts +271 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -285
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -195
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -60
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -55
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -204
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -346
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts.map +0 -1
  168. package/events/event_manager.js.map +0 -1
  169. package/events/index.d.ts.map +0 -1
  170. package/events/index.js.map +0 -1
  171. package/events/local_event_manager.d.ts.map +0 -1
  172. package/events/local_event_manager.js.map +0 -1
  173. package/http_clients/base-http-client.d.ts +0 -91
  174. package/http_clients/base-http-client.d.ts.map +0 -1
  175. package/http_clients/base-http-client.js +0 -44
  176. package/http_clients/base-http-client.js.map +0 -1
  177. package/http_clients/form-data-like.d.ts +0 -67
  178. package/http_clients/form-data-like.d.ts.map +0 -1
  179. package/http_clients/form-data-like.js +0 -5
  180. package/http_clients/form-data-like.js.map +0 -1
  181. package/http_clients/got-scraping-http-client.d.ts +0 -22
  182. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  183. package/http_clients/got-scraping-http-client.js +0 -116
  184. package/http_clients/got-scraping-http-client.js.map +0 -1
  185. package/http_clients/index.d.ts +0 -3
  186. package/http_clients/index.d.ts.map +0 -1
  187. package/http_clients/index.js +0 -3
  188. package/http_clients/index.js.map +0 -1
  189. package/index.d.ts.map +0 -1
  190. package/index.js.map +0 -1
  191. package/log.d.ts.map +0 -1
  192. package/log.js.map +0 -1
  193. package/proxy_configuration.d.ts.map +0 -1
  194. package/proxy_configuration.js.map +0 -1
  195. package/recoverable_state.d.ts.map +0 -1
  196. package/recoverable_state.js.map +0 -1
  197. package/request.d.ts.map +0 -1
  198. package/request.js.map +0 -1
  199. package/router.d.ts +0 -134
  200. package/router.d.ts.map +0 -1
  201. package/router.js +0 -164
  202. package/router.js.map +0 -1
  203. package/serialization.d.ts.map +0 -1
  204. package/serialization.js.map +0 -1
  205. package/session_pool/consts.d.ts +0 -4
  206. package/session_pool/consts.d.ts.map +0 -1
  207. package/session_pool/consts.js +0 -4
  208. package/session_pool/consts.js.map +0 -1
  209. package/session_pool/errors.d.ts +0 -8
  210. package/session_pool/errors.d.ts.map +0 -1
  211. package/session_pool/errors.js +0 -12
  212. package/session_pool/errors.js.map +0 -1
  213. package/session_pool/events.d.ts +0 -3
  214. package/session_pool/events.d.ts.map +0 -1
  215. package/session_pool/events.js +0 -3
  216. package/session_pool/events.js.map +0 -1
  217. package/session_pool/index.d.ts +0 -6
  218. package/session_pool/index.d.ts.map +0 -1
  219. package/session_pool/index.js +0 -6
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts +0 -203
  222. package/session_pool/session.d.ts.map +0 -1
  223. package/session_pool/session.js +0 -278
  224. package/session_pool/session.js.map +0 -1
  225. package/session_pool/session_pool.d.ts +0 -258
  226. package/session_pool/session_pool.d.ts.map +0 -1
  227. package/session_pool/session_pool.js +0 -387
  228. package/session_pool/session_pool.js.map +0 -1
  229. package/storages/access_checking.d.ts +0 -13
  230. package/storages/access_checking.d.ts.map +0 -1
  231. package/storages/access_checking.js +0 -14
  232. package/storages/access_checking.js.map +0 -1
  233. package/storages/dataset.d.ts.map +0 -1
  234. package/storages/dataset.js.map +0 -1
  235. package/storages/index.d.ts.map +0 -1
  236. package/storages/index.js.map +0 -1
  237. package/storages/key_value_store.d.ts.map +0 -1
  238. package/storages/key_value_store.js.map +0 -1
  239. package/storages/request_list.d.ts.map +0 -1
  240. package/storages/request_list.js.map +0 -1
  241. package/storages/request_list_adapter.d.ts +0 -58
  242. package/storages/request_list_adapter.d.ts.map +0 -1
  243. package/storages/request_list_adapter.js +0 -81
  244. package/storages/request_list_adapter.js.map +0 -1
  245. package/storages/request_manager_tandem.d.ts.map +0 -1
  246. package/storages/request_manager_tandem.js.map +0 -1
  247. package/storages/request_provider.d.ts +0 -371
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -585
  250. package/storages/request_provider.js.map +0 -1
  251. package/storages/request_queue.d.ts.map +0 -1
  252. package/storages/request_queue.js.map +0 -1
  253. package/storages/request_queue_v2.d.ts +0 -87
  254. package/storages/request_queue_v2.d.ts.map +0 -1
  255. package/storages/request_queue_v2.js +0 -438
  256. package/storages/request_queue_v2.js.map +0 -1
  257. package/storages/sitemap_request_list.d.ts +0 -245
  258. package/storages/sitemap_request_list.d.ts.map +0 -1
  259. package/storages/sitemap_request_list.js +0 -430
  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/typedefs.d.ts.map +0 -1
  268. package/typedefs.js.map +0 -1
  269. package/validators.d.ts.map +0 -1
  270. package/validators.js.map +0 -1
@@ -0,0 +1,127 @@
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
+ * A request source's own availability, in a single answer.
7
+ *
8
+ * - `ready` — the next {@link IRequestLoader.fetchNextRequest} is expected to hand something over.
9
+ * - `waiting` — nothing to fetch right now, but the source is not done: requests are in progress, are being
10
+ * added in the background, or are held back until `readyAt`.
11
+ * - `stalled` — the source holds requests it cannot make progress on. Only a manager that paces its own
12
+ * dispatch can reach this; see {@link ThrottlingRequestManager}.
13
+ * - `finished` — everything has been handled.
14
+ */
15
+ export type RequestSourceStatus = {
16
+ status: 'ready';
17
+ } | {
18
+ status: 'waiting';
19
+ /**
20
+ * A `Date.now()` timestamp at which the source expects to become `ready`. Absent when the wait has
21
+ * no clock (an in-progress request, a background add), leaving a consumer to poll.
22
+ */
23
+ readyAt?: number;
24
+ } | {
25
+ status: 'stalled';
26
+ reason: string;
27
+ } | {
28
+ status: 'finished';
29
+ };
30
+ /** Loaders never stall — only a manager that paces its own dispatch can. */
31
+ export type RequestLoaderStatus = Exclude<RequestSourceStatus, {
32
+ status: 'stalled';
33
+ }>;
34
+ /**
35
+ * Combines two request sources' statuses, with the precedence `ready` > `stalled` > `waiting` > `finished`.
36
+ *
37
+ * Binary rather than variadic on purpose: it is on the task loop's probe path and folding a pair allocates
38
+ * nothing.
39
+ *
40
+ * @internal
41
+ */
42
+ export declare function joinRequestSourceStatuses(a: RequestSourceStatus, b: RequestSourceStatus): RequestSourceStatus;
43
+ /**
44
+ * An abstract interface defining a read-only stream of requests to crawl.
45
+ *
46
+ * Request loaders are used to manage and provide access to a storage of crawling requests.
47
+ *
48
+ * Key responsibilities:
49
+ * - Fetching the next request to be processed.
50
+ * - Marking requests as handled once they are no longer in progress.
51
+ * - Managing state information such as the total and handled request counts.
52
+ *
53
+ * ## Request lifecycle contract
54
+ *
55
+ * Every request returned by {@link IRequestLoader.fetchNextRequest} is considered **in progress**
56
+ * until it is passed to {@link IRequestLoader.markRequestAsHandled}. Once you fetch a request, you are
57
+ * obligated to eventually mark it as handled — there is no way to hand a request back to a loader
58
+ * (only an {@link IRequestManager} can reclaim requests for a retry). "Handled" therefore means
59
+ * "finished with this request", whether processing succeeded or was abandoned after exhausting retries.
60
+ *
61
+ * Honoring this contract matters for three reasons:
62
+ * - **Restarts and migrations:** loaders that persist their state (such as {@link RequestList})
63
+ * treat in-progress requests as interrupted and re-serve them after a restart. A request that is fetched
64
+ * but never marked handled will be crawled again.
65
+ * - **Termination detection:** {@link IRequestLoader.checkReadiness} only reports `finished` once nothing is
66
+ * in progress. Leaving a request unmarked keeps the crawler running indefinitely.
67
+ * - **Bookkeeping:** the handled and pending counts are derived from the set of in-progress requests, so
68
+ * skipping {@link IRequestLoader.markRequestAsHandled} corrupts {@link IRequestLoader.getHandledCount}
69
+ * and {@link IRequestLoader.getPendingCount}.
70
+ *
71
+ * Concrete implementations such as {@link RequestList} or {@link SitemapRequestLoader} build on this interface.
72
+ * The {@link IRequestManager} interface extends it with the capability to enqueue and reclaim requests.
73
+ */
74
+ export interface IRequestLoader {
75
+ /**
76
+ * Returns an approximation of the total number of requests in the loader (i.e. pending + handled).
77
+ */
78
+ getTotalCount(): Promise<number>;
79
+ /**
80
+ * Returns an approximation of the number of pending requests in the loader.
81
+ */
82
+ getPendingCount(): Promise<number>;
83
+ /**
84
+ * Returns the number of requests in the loader that have been handled.
85
+ */
86
+ getHandledCount(): Promise<number>;
87
+ /**
88
+ * Reports whether the loader has a request to hand over, is waiting on one, or is done — see
89
+ * {@link RequestSourceStatus}.
90
+ *
91
+ * A consumer's task loop is gated on this, so implementations MUST answer `ready` before evaluating
92
+ * anything else. `finished` may arrive late behind distributed storage, but it is never wrong.
93
+ */
94
+ checkReadiness(): Promise<RequestSourceStatus>;
95
+ /**
96
+ * Gets the next {@link Request} to process, or `null` if there are no more pending requests.
97
+ *
98
+ * The returned request is marked as **in progress** and remains so until it is passed to
99
+ * {@link IRequestLoader.markRequestAsHandled}. The caller is responsible for eventually marking
100
+ * every fetched request as handled; otherwise the loader never considers itself finished and the
101
+ * request may be re-served after a restart. See the request lifecycle contract on {@link IRequestLoader}.
102
+ */
103
+ fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
104
+ /**
105
+ * Can be used to iterate over the loader instance in a `for await .. of` loop.
106
+ * Provides an alternative for the repeated use of `fetchNextRequest`.
107
+ */
108
+ [Symbol.asyncIterator](): AsyncGenerator<Request>;
109
+ /**
110
+ * Marks a request previously returned by {@link IRequestLoader.fetchNextRequest} as handled,
111
+ * removing it from the set of in-progress requests.
112
+ *
113
+ * Call this once you are done with the request — whether processing succeeded or was abandoned after
114
+ * exhausting retries. Because a loader cannot take a request back, marking it handled is the only way to
115
+ * signal completion; failing to do so prevents {@link IRequestLoader.checkReadiness} from ever reporting
116
+ * `finished` and skews the handled and pending counts. See the request lifecycle contract on
117
+ * {@link IRequestLoader}.
118
+ */
119
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
120
+ /**
121
+ * Combines the loader with a request manager to support adding and reclaiming requests.
122
+ *
123
+ * @param requestManager Request manager to combine the loader with. If not provided, the default
124
+ * {@link RequestQueue} is used.
125
+ */
126
+ toTandem?(requestManager?: IRequestManager): Promise<IRequestManager>;
127
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Combines two request sources' statuses, with the precedence `ready` > `stalled` > `waiting` > `finished`.
3
+ *
4
+ * Binary rather than variadic on purpose: it is on the task loop's probe path and folding a pair allocates
5
+ * nothing.
6
+ *
7
+ * @internal
8
+ */
9
+ export function joinRequestSourceStatuses(a, b) {
10
+ if (a.status === 'ready') {
11
+ return a;
12
+ }
13
+ if (b.status === 'ready') {
14
+ return b;
15
+ }
16
+ // `ready` outranking `stalled` masks a stalled source while the other still has work. That is parity with
17
+ // the crawler before this was a single answer: the stall check was only reached from `isFinishedFunction`,
18
+ // which the task loop calls only when nothing is in flight and nothing is ready. "Fixing" the masking
19
+ // turns a crawl that is progressing elsewhere into a `PersistentRateLimitError`. `stalled` outranking
20
+ // `waiting` is the same parity - that call site fired regardless of other domains' clocks.
21
+ if (a.status === 'stalled') {
22
+ return a;
23
+ }
24
+ if (b.status === 'stalled') {
25
+ return b;
26
+ }
27
+ if (a.status === 'waiting') {
28
+ // The earlier of the two known wake-up times - unknown only if neither source announced one.
29
+ if (b.status !== 'waiting' || b.readyAt === undefined) {
30
+ return a;
31
+ }
32
+ return a.readyAt !== undefined && a.readyAt <= b.readyAt ? a : b;
33
+ }
34
+ // `a` is finished, so `b` decides.
35
+ return b;
36
+ }
@@ -0,0 +1,119 @@
1
+ import type { LiteralUnion } from 'type-fest';
2
+ import type { Request, Source } from '../request.js';
3
+ import type { IRequestLoader } from './request_loader.js';
4
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
5
+ export type RequestsLike = AsyncIterable<Source | string> | Iterable<Source | string> | (Source | string)[];
6
+ /**
7
+ * Extends the read-only {@link IRequestLoader} interface with the capability to enqueue new requests
8
+ * and reclaim failed ones.
9
+ */
10
+ export interface IRequestManager extends IRequestLoader {
11
+ /**
12
+ * Reclaims request to the provider if its processing failed.
13
+ * The request will be returned by some subsequent `fetchNextRequest()` call.
14
+ */
15
+ reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
16
+ addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
17
+ addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
18
+ /**
19
+ * Remove all requests from the queue but keep the queue itself, resetting it
20
+ * so it can be reused (e.g. across multiple `crawler.run()` calls).
21
+ *
22
+ * Implementations that do not support purging may leave this `undefined`.
23
+ */
24
+ purge?(): Promise<void>;
25
+ /**
26
+ * Tells the manager how long a consumer expects to hold a request fetched via `fetchNextRequest()`
27
+ * before marking it handled or reclaiming it (typically the request-handler timeout plus padding).
28
+ *
29
+ * Managers backed by a storage backend that reserves requests via locking use this to avoid handing
30
+ * the same request out again while it is still being processed. Implementations that do not need
31
+ * this hint may leave it `undefined`.
32
+ */
33
+ setExpectedRequestProcessingTimeSecs?(secs: number): Promise<void>;
34
+ /**
35
+ * Records something said about the pace requests should go out at, so that a manager which paces its own
36
+ * dispatch can hold requests back.
37
+ *
38
+ * Required rather than optional, so that a wrapping manager always forwards it and a pacer nested in a
39
+ * composition still receives it; a manager that does not pace returns `false`.
40
+ *
41
+ * @returns `true` if anything in the composition took responsibility for the signal.
42
+ */
43
+ recordPacingSignal(signal: PacingSignal): boolean;
44
+ /**
45
+ * Extends the lock on a request previously handed out by `fetchNextRequest()` and still being
46
+ * processed, on storage backends that reserve requests via locking (e.g. via
47
+ * {@link CrawlingContext.extendTimeout|`context.extendTimeout`}).
48
+ *
49
+ * @returns `true` when the lock was prolonged, `false` when this manager does not lock
50
+ * requests or no longer holds this one; non-locking implementations may leave it `undefined`,
51
+ * which callers treat as `false`.
52
+ */
53
+ extendRequestProcessingTimeSecs?(request: Request, secs: number): Promise<boolean>;
54
+ }
55
+ /**
56
+ * How much of the URL space a {@link PacingSignal} covers.
57
+ *
58
+ * Open on purpose: `'hostname'` and `'registrableDomain'` are what Crawlee's own reporters send and what
59
+ * {@link ThrottlingRequestManager} understands, but any string is accepted, so a pacer keyed on something
60
+ * else can be reported to in its own vocabulary.
61
+ */
62
+ export type PacingScope = LiteralUnion<'hostname' | 'registrableDomain', string>;
63
+ /**
64
+ * Something said about the pace requests should go out at, reported to a request manager through
65
+ * {@link IRequestManager.recordPacingSignal}.
66
+ *
67
+ * One shape rather than a method per channel: a pacing manager switches on `reason`, a wrapping one forwards the
68
+ * value without knowing what is in it, and a new kind of signal costs the interface nothing. The `url` travels
69
+ * inside the value because the crawl-wide variant has none. Nothing here names the mechanism a signal came
70
+ * from - status codes, headers and robots.txt are the crawler's business - and every delay is in milliseconds.
71
+ *
72
+ * ## Scope
73
+ *
74
+ * A manager may apply a signal to a **wider** scope than it was given - a floor that holds for one host still
75
+ * holds when a whole site is paced by it - but never to a narrower one, which would leave some of the URLs the
76
+ * signal covers running unpaced. A manager that can only do the latter, or that does not recognise the scope at
77
+ * all, MUST throw rather than quietly under-apply it.
78
+ */
79
+ export type PacingSignal = {
80
+ /**
81
+ * The source turned a request away because we were going too fast — an HTTP 429 or 503, an exhausted
82
+ * quota. Reactive and transient: a pacer typically backs off while refusals continue, and lets that
83
+ * decay once they stop.
84
+ */
85
+ reason: 'rateLimited';
86
+ /** The URL that was turned away. */
87
+ url: string;
88
+ /** How long the source asked us to wait before trying again, if it said. */
89
+ waitMs?: number;
90
+ /**
91
+ * How far this refusal reaches, if the reporter can tell — a 429 rarely says. Left out, it asks the
92
+ * manager to apply the signal however it happens to group requests.
93
+ */
94
+ scope?: PacingScope;
95
+ } | {
96
+ /**
97
+ * The source declared a standing floor on how often it may be requested — a robots.txt `Crawl-delay`,
98
+ * a documented quota. A property of the source rather than of the run, so a pacer keeps it for the
99
+ * whole crawl.
100
+ */
101
+ reason: 'minInterval';
102
+ /** A URL of the source that declared the interval. */
103
+ url: string;
104
+ /** The declared minimum interval between two requests to the source. */
105
+ intervalMs: number;
106
+ /** Required, since whoever declares an interval knows what it applies to. */
107
+ scope: PacingScope;
108
+ } | {
109
+ /**
110
+ * A standing floor under the pace of **every** domain the manager dispatches to, declared by whoever
111
+ * owns the crawl rather than by a source — a crawler's `sameDomainDelaySecs`. A manager that paces only
112
+ * some of its domains MUST throw rather than under-apply it.
113
+ */
114
+ reason: 'minIntervalEverywhere';
115
+ /** The declared minimum interval between two requests to any one source. */
116
+ intervalMs: number;
117
+ /** At what granularity the floor applies. */
118
+ scope: PacingScope;
119
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,49 +1,56 @@
1
1
  import type { Dictionary } from '@crawlee/types';
2
2
  import type { Request, Source } from '../request.js';
3
- import type { IRequestList } from './request_list.js';
4
- import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, IRequestManager, RequestQueueOperationInfo, RequestQueueOperationOptions, RequestsLike } from './request_provider.js';
3
+ import type { IRequestLoader, RequestSourceStatus } from './request_loader.js';
4
+ import type { IRequestManager, PacingSignal, RequestsLike } from './request_manager.js';
5
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
5
6
  /**
6
- * A request manager that combines a RequestList and a RequestQueue.
7
- * It first reads requests from the RequestList and then, when needed,
8
- * transfers them in batches to the RequestQueue.
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.
9
10
  */
10
11
  export declare class RequestManagerTandem implements IRequestManager {
11
- private log;
12
- private requestList;
13
- private requestQueue;
14
- constructor(requestList: IRequestList, requestQueue: IRequestManager);
12
+ #private;
15
13
  /**
16
- * Transfers a batch of requests from the RequestList to the RequestQueue.
17
- * Handles both successful transfers and failures appropriately.
18
- * @private
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}).
19
18
  */
20
- private transferNextBatchToQueue;
19
+ constructor(requestLoader: IRequestLoader, requestManager: IRequestManager | (() => IRequestManager | Promise<IRequestManager>));
21
20
  /**
22
- * Fetches the next request from the RequestQueue. If the queue is empty and the RequestList
23
- * is not finished, it will transfer a batch of requests from the list to the queue first.
24
- * @inheritdoc
21
+ * Resolves the writable request manager, opening it lazily (via the factory) on first use and memoizing the result.
25
22
  */
26
- fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
23
+ private getRequestManager;
24
+ /**
25
+ * Transfers a single request from the read-only loader to the writable manager.
26
+ * If the transfer fails, the request is dropped (and logged) rather than reclaimed.
27
+ *
28
+ * @returns `true` if a request was successfully transferred (or there was nothing to transfer), and `false` if a
29
+ * transfer was attempted but failed - in which case the caller should not fetch from the manager this round.
30
+ */
31
+ private transferNextRequestToQueue;
27
32
  /**
33
+ * Fetches the next request, transferring one from the loader first if the loader still has work.
28
34
  * @inheritdoc
29
35
  */
30
- isFinished(): Promise<boolean>;
36
+ fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
31
37
  /**
38
+ * The loader and the manager read as one source.
32
39
  * @inheritdoc
33
40
  */
34
- isEmpty(): Promise<boolean>;
41
+ checkReadiness(): Promise<RequestSourceStatus>;
35
42
  /**
36
43
  * @inheritdoc
37
44
  */
38
- handledCount(): Promise<number>;
45
+ getHandledCount(): Promise<number>;
39
46
  /**
40
47
  * @inheritdoc
41
48
  */
42
- getTotalCount(): number;
49
+ getTotalCount(): Promise<number>;
43
50
  /**
44
51
  * @inheritdoc
45
52
  */
46
- getPendingCount(): number;
53
+ getPendingCount(): Promise<number>;
47
54
  /**
48
55
  * @inheritdoc
49
56
  */
@@ -51,7 +58,7 @@ export declare class RequestManagerTandem implements IRequestManager {
51
58
  /**
52
59
  * @inheritdoc
53
60
  */
54
- markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
61
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
55
62
  /**
56
63
  * @inheritdoc
57
64
  */
@@ -64,5 +71,24 @@ export declare class RequestManagerTandem implements IRequestManager {
64
71
  * @inheritdoc
65
72
  */
66
73
  addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
74
+ /**
75
+ * Purges the writable request manager so the tandem can be reused (e.g. across repeated `crawler.run()` calls).
76
+ * The read-only loader is immutable and cannot be purged, so only the manager side is reset.
77
+ * @inheritdoc
78
+ */
79
+ purge(): Promise<void>;
80
+ /**
81
+ * Forwards the hint to the writable request manager — that is where requests are fetched from and
82
+ * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
83
+ * @inheritdoc
84
+ */
85
+ setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
86
+ /**
87
+ * Forwards a pacing signal to the writable manager - the loader side is read-only and dispatches nothing of
88
+ * its own. Only a resolved manager is signalled; the tandem will not open a queue to answer a question about
89
+ * pacing.
90
+ * @inheritdoc
91
+ */
92
+ recordPacingSignal(signal: PacingSignal): boolean;
93
+ extendRequestProcessingTimeSecs(request: Request, secs: number): Promise<boolean>;
67
94
  }
68
- //# sourceMappingURL=request_manager_tandem.d.ts.map
@@ -1,89 +1,137 @@
1
- import { log } from '../log.js';
1
+ import { serviceLocator } from '../service_locator.js';
2
+ import { joinRequestSourceStatuses } from './request_loader.js';
2
3
  /**
3
- * A request manager that combines a RequestList and a RequestQueue.
4
- * It first reads requests from the RequestList and then, when needed,
5
- * transfers them in batches to the RequestQueue.
4
+ * A request manager that combines a {@link IRequestLoader} (such as a `RequestList`) with a writable
5
+ * {@link IRequestManager} (such as a `RequestQueue`).
6
+ * It first reads requests from the loader and then, when needed, transfers them in batches to the manager.
6
7
  */
7
8
  export class RequestManagerTandem {
8
- log;
9
- requestList;
10
- requestQueue;
11
- constructor(requestList, requestQueue) {
12
- this.log = log.child({ prefix: 'RequestManagerTandem' });
13
- this.requestList = requestList;
14
- this.requestQueue = requestQueue;
9
+ #log;
10
+ #requestLoader;
11
+ #requestManagerPromise;
12
+ #resolvedRequestManager;
13
+ #requestManagerFactory;
14
+ /**
15
+ * The latest expected request-processing time hinted via {@link setExpectedRequestProcessingTimeSecs}.
16
+ * Remembered so it can be applied to the writable manager once it is lazily resolved.
17
+ */
18
+ #expectedRequestProcessingSecs;
19
+ /**
20
+ * @param requestLoader The read-only loader to read requests from first.
21
+ * @param requestManager The writable manager to transfer requests into and enqueue new ones. May be passed as a
22
+ * factory function so that the tandem can be constructed synchronously and the manager opened lazily on first use
23
+ * (e.g. a lazily-opened default {@link RequestQueue}).
24
+ */
25
+ constructor(requestLoader, requestManager) {
26
+ this.#log = serviceLocator.getLogger().child({ prefix: 'RequestManagerTandem' });
27
+ this.#requestLoader = requestLoader;
28
+ if (typeof requestManager === 'function') {
29
+ this.#requestManagerFactory = requestManager;
30
+ }
31
+ else {
32
+ // Nothing to open, so mark it resolved up front - synchronous pacing signals can then reach it.
33
+ this.#resolvedRequestManager = requestManager;
34
+ this.#requestManagerFactory = () => requestManager;
35
+ }
36
+ }
37
+ /**
38
+ * Resolves the writable request manager, opening it lazily (via the factory) on first use and memoizing the result.
39
+ */
40
+ async getRequestManager() {
41
+ if (this.#resolvedRequestManager === undefined) {
42
+ this.#requestManagerPromise ??= Promise.resolve(this.#requestManagerFactory());
43
+ this.#resolvedRequestManager = await this.#requestManagerPromise;
44
+ // Apply any hint received before the manager was resolved.
45
+ if (this.#expectedRequestProcessingSecs !== undefined) {
46
+ await this.#resolvedRequestManager.setExpectedRequestProcessingTimeSecs?.(this.#expectedRequestProcessingSecs);
47
+ }
48
+ }
49
+ return this.#resolvedRequestManager;
15
50
  }
16
51
  /**
17
- * Transfers a batch of requests from the RequestList to the RequestQueue.
18
- * Handles both successful transfers and failures appropriately.
19
- * @private
52
+ * Transfers a single request from the read-only loader to the writable manager.
53
+ * If the transfer fails, the request is dropped (and logged) rather than reclaimed.
54
+ *
55
+ * @returns `true` if a request was successfully transferred (or there was nothing to transfer), and `false` if a
56
+ * transfer was attempted but failed - in which case the caller should not fetch from the manager this round.
20
57
  */
21
- async transferNextBatchToQueue() {
22
- const request = await this.requestList.fetchNextRequest();
58
+ async transferNextRequestToQueue() {
59
+ const request = await this.#requestLoader.fetchNextRequest();
23
60
  if (request === null) {
24
- return;
61
+ return true;
25
62
  }
63
+ const requestManager = await this.getRequestManager();
26
64
  try {
27
- await this.requestQueue.addRequest(request, { forefront: true });
65
+ await requestManager.addRequest(request, { forefront: true });
66
+ return true;
28
67
  }
29
68
  catch (error) {
30
- // If requestQueue.addRequest() fails here then we must reclaim it back to
31
- // the RequestList because probably it's not yet in the queue!
32
- this.log.error('Adding of request from the RequestList to the RequestQueue failed, reclaiming request back to the list.', { request });
33
- await this.requestList.reclaimRequest(request);
34
- return;
69
+ this.#log.exception(error, 'Adding request from the RequestLoader to the RequestManager failed, the request has been dropped.', { url: request.url, uniqueKey: request.uniqueKey });
70
+ return false;
71
+ }
72
+ finally {
73
+ // Mark it as handled so that the request doesn't get stuck in the `inProgress` state in the loader.
74
+ await this.#requestLoader.markRequestAsHandled(request);
35
75
  }
36
- await this.requestList.markRequestHandled(request);
37
76
  }
38
77
  /**
39
- * Fetches the next request from the RequestQueue. If the queue is empty and the RequestList
40
- * is not finished, it will transfer a batch of requests from the list to the queue first.
78
+ * Fetches the next request, transferring one from the loader first if the loader still has work.
41
79
  * @inheritdoc
42
80
  */
43
81
  async fetchNextRequest() {
44
- // First, try to transfer a request from the requestList
45
- const [listEmpty, listFinished] = await Promise.all([
46
- this.requestList.isEmpty(),
47
- this.requestList.isFinished(),
48
- ]);
49
- if (!listEmpty && !listFinished) {
50
- await this.transferNextBatchToQueue();
82
+ // Only the loader's own state decides this: a manager waiting out a backoff must not freeze the
83
+ // loader's unrelated requests for the length of it.
84
+ if ((await this.#requestLoader.checkReadiness()).status === 'ready') {
85
+ // If the transfer failed, the request was dropped; don't fetch from the manager this round (matching
86
+ // crawlee-python behaviour). The next `fetchNextRequest()` call will pick up where we left off.
87
+ if (!(await this.transferNextRequestToQueue())) {
88
+ return null;
89
+ }
51
90
  }
52
- // Try to fetch from queue after potential transfer
53
- return this.requestQueue.fetchNextRequest();
54
- }
55
- /**
56
- * @inheritdoc
57
- */
58
- async isFinished() {
59
- const storagesFinished = await Promise.all([this.requestList.isFinished(), this.requestQueue.isFinished()]);
60
- return storagesFinished.every(Boolean);
91
+ // Try to fetch from manager after the transfer
92
+ return (await this.getRequestManager()).fetchNextRequest();
61
93
  }
62
94
  /**
95
+ * The loader and the manager read as one source.
63
96
  * @inheritdoc
64
97
  */
65
- async isEmpty() {
66
- const storagesEmpty = await Promise.all([this.requestList.isEmpty(), this.requestQueue.isEmpty()]);
67
- return storagesEmpty.every(Boolean);
98
+ async checkReadiness() {
99
+ const requestManager = await this.getRequestManager();
100
+ const [loaderStatus, managerStatus] = await Promise.all([
101
+ this.#requestLoader.checkReadiness(),
102
+ requestManager.checkReadiness(),
103
+ ]);
104
+ return joinRequestSourceStatuses(loaderStatus, managerStatus);
68
105
  }
69
106
  /**
70
107
  * @inheritdoc
71
108
  */
72
- async handledCount() {
73
- // Since one of the stores needs to have priority when both are present, we query the request queue - the request list will first be dumped into the queue and then left empty.
74
- return await this.requestQueue.handledCount();
109
+ async getHandledCount() {
110
+ // 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.
111
+ return (await this.getRequestManager()).getHandledCount();
75
112
  }
76
113
  /**
77
114
  * @inheritdoc
78
115
  */
79
- getTotalCount() {
80
- return this.requestQueue.getTotalCount();
116
+ async getTotalCount() {
117
+ const requestManager = await this.getRequestManager();
118
+ const [managerTotal, loaderTotal] = await Promise.all([
119
+ requestManager.getTotalCount(),
120
+ // count only pending to avoid double counting, requests marked as "handled" have been moved to requestManager
121
+ this.#requestLoader.getPendingCount(),
122
+ ]);
123
+ return managerTotal + loaderTotal;
81
124
  }
82
125
  /**
83
126
  * @inheritdoc
84
127
  */
85
- getPendingCount() {
86
- return this.requestQueue.getPendingCount() + this.requestList.length() - this.requestList.handledCount();
128
+ async getPendingCount() {
129
+ const requestManager = await this.getRequestManager();
130
+ const [managerPending, loaderPending] = await Promise.all([
131
+ requestManager.getPendingCount(),
132
+ this.#requestLoader.getPendingCount(),
133
+ ]);
134
+ return managerPending + loaderPending;
87
135
  }
88
136
  /**
89
137
  * @inheritdoc
@@ -99,26 +147,54 @@ export class RequestManagerTandem {
99
147
  /**
100
148
  * @inheritdoc
101
149
  */
102
- async markRequestHandled(request) {
103
- return this.requestQueue.markRequestHandled(request);
150
+ async markRequestAsHandled(request) {
151
+ return (await this.getRequestManager()).markRequestAsHandled(request);
104
152
  }
105
153
  /**
106
154
  * @inheritdoc
107
155
  */
108
156
  async reclaimRequest(request, options) {
109
- return await this.requestQueue.reclaimRequest(request, options);
157
+ return (await this.getRequestManager()).reclaimRequest(request, options);
110
158
  }
111
159
  /**
112
160
  * @inheritdoc
113
161
  */
114
162
  async addRequest(requestLike, options) {
115
- return await this.requestQueue.addRequest(requestLike, options);
163
+ return (await this.getRequestManager()).addRequest(requestLike, options);
116
164
  }
117
165
  /**
118
166
  * @inheritdoc
119
167
  */
120
168
  async addRequestsBatched(requests, options) {
121
- return await this.requestQueue.addRequestsBatched(requests, options);
169
+ return (await this.getRequestManager()).addRequestsBatched(requests, options);
170
+ }
171
+ /**
172
+ * Purges the writable request manager so the tandem can be reused (e.g. across repeated `crawler.run()` calls).
173
+ * The read-only loader is immutable and cannot be purged, so only the manager side is reset.
174
+ * @inheritdoc
175
+ */
176
+ async purge() {
177
+ await (await this.getRequestManager()).purge?.();
178
+ }
179
+ /**
180
+ * Forwards the hint to the writable request manager — that is where requests are fetched from and
181
+ * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
182
+ * @inheritdoc
183
+ */
184
+ async setExpectedRequestProcessingTimeSecs(secs) {
185
+ this.#expectedRequestProcessingSecs = secs;
186
+ await this.#resolvedRequestManager?.setExpectedRequestProcessingTimeSecs?.(secs);
187
+ }
188
+ /**
189
+ * Forwards a pacing signal to the writable manager - the loader side is read-only and dispatches nothing of
190
+ * its own. Only a resolved manager is signalled; the tandem will not open a queue to answer a question about
191
+ * pacing.
192
+ * @inheritdoc
193
+ */
194
+ recordPacingSignal(signal) {
195
+ return this.#resolvedRequestManager?.recordPacingSignal(signal) ?? false;
196
+ }
197
+ async extendRequestProcessingTimeSecs(request, secs) {
198
+ return (await this.getRequestManager()).extendRequestProcessingTimeSecs?.(request, secs) ?? false;
122
199
  }
123
200
  }
124
- //# sourceMappingURL=request_manager_tandem.js.map