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

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