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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/README.md +14 -14
  2. package/autoscaling/autoscaled_pool.d.ts +73 -177
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +364 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +98 -0
  13. package/autoscaling/load_signal.js +103 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -126
  33. package/crawlers/crawler_commons.js +1 -108
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -64
  43. package/crawlers/statistics.js +354 -165
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +61 -154
  47. package/enqueue_links/enqueue_links.js +40 -232
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +55 -28
  51. package/enqueue_links/shared.js +116 -69
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -5
  63. package/index.js +8 -4
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +77 -1
  67. package/log.js +104 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +44 -0
  73. package/memory-storage/memory-storage.js +160 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +106 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +199 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +407 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +13 -12
  87. package/proxy_configuration.d.ts +22 -128
  88. package/proxy_configuration.js +32 -144
  89. package/recoverable_state.d.ts +83 -51
  90. package/recoverable_state.js +163 -72
  91. package/request.d.ts +57 -16
  92. package/request.js +130 -69
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +39 -89
  108. package/session_pool/session.js +102 -159
  109. package/session_pool/session_pool.d.ts +67 -91
  110. package/session_pool/session_pool.js +196 -187
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +109 -56
  114. package/storages/dataset.js +284 -149
  115. package/storages/index.d.ts +9 -9
  116. package/storages/index.js +7 -9
  117. package/storages/key_value_store.d.ts +183 -48
  118. package/storages/key_value_store.js +444 -171
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +53 -115
  124. package/storages/request_list.js +194 -167
  125. package/storages/request_loader.d.ts +133 -0
  126. package/storages/request_loader.js +36 -0
  127. package/storages/request_manager.d.ts +109 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +55 -23
  130. package/storages/request_manager_tandem.js +139 -57
  131. package/storages/request_queue.d.ts +286 -48
  132. package/storages/request_queue.js +757 -218
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +43 -91
  134. package/storages/sitemap_request_loader.js +439 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +222 -0
  140. package/storages/throttling_request_manager.js +780 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -85
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/recoverable_state.d.ts.map +0 -1
  226. package/recoverable_state.js.map +0 -1
  227. package/request.d.ts.map +0 -1
  228. package/request.js.map +0 -1
  229. package/router.d.ts.map +0 -1
  230. package/router.js.map +0 -1
  231. package/serialization.d.ts.map +0 -1
  232. package/serialization.js.map +0 -1
  233. package/session_pool/consts.d.ts.map +0 -1
  234. package/session_pool/consts.js.map +0 -1
  235. package/session_pool/errors.d.ts.map +0 -1
  236. package/session_pool/errors.js.map +0 -1
  237. package/session_pool/events.d.ts +0 -3
  238. package/session_pool/events.d.ts.map +0 -1
  239. package/session_pool/events.js +0 -3
  240. package/session_pool/events.js.map +0 -1
  241. package/session_pool/index.d.ts.map +0 -1
  242. package/session_pool/index.js.map +0 -1
  243. package/session_pool/session.d.ts.map +0 -1
  244. package/session_pool/session.js.map +0 -1
  245. package/session_pool/session_pool.d.ts.map +0 -1
  246. package/session_pool/session_pool.js.map +0 -1
  247. package/storages/access_checking.d.ts +0 -13
  248. package/storages/access_checking.d.ts.map +0 -1
  249. package/storages/access_checking.js +0 -14
  250. package/storages/access_checking.js.map +0 -1
  251. package/storages/dataset.d.ts.map +0 -1
  252. package/storages/dataset.js.map +0 -1
  253. package/storages/index.d.ts.map +0 -1
  254. package/storages/index.js.map +0 -1
  255. package/storages/key_value_store.d.ts.map +0 -1
  256. package/storages/key_value_store.js.map +0 -1
  257. package/storages/request_list.d.ts.map +0 -1
  258. package/storages/request_list.js.map +0 -1
  259. package/storages/request_list_adapter.d.ts +0 -58
  260. package/storages/request_list_adapter.d.ts.map +0 -1
  261. package/storages/request_list_adapter.js +0 -81
  262. package/storages/request_list_adapter.js.map +0 -1
  263. package/storages/request_manager_tandem.d.ts.map +0 -1
  264. package/storages/request_manager_tandem.js.map +0 -1
  265. package/storages/request_provider.d.ts +0 -371
  266. package/storages/request_provider.d.ts.map +0 -1
  267. package/storages/request_provider.js +0 -585
  268. package/storages/request_provider.js.map +0 -1
  269. package/storages/request_queue.d.ts.map +0 -1
  270. package/storages/request_queue.js.map +0 -1
  271. package/storages/request_queue_v2.d.ts +0 -87
  272. package/storages/request_queue_v2.d.ts.map +0 -1
  273. package/storages/request_queue_v2.js +0 -438
  274. package/storages/request_queue_v2.js.map +0 -1
  275. package/storages/sitemap_request_list.d.ts.map +0 -1
  276. package/storages/sitemap_request_list.js +0 -430
  277. package/storages/sitemap_request_list.js.map +0 -1
  278. package/storages/storage_manager.d.ts +0 -58
  279. package/storages/storage_manager.d.ts.map +0 -1
  280. package/storages/storage_manager.js +0 -105
  281. package/storages/storage_manager.js.map +0 -1
  282. package/storages/utils.d.ts.map +0 -1
  283. package/storages/utils.js.map +0 -1
  284. package/typedefs.d.ts.map +0 -1
  285. package/typedefs.js.map +0 -1
  286. package/validators.d.ts.map +0 -1
  287. package/validators.js.map +0 -1
@@ -1,16 +1,63 @@
1
- import { setTimeout as sleep } from 'node:timers/promises';
2
- import { REQUEST_QUEUE_HEAD_MAX_LIMIT } from '@apify/consts';
1
+ import { inspect } from 'node:util';
2
+ import { isAsyncIterable, isIterable } from '@crawlee/utils/internal';
3
+ import { downloadListOfUrls } from '@crawlee/utils';
4
+ import { z } from 'zod';
5
+ import { LruCache } from '@apify/datastructures';
6
+ import { tryCancel } from '@apify/timeout';
3
7
  import { Configuration } from '../configuration.js';
4
- import { checkStorageAccess } from './access_checking.js';
5
- import { RequestProvider } from './request_provider.js';
6
- import { API_PROCESSED_REQUESTS_DELAY_MILLIS, getRequestId, MAX_QUERIES_FOR_CONSISTENCY, QUERY_HEAD_BUFFER, QUERY_HEAD_MIN_LENGTH, STORAGE_CONSISTENCY_DELAY_MILLIS, } from './utils.js';
7
- const MAX_CACHED_REQUESTS = 1_000_000;
8
+ import { getObjectType } from '../debug.js';
9
+ import { EventType } from '../events/event_manager.js';
10
+ import { Request } from '../request.js';
11
+ import { serviceLocator } from '../service_locator.js';
12
+ import { parseArgument, schemas, validators } from '../validators.js';
13
+ import { activeStorageTransaction, rejectOperationInTransaction } from './transaction.js';
14
+ import { drainRequestBatches } from './batched_adds.js';
15
+ import { StorageStatsTracker } from './storage_stats.js';
16
+ import { resolveStorageIdentifier } from './storage_instance_manager.js';
17
+ import { getRequestId, purgeDefaultStorages } from './utils.js';
18
+ import { RequestDeduplicationCache } from './request_dedup_cache.js';
8
19
  /**
9
- * This number must be large enough so that processing of all these requests cannot be done in
10
- * a time lower than expected maximum latency of DynamoDB, but low enough not to waste too much memory.
20
+ * The maximum number of requests cached locally to avoid redundant calls to the storage backend.
11
21
  * @internal
12
22
  */
13
- const RECENTLY_HANDLED_CACHE_SIZE = 1000;
23
+ const MAX_CACHED_REQUESTS = 2_000_000;
24
+ const iterableSchema = z.custom((value) => isIterable(value) || isAsyncIterable(value), {
25
+ error: (issue) => `Expected an iterable or async iterable, got ${getObjectType(issue.input)}`,
26
+ });
27
+ const operationOptionsSchema = z.strictObject({
28
+ forefront: z.boolean().default(false),
29
+ });
30
+ const addRequestsOptionsSchema = z.strictObject({
31
+ forefront: z.boolean().default(false),
32
+ cache: z.boolean().default(true),
33
+ });
34
+ const addRequestsBatchedOptionsSchema = z.strictObject({
35
+ forefront: z.boolean().optional(),
36
+ waitForAllRequestsToBeAdded: z.boolean().default(false),
37
+ batchSize: schemas.anyNumber.default(1000),
38
+ waitBetweenBatchesMillis: schemas.anyNumber.default(1000),
39
+ maxNewRequests: schemas.anyNumber.optional(),
40
+ });
41
+ const newRequestLikeSchema = z.looseObject({
42
+ url: z.string(),
43
+ id: z.undefined().optional(),
44
+ });
45
+ const handledRequestSchema = z.looseObject({
46
+ id: z.string(),
47
+ uniqueKey: z.string(),
48
+ handledAt: z.string().optional(),
49
+ });
50
+ const reclaimedRequestSchema = z.looseObject({
51
+ id: z.string(),
52
+ uniqueKey: z.string(),
53
+ });
54
+ const uniqueKeySchema = z.string();
55
+ const openOptionsSchema = z.strictObject({
56
+ configuration: z.instanceof(Configuration).optional(),
57
+ storageBackend: validators.storageBackend.optional(),
58
+ proxyConfiguration: validators.proxyConfiguration.optional(),
59
+ httpClient: schemas.httpClient.optional(),
60
+ });
14
61
  /**
15
62
  * Represents a queue of URLs to crawl, which is used for deep crawling of websites
16
63
  * where you start with several URLs and then recursively
@@ -29,18 +76,6 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
29
76
  * Unlike {@link RequestList}, `RequestQueue` supports dynamic adding and removing of requests.
30
77
  * On the other hand, the queue is not optimized for operations that add or remove a large number of URLs in a batch.
31
78
  *
32
- * `RequestQueue` stores its data either on local disk or in the Apify Cloud,
33
- * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variable is set.
34
- *
35
- * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the queue data is stored in
36
- * that directory in an SQLite database file.
37
- *
38
- * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` is not, the data is stored in the
39
- * [Apify Request Queue](https://docs.apify.com/storage/request-queue)
40
- * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`
41
- * option to {@link RequestQueue.open} function,
42
- * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
43
- *
44
79
  * **Example usage:**
45
80
  *
46
81
  * ```javascript
@@ -56,34 +91,461 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
56
91
  * await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });
57
92
  * ```
58
93
  * @category Sources
59
- *
60
- * @deprecated RequestQueue v1 is deprecated and will be removed in the future. Please use {@link RequestQueue} instead.
61
94
  */
62
- class RequestQueue extends RequestProvider {
63
- queryQueueHeadPromise = null;
64
- inProgress = new Set();
95
+ export class RequestQueue {
96
+ id;
97
+ name;
98
+ backend;
99
+ #proxyConfiguration;
100
+ log;
101
+ #requestCache;
65
102
  /**
66
- * @internal
103
+ * Remembers the `requestId` of every request already submitted to the client — including background
104
+ * batches that `requestCache` skips — so overlapping URL sets aren't re-submitted.
105
+ * See {@link RequestDeduplicationCache} for why this is a separate, cheaper cache.
67
106
  */
68
- constructor(options, config = Configuration.getGlobalConfig()) {
69
- super({
70
- ...options,
71
- logPrefix: 'RequestQueue',
72
- recentlyHandledRequestsMaxSize: RECENTLY_HANDLED_CACHE_SIZE,
73
- requestCacheMaxSize: MAX_CACHED_REQUESTS,
74
- }, config);
107
+ #requestSeenCache;
108
+ #queuePausedForMigration = false;
109
+ #inProgressRequestBatchCount = 0;
110
+ /**
111
+ * The largest expected request-processing time (in seconds) seen so far via
112
+ * {@link setExpectedRequestProcessingTimeSecs}. Used to ensure that value is only ever raised, never
113
+ * lowered, before being forwarded to the storage backend.
114
+ */
115
+ #expectedRequestProcessingSecs = 0;
116
+ #httpClient;
117
+ #events;
118
+ #statsTracker = new StorageStatsTracker({
119
+ writeCount: 0,
120
+ headItemReadCount: 0,
121
+ });
122
+ /**
123
+ * Backend-independent usage counters tracked for this request queue (write operations and
124
+ * queue-head reads issued to the underlying storage backend). Counted per backend call.
125
+ */
126
+ get stats() {
127
+ return this.#statsTracker.current;
75
128
  }
76
129
  /**
77
130
  * @internal
78
131
  */
79
- inProgressCount() {
80
- return this.inProgress.size;
132
+ constructor(options) {
133
+ this.id = options.metadata.id;
134
+ this.name = options.metadata.name;
135
+ this.#events = serviceLocator.getEventManager();
136
+ this.backend = options.backend;
137
+ this.#proxyConfiguration = options.proxyConfiguration;
138
+ this.#requestCache = new LruCache({ maxLength: MAX_CACHED_REQUESTS });
139
+ this.#requestSeenCache = new RequestDeduplicationCache();
140
+ this.log = serviceLocator.getLogger().child({ prefix: `RequestQueue(${this.id}, ${this.name ?? 'no-name'})` });
141
+ this.#events.on(EventType.MIGRATING, async () => {
142
+ this.#queuePausedForMigration = true;
143
+ });
144
+ }
145
+ /**
146
+ * Returns the total number of requests in the queue (i.e. pending + handled).
147
+ *
148
+ * Survives restarts and actor migrations.
149
+ */
150
+ async getTotalCount() {
151
+ const { totalRequestCount } = await this.getInfo();
152
+ return totalRequestCount;
153
+ }
154
+ /**
155
+ * Returns the total number of pending requests in the queue.
156
+ *
157
+ * Survives restarts and Actor migrations.
158
+ */
159
+ async getPendingCount() {
160
+ const { totalRequestCount, handledRequestCount } = await this.getInfo();
161
+ return totalRequestCount - handledRequestCount;
162
+ }
163
+ /**
164
+ * Adds a request to the queue.
165
+ *
166
+ * If a request with the same `uniqueKey` property is already present in the queue,
167
+ * it will not be updated. You can find out whether this happened from the resulting
168
+ * {@link QueueOperationInfo} object.
169
+ *
170
+ * To add multiple requests to the queue by extracting links from a webpage,
171
+ * see the {@link enqueueLinks} helper function.
172
+ *
173
+ * @param requestLike {@link Request} object or vanilla object with request data.
174
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed Request.
175
+ * @param [options] Request queue operation options.
176
+ */
177
+ async addRequest(requestLike, options = {}) {
178
+ const transaction = activeStorageTransaction();
179
+ parseArgument(requestLike, schemas.anyObject);
180
+ const { forefront } = parseArgument(options, operationOptionsSchema);
181
+ if ('requestsFromUrl' in requestLike) {
182
+ const requests = await this.fetchRequestsFromUrl(requestLike);
183
+ const processedRequests = await this.addFetchedRequests(requestLike, requests, options);
184
+ return { ...processedRequests[0], forefront };
185
+ }
186
+ parseArgument(requestLike, newRequestLikeSchema);
187
+ const request = requestLike instanceof Request ? requestLike : new Request(requestLike);
188
+ if (transaction?.policy.requestQueue === 'deferred') {
189
+ return this.addRequestDeferred(transaction, request, forefront);
190
+ }
191
+ const cacheKey = getRequestId(request.uniqueKey);
192
+ const cachedInfo = this.#requestCache.get(cacheKey);
193
+ if (cachedInfo) {
194
+ request.id = cachedInfo.id;
195
+ this.recordRequestJournalEntry(transaction, [request], forefront, true);
196
+ return {
197
+ wasAlreadyPresent: true,
198
+ // We may assume that if request is in local cache then also the information if the
199
+ // request was already handled is there because just one client should be using one queue.
200
+ wasAlreadyHandled: cachedInfo.isHandled,
201
+ requestId: cachedInfo.id,
202
+ uniqueKey: cachedInfo.uniqueKey,
203
+ forefront,
204
+ };
205
+ }
206
+ this.#statsTracker.add('writeCount');
207
+ const { processedRequests } = await this.backend.addBatchOfRequests([request], { forefront });
208
+ this.recordRequestJournalEntry(transaction, [request], forefront, true);
209
+ const queueOperationInfo = {
210
+ ...processedRequests[0],
211
+ uniqueKey: request.uniqueKey,
212
+ forefront,
213
+ };
214
+ this.cacheRequest(cacheKey, queueOperationInfo);
215
+ this.#requestSeenCache.add(cacheKey, request.id);
216
+ return queueOperationInfo;
217
+ }
218
+ /**
219
+ * Journals an addition for introspection only; these entries are never replayed. A no-op unless the
220
+ * transaction is open, so detached and outliving writers stay out of the journal.
221
+ */
222
+ recordRequestJournalEntry(transaction, requests, forefront, writeThrough) {
223
+ if (!transaction?.isActive || requests.length === 0)
224
+ return;
225
+ transaction.recordJournalEntry({
226
+ type: 'requestQueue',
227
+ participant: this,
228
+ requests: requests.map((request) => ({
229
+ url: request.url,
230
+ uniqueKey: request.uniqueKey,
231
+ label: request.label,
232
+ })),
233
+ forefront,
234
+ writeThrough,
235
+ });
236
+ }
237
+ /**
238
+ * The requests buffered by the given transaction for this queue, keyed by `uniqueKey` — a dedup
239
+ * index derived from the transaction journal.
240
+ */
241
+ bufferedRequests(transaction) {
242
+ const buffered = new Map();
243
+ // Only `deferred` records snapshots, so scanning the journal under `writeThrough` never finds any.
244
+ if (transaction.policy.requestQueue !== 'deferred')
245
+ return buffered;
246
+ for (const entry of transaction.journal) {
247
+ if (entry.type !== 'requestQueue' || entry.participant !== this)
248
+ continue;
249
+ for (const request of entry.requests) {
250
+ if (request.snapshot !== undefined)
251
+ buffered.set(request.uniqueKey, request.snapshot);
252
+ }
253
+ }
254
+ return buffered;
255
+ }
256
+ /**
257
+ * Adds a request under the `deferred` policy: journaled now, really added by the commit replay.
258
+ * A new request's `requestId` is the local `uniqueKey` hash and is **provisional** — never write it
259
+ * to `request.id` or the dedup caches. Dedup is cheapest-first: buffer, caches, then a backend probe.
260
+ */
261
+ async addRequestDeferred(transaction, request, forefront, buffered = this.bufferedRequests(transaction)) {
262
+ // This transaction's own buffered adds; the shared caches never see them (provisional ids).
263
+ if (buffered.has(request.uniqueKey)) {
264
+ this.recordRequestJournalEntry(transaction, [request], forefront, false);
265
+ return {
266
+ wasAlreadyPresent: true,
267
+ wasAlreadyHandled: false,
268
+ requestId: getRequestId(request.uniqueKey),
269
+ uniqueKey: request.uniqueKey,
270
+ forefront,
271
+ };
272
+ }
273
+ // The caches hold real backend ids. Only *writing* provisional ids to them would be wrong;
274
+ // reading saves a probe. Same lookup as the write-through path.
275
+ const cacheKey = getRequestId(request.uniqueKey);
276
+ const cachedInfo = this.#requestCache.get(cacheKey);
277
+ const knownRequestId = cachedInfo?.id ?? this.#requestSeenCache.get(cacheKey);
278
+ if (knownRequestId) {
279
+ this.recordRequestJournalEntry(transaction, [request], forefront, false);
280
+ return {
281
+ wasAlreadyPresent: true,
282
+ // The dedup cache doesn't track the handled state; only the full record does.
283
+ wasAlreadyHandled: cachedInfo?.isHandled ?? false,
284
+ requestId: knownRequestId,
285
+ uniqueKey: request.uniqueKey,
286
+ forefront,
287
+ };
288
+ }
289
+ // The caches are bounded, so a miss is not proof of absence - probe for an accurate answer.
290
+ const existing = await this.backend.getRequest(request.uniqueKey);
291
+ if (existing) {
292
+ this.recordRequestJournalEntry(transaction, [request], forefront, false);
293
+ return {
294
+ wasAlreadyPresent: true,
295
+ wasAlreadyHandled: existing.handledAt != null,
296
+ requestId: existing.id,
297
+ uniqueKey: request.uniqueKey,
298
+ forefront,
299
+ };
300
+ }
301
+ // The entry below *is* the write, so a transaction closed during the probe must not receive it -
302
+ // pass through instead, per the closed-transaction rule. Under `deferred` that can land an
303
+ // addition a rollback would have discarded; dedup bounds that cost, silent loss is unbounded.
304
+ if (!transaction.isActive) {
305
+ return await this.addRequest(request, { forefront });
306
+ }
307
+ const snapshot = JSON.parse(JSON.stringify(request));
308
+ // Strip-list, not allow-list: every user-facing field flows through, including ones added to
309
+ // `Request` in the future. The exceptions are `id` and `handledAt`, the two backend-owned
310
+ // lifecycle fields.
311
+ delete snapshot.id;
312
+ delete snapshot.handledAt;
313
+ transaction.recordJournalEntry({
314
+ type: 'requestQueue',
315
+ participant: this,
316
+ requests: [{ url: request.url, uniqueKey: request.uniqueKey, label: request.label, snapshot }],
317
+ forefront,
318
+ writeThrough: false,
319
+ });
320
+ buffered.set(request.uniqueKey, snapshot);
321
+ return {
322
+ wasAlreadyPresent: false,
323
+ wasAlreadyHandled: false,
324
+ requestId: getRequestId(request.uniqueKey),
325
+ uniqueKey: request.uniqueKey,
326
+ forefront,
327
+ };
328
+ }
329
+ /** @internal */
330
+ async commitJournalEntries(entries) {
331
+ // Replay through `backend.addBatchOfRequests`, *not* the batched frontend wrapper - the wrapper
332
+ // resolves after the first chunk and sleeps between the rest, neither of which commit may
333
+ // inherit. One call per `forefront` flag; the order of forefront additions is arbitrary anyway.
334
+ for (const forefront of [false, true]) {
335
+ const requests = entries.flatMap((entry) => entry.type === 'requestQueue' && entry.forefront === forefront
336
+ ? // Requests without a snapshot were deduplicated or written through; nothing to replay.
337
+ entry.requests
338
+ .filter((journaled) => journaled.snapshot !== undefined)
339
+ .map((journaled) => new Request(journaled.snapshot))
340
+ : []);
341
+ if (requests.length === 0)
342
+ continue;
343
+ this.#statsTracker.add('writeCount');
344
+ const { processedRequests, unprocessedRequests } = await this.backend.addBatchOfRequests(requests, {
345
+ forefront,
346
+ });
347
+ // Only now, with the real backend-assigned ids, may the shared dedup caches be populated.
348
+ for (const processed of processedRequests) {
349
+ const cacheKey = getRequestId(processed.uniqueKey);
350
+ this.cacheRequest(cacheKey, { ...processed, forefront });
351
+ this.#requestSeenCache.add(cacheKey, processed.requestId);
352
+ }
353
+ if (unprocessedRequests.length > 0) {
354
+ // Warn and skip, rather than retry or fail. `unprocessedRequests` is what remains after
355
+ // the backend's own transient-error handling - a semantic rejection that retrying here
356
+ // would only re-poke. And failing the commit would let one malformed request hold the
357
+ // whole transaction hostage.
358
+ this.log.warning('Some requests were rejected by the request queue while committing a storage transaction and will be skipped. ' +
359
+ "This usually means the request data is malformed (e.g. an invalid 'userData' shape).", { unprocessedRequests });
360
+ }
361
+ }
362
+ }
363
+ /**
364
+ * Adds requests to the queue in batches of 25. This method will wait till all the requests are added
365
+ * to the queue before resolving. You should prefer using `queue.addRequestsBatched()` or `crawler.addRequests()`
366
+ * if you don't want to block the processing, as those methods will only wait for the initial 1000 requests,
367
+ * start processing right after that happens, and continue adding more in the background.
368
+ *
369
+ * If a request passed in is already present due to its `uniqueKey` property being the same,
370
+ * it will not be updated. You can find out whether this happened by finding the request in the resulting
371
+ * {@link BatchAddRequestsResult} object.
372
+ *
373
+ * @param requestsLike {@link Request} objects or vanilla objects with request data.
374
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed requests if missing.
375
+ * @param [options] Request queue operation options.
376
+ */
377
+ async addRequests(requestsLike, options = {}) {
378
+ const transaction = activeStorageTransaction();
379
+ parseArgument(requestsLike, iterableSchema);
380
+ const { forefront, cache } = parseArgument(options, addRequestsOptionsSchema);
381
+ const uniqueKeyToCacheKey = new Map();
382
+ const getCachedRequestId = (uniqueKey) => {
383
+ const cached = uniqueKeyToCacheKey.get(uniqueKey);
384
+ if (cached)
385
+ return cached;
386
+ const newCacheKey = getRequestId(uniqueKey);
387
+ uniqueKeyToCacheKey.set(uniqueKey, newCacheKey);
388
+ return newCacheKey;
389
+ };
390
+ const results = {
391
+ processedRequests: [],
392
+ unprocessedRequests: [],
393
+ };
394
+ const requests = [];
395
+ for await (const requestLike of requestsLike) {
396
+ if (typeof requestLike === 'string') {
397
+ requests.push(new Request({ url: requestLike }));
398
+ }
399
+ else if ('requestsFromUrl' in requestLike) {
400
+ const fetchedRequests = await this.fetchRequestsFromUrl(requestLike);
401
+ await this.addFetchedRequests(requestLike, fetchedRequests, options);
402
+ }
403
+ else {
404
+ requests.push(requestLike instanceof Request ? requestLike : new Request(requestLike));
405
+ }
406
+ }
407
+ if (transaction?.policy.requestQueue === 'deferred') {
408
+ const buffered = this.bufferedRequests(transaction);
409
+ for (const request of requests) {
410
+ results.processedRequests.push(await this.addRequestDeferred(transaction, request, forefront, buffered));
411
+ }
412
+ return results;
413
+ }
414
+ this.recordRequestJournalEntry(transaction, requests, forefront, true);
415
+ const requestsToAdd = new Map();
416
+ for (const request of requests) {
417
+ const cacheKey = getCachedRequestId(request.uniqueKey);
418
+ // Prefer the full `requestCache` record; fall back to the dedup cache for background batches it skips.
419
+ const cachedInfo = this.#requestCache.get(cacheKey);
420
+ const knownRequestId = cachedInfo?.id ?? this.#requestSeenCache.get(cacheKey);
421
+ if (knownRequestId) {
422
+ request.id = knownRequestId;
423
+ results.processedRequests.push({
424
+ wasAlreadyPresent: true,
425
+ // The dedup cache doesn't track the handled state; only the full record does.
426
+ wasAlreadyHandled: cachedInfo?.isHandled ?? false,
427
+ requestId: knownRequestId,
428
+ uniqueKey: request.uniqueKey,
429
+ });
430
+ }
431
+ else if (!requestsToAdd.has(request.uniqueKey)) {
432
+ requestsToAdd.set(request.uniqueKey, request);
433
+ }
434
+ }
435
+ // Early exit if all provided requests were already added
436
+ if (!requestsToAdd.size) {
437
+ return results;
438
+ }
439
+ this.#statsTracker.add('writeCount');
440
+ const apiResults = await this.backend.addBatchOfRequests([...requestsToAdd.values()], { forefront });
441
+ // Report unprocessed requests
442
+ results.unprocessedRequests = apiResults.unprocessedRequests;
443
+ // Add all new requests to the requestCache
444
+ for (const newRequest of apiResults.processedRequests) {
445
+ // Add the new request to the processed list
446
+ results.processedRequests.push(newRequest);
447
+ const cacheKey = getCachedRequestId(newRequest.uniqueKey);
448
+ if (cache) {
449
+ this.cacheRequest(cacheKey, { ...newRequest, forefront });
450
+ }
451
+ // Unlike `requestCache`, populate this on every batch (including background ones).
452
+ this.#requestSeenCache.add(cacheKey, newRequest.requestId);
453
+ }
454
+ return results;
455
+ }
456
+ /**
457
+ * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
458
+ * adding the rest in the background. You can configure the batch size via `batchSize` option and the sleep time in between
459
+ * the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
460
+ * the `waitForAllRequestsToBeAdded` promise you get in the response object.
461
+ *
462
+ * @param requests The requests to add
463
+ * @param options Options for the request queue
464
+ */
465
+ async addRequestsBatched(requests, options = {}) {
466
+ parseArgument(requests, iterableSchema);
467
+ const { forefront, waitForAllRequestsToBeAdded, batchSize, waitBetweenBatchesMillis, maxNewRequests } = parseArgument(options, addRequestsBatchedOptionsSchema);
468
+ const addRequest = this.addRequest.bind(this);
469
+ async function* generateRequests() {
470
+ for await (const opts of requests) {
471
+ // Validate the input
472
+ if (typeof opts === 'object' && opts !== null) {
473
+ if (opts.url !== undefined && typeof opts.url !== 'string') {
474
+ throw new Error(`Request options are not valid, the 'url' property is not a string. Input: ${inspect(opts)}`);
475
+ }
476
+ if (opts.id !== undefined) {
477
+ throw new Error(`Request options are not valid, the 'id' property must not be present. Input: ${inspect(opts)}`);
478
+ }
479
+ if (opts.requestsFromUrl !== undefined &&
480
+ typeof opts.requestsFromUrl !== 'string') {
481
+ throw new Error(`Request options are not valid, the 'requestsFromUrl' property is not a string. Input: ${inspect(opts)}`);
482
+ }
483
+ }
484
+ if (opts && typeof opts === 'object' && 'requestsFromUrl' in opts) {
485
+ // Handle URL lists right away
486
+ await addRequest(opts, { forefront });
487
+ }
488
+ else {
489
+ // Yield valid requests
490
+ yield typeof opts === 'string' ? { url: opts } : opts;
491
+ }
492
+ }
493
+ }
494
+ return drainRequestBatches({
495
+ items: generateRequests(),
496
+ batchSize,
497
+ waitBetweenBatchesMillis,
498
+ waitForAllRequestsToBeAdded,
499
+ maxNewRequests,
500
+ /**
501
+ * Requests the backend reports as unprocessed are warned about and skipped rather than retried:
502
+ * `unprocessedRequests` is what remains after the backend's own transient-error handling - a
503
+ * semantic rejection (e.g. a malformed `userData` shape) that re-sending would only re-poke.
504
+ * Retrying transient failures is the storage backend's job, not the frontend's.
505
+ */
506
+ processChunk: async (chunk, isInitial) => {
507
+ const { processedRequests, unprocessedRequests } = await this.addRequests(chunk, {
508
+ forefront,
509
+ cache: isInitial,
510
+ });
511
+ if (unprocessedRequests.length > 0) {
512
+ this.log.warning('Some requests were rejected by the request queue and will be skipped. ' +
513
+ "This usually means the request data is malformed (e.g. an invalid 'userData' shape).", { unprocessedRequests });
514
+ }
515
+ return processedRequests;
516
+ },
517
+ trackBackgroundBatches: (batches) => {
518
+ this.#inProgressRequestBatchCount += 1;
519
+ void batches.finally(() => {
520
+ this.#inProgressRequestBatchCount -= 1;
521
+ });
522
+ },
523
+ });
524
+ }
525
+ /**
526
+ * Gets the request from the queue specified by its `uniqueKey`.
527
+ *
528
+ * @param uniqueKey Unique key of the request.
529
+ * @returns Returns the request object, or `null` if it was not found.
530
+ */
531
+ async getRequest(uniqueKey) {
532
+ const transaction = activeStorageTransaction();
533
+ parseArgument(uniqueKey, uniqueKeySchema);
534
+ // Requests buffered by the active transaction (under the `deferred` write policy) are visible to it.
535
+ const buffered = transaction && this.bufferedRequests(transaction).get(uniqueKey);
536
+ if (buffered) {
537
+ return new Request(buffered);
538
+ }
539
+ const requestOptions = await this.backend.getRequest(uniqueKey);
540
+ if (!requestOptions)
541
+ return null;
542
+ return new Request(requestOptions);
81
543
  }
82
544
  /**
83
545
  * Returns a next request in the queue to be processed, or `null` if there are no more pending requests.
84
546
  *
85
547
  * Once you successfully finish processing of the request, you need to call
86
- * {@link RequestQueue.markRequestHandled}
548
+ * {@link RequestQueue.markRequestAsHandled}
87
549
  * to mark the request as handled in the queue. If there was some error in processing the request,
88
550
  * call {@link RequestQueue.reclaimRequest} instead,
89
551
  * so that the queue will give the request to some other consumer in another call to the `fetchNextRequest` function.
@@ -91,210 +553,273 @@ class RequestQueue extends RequestProvider {
91
553
  * Note that the `null` return value doesn't mean the queue processing finished,
92
554
  * it means there are currently no pending requests.
93
555
  * To check whether all requests in queue were finished,
94
- * use {@link RequestQueue.isFinished} instead.
556
+ * use {@link RequestQueue.checkReadiness} instead.
95
557
  *
96
558
  * @returns
97
559
  * Returns the request object or `null` if there are no more pending requests.
98
560
  */
99
561
  async fetchNextRequest() {
100
- checkStorageAccess();
101
- this.lastActivity = new Date();
102
- await this.ensureHeadIsNonEmpty();
103
- const nextRequestId = this.queueHeadIds.removeFirst();
104
- // We are likely done at this point.
105
- if (!nextRequestId)
106
- return null;
107
- // This should never happen, but...
108
- if (this.inProgress.has(nextRequestId) || this.recentlyHandledRequestsCache.get(nextRequestId)) {
109
- this.log.warning('Queue head returned a request that is already in progress?!', {
110
- nextRequestId,
111
- inProgress: this.inProgress.has(nextRequestId),
112
- recentlyHandled: !!this.recentlyHandledRequestsCache.get(nextRequestId),
113
- });
562
+ rejectOperationInTransaction('RequestQueue.fetchNextRequest()', 'it is part of the crawler request-processing bookkeeping, which a transaction must not affect.');
563
+ if (this.#queuePausedForMigration) {
114
564
  return null;
115
565
  }
116
- this.inProgress.add(nextRequestId);
117
- this.lastActivity = new Date();
118
- let request;
119
- try {
120
- request = await this.getRequest(nextRequestId);
121
- }
122
- catch (e) {
123
- // On error, remove the request from in progress, otherwise it would be there forever
124
- this.inProgress.delete(nextRequestId);
125
- throw e;
126
- }
127
- // NOTE: It can happen that the queue head index is inconsistent with the main queue table. This can occur in two situations:
128
- // 1) Queue head index is ahead of the main table and the request is not present in the main table yet (i.e. getRequest() returned null).
129
- // In this case, keep the request marked as in progress for a short while,
130
- // so that isFinished() doesn't return true and _ensureHeadIsNonEmpty() doesn't not load the request
131
- // into the queueHeadDict straight again. After the interval expires, fetchNextRequest()
132
- // will try to fetch this request again, until it eventually appears in the main table.
133
- if (!request) {
134
- this.log.debug('Cannot find a request from the beginning of queue, will be retried later', {
135
- nextRequestId,
136
- });
137
- setTimeout(() => {
138
- this.inProgress.delete(nextRequestId);
139
- }, STORAGE_CONSISTENCY_DELAY_MILLIS);
566
+ this.#statsTracker.add('headItemReadCount');
567
+ const requestOptions = await this.backend.fetchNextRequest();
568
+ if (!requestOptions)
569
+ return null;
570
+ return new Request(requestOptions);
571
+ }
572
+ /**
573
+ * Marks a request that was previously returned by the
574
+ * {@link RequestQueue.fetchNextRequest}
575
+ * function as handled after successful processing.
576
+ * Handled requests will never again be returned by the `fetchNextRequest` function.
577
+ */
578
+ async markRequestAsHandled(request) {
579
+ rejectOperationInTransaction('RequestQueue.markRequestAsHandled()', 'it is part of the crawler request-processing bookkeeping, which a transaction must not affect.');
580
+ parseArgument(request, handledRequestSchema);
581
+ const forefront = this.#requestCache.get(getRequestId(request.uniqueKey))?.forefront ?? false;
582
+ const handledAt = request.handledAt ?? new Date().toISOString();
583
+ this.#statsTracker.add('writeCount');
584
+ const processedRequest = await this.backend.markRequestAsHandled({
585
+ ...request,
586
+ handledAt,
587
+ });
588
+ // The request was not in progress (e.g. already handled) — nothing to do.
589
+ if (!processedRequest) {
140
590
  return null;
141
591
  }
142
- // 2) Queue head index is behind the main table and the underlying request was already handled
143
- // (by some other client, since we keep the track of handled requests in recentlyHandled dictionary).
144
- // We just add the request to the recentlyHandled dictionary so that next call to _ensureHeadIsNonEmpty()
145
- // will not put the request again to queueHeadDict.
146
- if (request.handledAt) {
147
- this.log.debug('Request fetched from the beginning of queue was already handled', { nextRequestId });
148
- this.recentlyHandledRequestsCache.add(nextRequestId, true);
592
+ request.handledAt = handledAt;
593
+ const queueOperationInfo = {
594
+ ...processedRequest,
595
+ uniqueKey: request.uniqueKey,
596
+ forefront,
597
+ };
598
+ this.cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
599
+ return queueOperationInfo;
600
+ }
601
+ /**
602
+ * Reclaims a failed request back to the queue, so that it can be returned for processing later again
603
+ * by another call to {@link RequestQueue.fetchNextRequest}.
604
+ * The request record in the queue is updated using the provided `request` parameter.
605
+ * For example, this lets you store the number of retries or error messages for the request.
606
+ */
607
+ async reclaimRequest(request, options = {}) {
608
+ rejectOperationInTransaction('RequestQueue.reclaimRequest()', 'it is part of the crawler request-processing bookkeeping, which a transaction must not affect.');
609
+ parseArgument(request, reclaimedRequestSchema);
610
+ const { forefront } = parseArgument(options, operationOptionsSchema);
611
+ this.#statsTracker.add('writeCount');
612
+ const processedRequest = await this.backend.reclaimRequest(request, {
613
+ forefront,
614
+ });
615
+ // The request was not in progress — nothing to reclaim.
616
+ if (!processedRequest) {
149
617
  return null;
150
618
  }
151
- return request;
619
+ const queueOperationInfo = {
620
+ ...processedRequest,
621
+ uniqueKey: request.uniqueKey,
622
+ forefront,
623
+ };
624
+ this.cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
625
+ return queueOperationInfo;
152
626
  }
153
- async ensureHeadIsNonEmpty() {
154
- // Alias for backwards compatibility
155
- await this._ensureHeadIsNonEmpty();
627
+ /**
628
+ * A queue hands requests out as fast as they are asked for; pacing is a job for a manager wrapped around it,
629
+ * such as {@link ThrottlingRequestManager}.
630
+ * @inheritdoc
631
+ */
632
+ recordPacingSignal(_signal) {
633
+ return false;
156
634
  }
157
635
  /**
158
- * We always request more items than is in progress to ensure that something falls into head.
636
+ * Reports whether the queue has a request to hand over, is waiting on one, or is done.
637
+ *
638
+ * `waiting` means requests are in progress (fetched but not yet handled or reclaimed, possibly by another
639
+ * client sharing the queue) or a background add is still landing; neither has a clock, so no `readyAt`.
159
640
  *
160
- * @param [ensureConsistency] If true then query for queue head is retried until queueModifiedAt
161
- * is older than queryStartedAt by at least API_PROCESSED_REQUESTS_DELAY_MILLIS to ensure that queue
162
- * head is consistent.
163
- * @default false
164
- * @param [limit] How many queue head items will be fetched.
165
- * @param [iteration] Used when this function is called recursively to limit the recursion.
166
- * @returns Indicates if queue head is consistent (true) or inconsistent (false).
641
+ * Due to the nature of distributed storage used by the queue, `finished` may occasionally arrive a probe or
642
+ * two late, but it is never reported early.
167
643
  */
168
- async _ensureHeadIsNonEmpty(ensureConsistency = false, limit = Math.max(this.inProgressCount() * QUERY_HEAD_BUFFER, QUERY_HEAD_MIN_LENGTH), iteration = 0) {
169
- // If we are paused for migration, resolve immediately.
170
- if (this.queuePausedForMigration) {
171
- return true;
644
+ async checkReadiness() {
645
+ const transaction = activeStorageTransaction();
646
+ // Requests buffered by the active transaction count as pending from its point of view.
647
+ if (transaction && this.bufferedRequests(transaction).size > 0) {
648
+ return { status: 'ready' };
172
649
  }
173
- // If is nonempty resolve immediately.
174
- if (this.queueHeadIds.length() > 0) {
175
- return true;
650
+ // Something fetchable outranks everything below, so this is the only backend call a probe needs.
651
+ if (!(await this.backend.isEmpty())) {
652
+ return { status: 'ready' };
176
653
  }
177
- if (!this.queryQueueHeadPromise) {
178
- const queryStartedAt = new Date();
179
- this.queryQueueHeadPromise = this.client
180
- .listHead({ limit })
181
- .then(({ items, queueModifiedAt, hadMultipleClients }) => {
182
- items.forEach(({ id: requestId, uniqueKey }) => {
183
- // Queue head index might be behind the main table, so ensure we don't recycle requests
184
- if (!requestId ||
185
- !uniqueKey ||
186
- this.inProgress.has(requestId) ||
187
- this.recentlyHandledRequestsCache.get(requestId))
188
- return;
189
- this.queueHeadIds.add(requestId, requestId, false);
190
- const forefront = this.requestCache.get(getRequestId(uniqueKey))?.forefront ?? false;
191
- this._cacheRequest(getRequestId(uniqueKey), {
192
- requestId,
193
- wasAlreadyHandled: false,
194
- wasAlreadyPresent: true,
195
- uniqueKey,
196
- forefront,
197
- });
198
- });
199
- // This is needed so that the next call to _ensureHeadIsNonEmpty() will fetch the queue head again.
200
- this.queryQueueHeadPromise = null;
201
- return {
202
- wasLimitReached: items.length >= limit,
203
- prevLimit: limit,
204
- queueModifiedAt: new Date(queueModifiedAt),
205
- queryStartedAt,
206
- hadMultipleClients,
207
- };
208
- });
209
- }
210
- const { queueModifiedAt, wasLimitReached, prevLimit, queryStartedAt, hadMultipleClients } = await this.queryQueueHeadPromise;
211
- // TODO: I feel this code below can be greatly simplified...
212
- // If queue is still empty then one of the following holds:
213
- // - the other calls waiting for this promise already consumed all the returned requests
214
- // - the limit was too low and contained only requests in progress
215
- // - the writes from other clients were not propagated yet
216
- // - the whole queue was processed and we are done
217
- // If limit was not reached in the call then there are no more requests to be returned.
218
- if (prevLimit >= REQUEST_QUEUE_HEAD_MAX_LIMIT) {
219
- this.log.warning(`Reached the maximum number of requests in progress: ${REQUEST_QUEUE_HEAD_MAX_LIMIT}.`);
654
+ // We are not finished if we're still adding new requests in the background.
655
+ if (this.#inProgressRequestBatchCount > 0) {
656
+ return { status: 'waiting' };
220
657
  }
221
- const shouldRepeatWithHigherLimit = this.queueHeadIds.length() === 0 && wasLimitReached && prevLimit < REQUEST_QUEUE_HEAD_MAX_LIMIT;
222
- // If ensureConsistency=true then we must ensure that either:
223
- // - queueModifiedAt is older than queryStartedAt by at least API_PROCESSED_REQUESTS_DELAY_MILLIS
224
- // - hadMultipleClients=false and this.assumedTotalCount<=this.assumedHandledCount
225
- const isDatabaseConsistent = +queryStartedAt - +queueModifiedAt >= API_PROCESSED_REQUESTS_DELAY_MILLIS;
226
- const isLocallyConsistent = !hadMultipleClients && this.assumedTotalCount <= this.assumedHandledCount;
227
- // Consistent information from one source is enough to consider request queue finished.
228
- const shouldRepeatForConsistency = ensureConsistency && !isDatabaseConsistent && !isLocallyConsistent;
229
- // If both are false then head is consistent and we may exit.
230
- if (!shouldRepeatWithHigherLimit && !shouldRepeatForConsistency)
231
- return true;
232
- // If we are querying for consistency then we limit the number of queries to MAX_QUERIES_FOR_CONSISTENCY.
233
- // If this is reached then we return false so that empty() and finished() returns possibly false negative.
234
- if (!shouldRepeatWithHigherLimit && iteration > MAX_QUERIES_FOR_CONSISTENCY)
235
- return false;
236
- const nextLimit = shouldRepeatWithHigherLimit ? Math.round(prevLimit * 1.5) : prevLimit;
237
- // If we are repeating for consistency then wait required time.
238
- if (shouldRepeatForConsistency) {
239
- const delayMillis = API_PROCESSED_REQUESTS_DELAY_MILLIS - (Date.now() - +queueModifiedAt);
240
- this.log.info(`Waiting for ${delayMillis}ms before considering the queue as finished to ensure that the data is consistent.`);
241
- await sleep(delayMillis);
658
+ return (await this.backend.isFinished()) ? { status: 'finished' } : { status: 'waiting' };
659
+ }
660
+ /**
661
+ * Tells the queue how long a consumer expects to hold a fetched request before marking it handled
662
+ * or reclaiming it (typically the request-handler timeout plus padding), so that a storage backend
663
+ * that reserves requests via locking does not hand the same request out again while it is still
664
+ * being processed.
665
+ *
666
+ * Several consumers may share one queue (and therefore one client) in a single process, so we only
667
+ * ever raise the reservation duration, never lower it — otherwise a short-lived consumer could cut
668
+ * short the reservation of a long-lived one and have its in-flight request stolen.
669
+ */
670
+ async setExpectedRequestProcessingTimeSecs(secs) {
671
+ if (secs <= this.#expectedRequestProcessingSecs) {
672
+ return;
242
673
  }
243
- return this._ensureHeadIsNonEmpty(ensureConsistency, nextLimit, iteration + 1);
674
+ this.#expectedRequestProcessingSecs = secs;
675
+ await this.backend.setExpectedRequestProcessingTimeSecs?.(secs);
676
+ }
677
+ /**
678
+ * Caches information about request to beware of unneeded addRequest() calls.
679
+ */
680
+ cacheRequest(cacheKey, queueOperationInfo) {
681
+ // Remove the previous entry, as otherwise our cache will never update 👀
682
+ this.#requestCache.remove(cacheKey);
683
+ this.#requestCache.add(cacheKey, {
684
+ id: queueOperationInfo.requestId,
685
+ isHandled: queueOperationInfo.wasAlreadyHandled,
686
+ uniqueKey: queueOperationInfo.uniqueKey,
687
+ hydrated: null,
688
+ lockExpiresAt: null,
689
+ forefront: queueOperationInfo.forefront,
690
+ });
244
691
  }
245
- // RequestQueue v1 behavior overrides below
246
- async isFinished() {
247
- checkStorageAccess();
248
- if (Date.now() - +this.lastActivity > this.internalTimeoutMillis) {
249
- const message = `The request queue seems to be stuck for ${this.internalTimeoutMillis / 1e3}s, resetting internal state.`;
250
- this.log.warning(message, { inProgress: [...this.inProgress] });
251
- this._reset();
692
+ /**
693
+ * Removes the queue either from the Apify Cloud storage or from the local database,
694
+ * depending on the mode of operation.
695
+ */
696
+ async drop() {
697
+ rejectOperationInTransaction('RequestQueue.drop()');
698
+ await this.backend.drop();
699
+ serviceLocator.getStorageInstanceManager().removeFromCache(this);
700
+ }
701
+ /**
702
+ * Remove all requests from the queue but keep the queue itself, resetting it
703
+ * so it can be reused (e.g. across multiple `crawler.run()` calls).
704
+ */
705
+ async purge() {
706
+ rejectOperationInTransaction('RequestQueue.purge()');
707
+ await this.backend.purge();
708
+ // Reset in-memory bookkeeping so the queue behaves as if freshly opened.
709
+ this.#requestCache.clear();
710
+ this.#requestSeenCache.clear();
711
+ this.#inProgressRequestBatchCount = 0;
712
+ // Reset the expected-processing-time high-water mark too, otherwise the monotonic-raise guard
713
+ // in `setExpectedRequestProcessingTimeSecs` would let a value raised in an earlier run leak into a
714
+ // later one and silently swallow a lower hint (the queue is meant to be reusable across runs).
715
+ this.#expectedRequestProcessingSecs = 0;
716
+ }
717
+ /**
718
+ * @inheritdoc
719
+ */
720
+ async *[Symbol.asyncIterator]() {
721
+ while (true) {
722
+ const req = await this.fetchNextRequest();
723
+ if (!req)
724
+ break;
725
+ yield req;
252
726
  }
253
- if (this.inProgressRequestBatchCount > 0) {
254
- return false;
727
+ }
728
+ /**
729
+ * Returns the number of handled requests.
730
+ *
731
+ * This function is just a convenient shortcut for:
732
+ *
733
+ * ```javascript
734
+ * const { handledRequestCount } = await queue.getInfo();
735
+ * ```
736
+ * @inheritdoc
737
+ */
738
+ async getHandledCount() {
739
+ // NOTE: We keep this function for compatibility with RequestList.getHandledCount()
740
+ const { handledRequestCount } = await this.getInfo();
741
+ return handledRequestCount;
742
+ }
743
+ /**
744
+ * Returns an object containing general information about the request queue.
745
+ *
746
+ * **Example:**
747
+ * ```
748
+ * {
749
+ * id: "WkzbQMuFYuamGv3YF",
750
+ * name: "my-queue",
751
+ * createdAt: new Date("2015-12-12T07:34:14.202Z"),
752
+ * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
753
+ * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
754
+ * totalRequestCount: 25,
755
+ * handledRequestCount: 5,
756
+ * pendingRequestCount: 20,
757
+ * }
758
+ * ```
759
+ *
760
+ * @throws If the underlying storage no longer exists (e.g. it was deleted externally).
761
+ */
762
+ async getInfo() {
763
+ const transaction = activeStorageTransaction();
764
+ const metadata = await this.backend.getMetadata();
765
+ const bufferedCount = transaction ? this.bufferedRequests(transaction).size : 0;
766
+ if (bufferedCount > 0) {
767
+ return {
768
+ ...metadata,
769
+ totalRequestCount: metadata.totalRequestCount + bufferedCount,
770
+ pendingRequestCount: metadata.pendingRequestCount + bufferedCount,
771
+ };
255
772
  }
256
- if (this.queueHeadIds.length() > 0 || this.inProgressCount() > 0)
257
- return false;
258
- const isHeadConsistent = await this._ensureHeadIsNonEmpty(true);
259
- return isHeadConsistent && this.queueHeadIds.length() === 0 && this.inProgressCount() === 0;
773
+ return metadata;
260
774
  }
261
775
  /**
262
- * Reclaims a failed request back to the queue, so that it can be returned for processing later again
263
- * by another call to {@link RequestQueue.fetchNextRequest}.
264
- * The request record in the queue is updated using the provided `request` parameter.
265
- * For example, this lets you store the number of retries or error messages for the request.
776
+ * Fetches URLs from requestsFromUrl and returns them in format of list of requests
266
777
  */
267
- async reclaimRequest(...args) {
268
- checkStorageAccess();
269
- const [request, options] = args;
270
- const forefront = options?.forefront ?? false;
271
- const result = await super.reclaimRequest(...args);
272
- // Wait a little to increase a chance that the next call to fetchNextRequest() will return the request with updated data.
273
- // This is to compensate for the limitation of DynamoDB, where writes might not be immediately visible to subsequent reads.
274
- setTimeout(() => {
275
- if (!this.inProgress.has(request.id)) {
276
- this.log.debug('The request is no longer marked as in progress in the queue?!', {
277
- requestId: request.id,
278
- });
279
- return;
280
- }
281
- this.inProgress.delete(request.id);
282
- // Performance optimization: add request straight to head if possible
283
- this._maybeAddRequestToQueueHead(request.id, forefront);
284
- }, STORAGE_CONSISTENCY_DELAY_MILLIS);
285
- return result;
778
+ async fetchRequestsFromUrl(source) {
779
+ const { requestsFromUrl, regex, ...sharedOpts } = source;
780
+ // Download remote resource and parse URLs.
781
+ let urlsArr;
782
+ try {
783
+ urlsArr = await this.downloadListOfUrls({
784
+ url: requestsFromUrl,
785
+ urlRegExp: regex,
786
+ proxyUrl: (await this.#proxyConfiguration?.newProxyInfo())?.url,
787
+ });
788
+ }
789
+ catch (err) {
790
+ throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
791
+ }
792
+ // Skip if resource contained no URLs.
793
+ if (!urlsArr.length) {
794
+ this.log.warning('The fetched list contains no valid URLs.', { requestsFromUrl, regex });
795
+ return [];
796
+ }
797
+ return urlsArr.map((url) => ({ url, ...sharedOpts }));
286
798
  }
287
799
  /**
288
- * @inheritdoc
800
+ * Adds all fetched requests from a URL from a remote resource.
289
801
  */
290
- async markRequestHandled(request) {
291
- const res = await super.markRequestHandled(request);
292
- this.inProgress.delete(request.id);
293
- return res;
802
+ async addFetchedRequests(source, fetchedRequests, options) {
803
+ const { requestsFromUrl, regex } = source;
804
+ const { addedRequests } = await this.addRequestsBatched(fetchedRequests, options);
805
+ this.log.info('Fetched and loaded Requests from a remote resource.', {
806
+ requestsFromUrl,
807
+ regex,
808
+ fetchedCount: fetchedRequests.length,
809
+ importedCount: addedRequests.length,
810
+ duplicateCount: fetchedRequests.length - addedRequests.length,
811
+ sample: JSON.stringify(fetchedRequests.slice(0, 5)),
812
+ });
813
+ return addedRequests;
294
814
  }
295
- _reset() {
296
- super._reset();
297
- this.inProgress.clear();
815
+ /**
816
+ * @internal wraps public utility for mocking purposes
817
+ */
818
+ async downloadListOfUrls(options) {
819
+ return downloadListOfUrls({
820
+ ...options,
821
+ httpClient: this.#httpClient,
822
+ });
298
823
  }
299
824
  /**
300
825
  * Opens a request queue and returns a promise resolving to an instance
@@ -307,14 +832,28 @@ class RequestQueue extends RequestProvider {
307
832
  *
308
833
  * For more details and code examples, see the {@link RequestQueue} class.
309
834
  *
310
- * @param [queueIdOrName]
311
- * ID or name of the request queue to be opened. If `null` or `undefined`,
312
- * the function returns the default request queue associated with the crawler run.
835
+ * @param [identifier]
836
+ * ID or name of the request queue to be opened. If a string is provided, it will first be
837
+ * looked up as an ID; if no such storage exists, it will be treated as a name.
838
+ * If `null` or `undefined`, the function returns the default request queue associated with the crawler run.
313
839
  * @param [options] Open Request Queue options.
314
840
  */
315
- static async open(...args) {
316
- return super.open(...args);
841
+ static async open(identifier, options = {}) {
842
+ tryCancel();
843
+ const parsedOptions = parseArgument(options, openOptionsSchema);
844
+ const storageBackend = parsedOptions.storageBackend ?? serviceLocator.getStorageBackend();
845
+ const configuration = parsedOptions.configuration ?? serviceLocator.getConfiguration();
846
+ await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration });
847
+ const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'RequestQueue');
848
+ const queue = await serviceLocator
849
+ .getStorageInstanceManager()
850
+ .openStorage(this, {
851
+ ...resolved,
852
+ backendOpener: () => storageBackend.createRequestQueueBackend(resolved),
853
+ backendCacheKey: storageBackend.getStorageBackendCacheKey?.() ?? storageBackend.constructor.name,
854
+ });
855
+ queue.#proxyConfiguration = parsedOptions.proxyConfiguration;
856
+ queue.#httpClient = parsedOptions.httpClient;
857
+ return queue;
317
858
  }
318
859
  }
319
- export { RequestQueue as RequestQueueV1 };
320
- //# sourceMappingURL=request_queue.js.map