@crawlee/core 4.0.0-beta.8 → 4.0.0-beta.80

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 (257) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +5 -6
  3. package/autoscaling/autoscaled_pool.js +12 -11
  4. package/autoscaling/client_load_signal.d.ts +25 -0
  5. package/autoscaling/client_load_signal.js +36 -0
  6. package/autoscaling/cpu_load_signal.d.ts +28 -0
  7. package/autoscaling/cpu_load_signal.js +24 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +23 -0
  9. package/autoscaling/event_loop_load_signal.js +35 -0
  10. package/autoscaling/index.d.ts +5 -1
  11. package/autoscaling/index.js +5 -1
  12. package/autoscaling/load_signal.d.ts +99 -0
  13. package/autoscaling/load_signal.js +135 -0
  14. package/autoscaling/memory_load_signal.d.ts +43 -0
  15. package/autoscaling/memory_load_signal.js +102 -0
  16. package/autoscaling/snapshotter.d.ts +35 -72
  17. package/autoscaling/snapshotter.js +78 -181
  18. package/autoscaling/system_status.d.ts +21 -36
  19. package/autoscaling/system_status.js +46 -84
  20. package/configuration.d.ts +88 -228
  21. package/configuration.js +162 -224
  22. package/cookie_utils.d.ts +4 -3
  23. package/cookie_utils.js +20 -13
  24. package/crawlers/context_pipeline.d.ts +70 -0
  25. package/crawlers/context_pipeline.js +122 -0
  26. package/crawlers/crawler_commons.d.ts +20 -30
  27. package/crawlers/crawler_commons.js +12 -21
  28. package/crawlers/crawler_utils.d.ts +2 -3
  29. package/crawlers/crawler_utils.js +1 -2
  30. package/crawlers/error_snapshotter.d.ts +3 -3
  31. package/crawlers/error_snapshotter.js +2 -3
  32. package/crawlers/error_tracker.d.ts +2 -2
  33. package/crawlers/error_tracker.js +0 -1
  34. package/crawlers/index.d.ts +1 -2
  35. package/crawlers/index.js +1 -2
  36. package/crawlers/internals/types.d.ts +7 -0
  37. package/crawlers/internals/types.js +1 -0
  38. package/crawlers/statistics.d.ts +22 -17
  39. package/crawlers/statistics.js +30 -26
  40. package/enqueue_links/enqueue_links.d.ts +44 -22
  41. package/enqueue_links/enqueue_links.js +51 -30
  42. package/enqueue_links/index.d.ts +0 -1
  43. package/enqueue_links/index.js +0 -1
  44. package/enqueue_links/shared.d.ts +25 -9
  45. package/enqueue_links/shared.js +69 -38
  46. package/errors.d.ts +53 -4
  47. package/errors.js +70 -5
  48. package/events/event_manager.d.ts +34 -8
  49. package/events/event_manager.js +8 -10
  50. package/events/index.d.ts +0 -1
  51. package/events/index.js +0 -1
  52. package/events/local_event_manager.d.ts +15 -5
  53. package/events/local_event_manager.js +37 -40
  54. package/index.d.ts +4 -3
  55. package/index.js +3 -2
  56. package/log.d.ts +82 -3
  57. package/log.js +102 -1
  58. package/memory-storage/consts.d.ts +4 -0
  59. package/memory-storage/consts.js +4 -0
  60. package/memory-storage/index.d.ts +1 -0
  61. package/memory-storage/index.js +1 -0
  62. package/memory-storage/memory-storage.d.ts +46 -0
  63. package/memory-storage/memory-storage.js +136 -0
  64. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  65. package/memory-storage/resource-clients/common/base-client.js +6 -0
  66. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  67. package/memory-storage/resource-clients/dataset.js +113 -0
  68. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  69. package/memory-storage/resource-clients/key-value-store.js +203 -0
  70. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  71. package/memory-storage/resource-clients/request-queue.js +421 -0
  72. package/memory-storage/utils.d.ts +17 -0
  73. package/memory-storage/utils.js +42 -0
  74. package/package.json +12 -10
  75. package/proxy_configuration.d.ts +14 -149
  76. package/proxy_configuration.js +19 -168
  77. package/recoverable_state.d.ts +120 -0
  78. package/recoverable_state.js +141 -0
  79. package/request.d.ts +84 -13
  80. package/request.js +107 -28
  81. package/router.d.ts +117 -15
  82. package/router.js +124 -30
  83. package/serialization.d.ts +0 -1
  84. package/serialization.js +1 -2
  85. package/service_locator.d.ts +156 -0
  86. package/service_locator.js +238 -0
  87. package/session_pool/consts.d.ts +1 -2
  88. package/session_pool/consts.js +1 -2
  89. package/session_pool/errors.d.ts +0 -1
  90. package/session_pool/errors.js +0 -1
  91. package/session_pool/fingerprint.d.ts +9 -0
  92. package/session_pool/fingerprint.js +30 -0
  93. package/session_pool/index.d.ts +0 -2
  94. package/session_pool/index.js +0 -2
  95. package/session_pool/session.d.ts +35 -73
  96. package/session_pool/session.js +46 -99
  97. package/session_pool/session_pool.d.ts +71 -72
  98. package/session_pool/session_pool.js +111 -100
  99. package/storages/access_checking.d.ts +0 -1
  100. package/storages/access_checking.js +5 -2
  101. package/storages/dataset.d.ts +101 -51
  102. package/storages/dataset.js +168 -126
  103. package/storages/index.d.ts +8 -7
  104. package/storages/index.js +6 -7
  105. package/storages/key_value_store.d.ts +165 -36
  106. package/storages/key_value_store.js +269 -122
  107. package/storages/key_value_store_codec.d.ts +32 -0
  108. package/storages/key_value_store_codec.js +113 -0
  109. package/storages/request_dedup_cache.d.ts +23 -0
  110. package/storages/request_dedup_cache.js +48 -0
  111. package/storages/request_list.d.ts +38 -82
  112. package/storages/request_list.js +65 -41
  113. package/storages/request_loader.d.ts +96 -0
  114. package/storages/request_loader.js +1 -0
  115. package/storages/request_manager.d.ts +33 -0
  116. package/storages/request_manager.js +1 -0
  117. package/storages/request_manager_tandem.d.ts +106 -0
  118. package/storages/request_manager_tandem.js +197 -0
  119. package/storages/request_queue.d.ts +303 -46
  120. package/storages/request_queue.js +629 -214
  121. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
  122. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -46
  123. package/storages/storage_instance_manager.d.ts +91 -0
  124. package/storages/storage_instance_manager.js +258 -0
  125. package/storages/storage_stats.d.ts +48 -0
  126. package/storages/storage_stats.js +29 -0
  127. package/storages/utils.d.ts +51 -6
  128. package/storages/utils.js +60 -9
  129. package/system-info/cpu-info.d.ts +67 -0
  130. package/system-info/cpu-info.js +216 -0
  131. package/system-info/memory-info.d.ts +31 -0
  132. package/system-info/memory-info.js +115 -0
  133. package/system-info/ps-tree.d.ts +17 -0
  134. package/system-info/ps-tree.js +144 -0
  135. package/system-info/runtime.d.ts +14 -0
  136. package/system-info/runtime.js +80 -0
  137. package/typedefs.d.ts +1 -2
  138. package/typedefs.js +0 -1
  139. package/validators.d.ts +8 -1
  140. package/validators.js +8 -1
  141. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  142. package/autoscaling/autoscaled_pool.js.map +0 -1
  143. package/autoscaling/index.d.ts.map +0 -1
  144. package/autoscaling/index.js.map +0 -1
  145. package/autoscaling/snapshotter.d.ts.map +0 -1
  146. package/autoscaling/snapshotter.js.map +0 -1
  147. package/autoscaling/system_status.d.ts.map +0 -1
  148. package/autoscaling/system_status.js.map +0 -1
  149. package/configuration.d.ts.map +0 -1
  150. package/configuration.js.map +0 -1
  151. package/cookie_utils.d.ts.map +0 -1
  152. package/cookie_utils.js.map +0 -1
  153. package/crawlers/crawler_commons.d.ts.map +0 -1
  154. package/crawlers/crawler_commons.js.map +0 -1
  155. package/crawlers/crawler_extension.d.ts +0 -12
  156. package/crawlers/crawler_extension.d.ts.map +0 -1
  157. package/crawlers/crawler_extension.js +0 -14
  158. package/crawlers/crawler_extension.js.map +0 -1
  159. package/crawlers/crawler_utils.d.ts.map +0 -1
  160. package/crawlers/crawler_utils.js.map +0 -1
  161. package/crawlers/error_snapshotter.d.ts.map +0 -1
  162. package/crawlers/error_snapshotter.js.map +0 -1
  163. package/crawlers/error_tracker.d.ts.map +0 -1
  164. package/crawlers/error_tracker.js.map +0 -1
  165. package/crawlers/index.d.ts.map +0 -1
  166. package/crawlers/index.js.map +0 -1
  167. package/crawlers/statistics.d.ts.map +0 -1
  168. package/crawlers/statistics.js.map +0 -1
  169. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  170. package/enqueue_links/enqueue_links.js.map +0 -1
  171. package/enqueue_links/index.d.ts.map +0 -1
  172. package/enqueue_links/index.js.map +0 -1
  173. package/enqueue_links/shared.d.ts.map +0 -1
  174. package/enqueue_links/shared.js.map +0 -1
  175. package/errors.d.ts.map +0 -1
  176. package/errors.js.map +0 -1
  177. package/events/event_manager.d.ts.map +0 -1
  178. package/events/event_manager.js.map +0 -1
  179. package/events/index.d.ts.map +0 -1
  180. package/events/index.js.map +0 -1
  181. package/events/local_event_manager.d.ts.map +0 -1
  182. package/events/local_event_manager.js.map +0 -1
  183. package/http_clients/base-http-client.d.ts +0 -134
  184. package/http_clients/base-http-client.d.ts.map +0 -1
  185. package/http_clients/base-http-client.js +0 -33
  186. package/http_clients/base-http-client.js.map +0 -1
  187. package/http_clients/form-data-like.d.ts +0 -67
  188. package/http_clients/form-data-like.d.ts.map +0 -1
  189. package/http_clients/form-data-like.js +0 -5
  190. package/http_clients/form-data-like.js.map +0 -1
  191. package/http_clients/got-scraping-http-client.d.ts +0 -15
  192. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  193. package/http_clients/got-scraping-http-client.js +0 -69
  194. package/http_clients/got-scraping-http-client.js.map +0 -1
  195. package/http_clients/index.d.ts +0 -3
  196. package/http_clients/index.d.ts.map +0 -1
  197. package/http_clients/index.js +0 -3
  198. package/http_clients/index.js.map +0 -1
  199. package/index.d.ts.map +0 -1
  200. package/index.js.map +0 -1
  201. package/log.d.ts.map +0 -1
  202. package/log.js.map +0 -1
  203. package/proxy_configuration.d.ts.map +0 -1
  204. package/proxy_configuration.js.map +0 -1
  205. package/request.d.ts.map +0 -1
  206. package/request.js.map +0 -1
  207. package/router.d.ts.map +0 -1
  208. package/router.js.map +0 -1
  209. package/serialization.d.ts.map +0 -1
  210. package/serialization.js.map +0 -1
  211. package/session_pool/consts.d.ts.map +0 -1
  212. package/session_pool/consts.js.map +0 -1
  213. package/session_pool/errors.d.ts.map +0 -1
  214. package/session_pool/errors.js.map +0 -1
  215. package/session_pool/events.d.ts +0 -3
  216. package/session_pool/events.d.ts.map +0 -1
  217. package/session_pool/events.js +0 -3
  218. package/session_pool/events.js.map +0 -1
  219. package/session_pool/index.d.ts.map +0 -1
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts.map +0 -1
  222. package/session_pool/session.js.map +0 -1
  223. package/session_pool/session_pool.d.ts.map +0 -1
  224. package/session_pool/session_pool.js.map +0 -1
  225. package/storages/access_checking.d.ts.map +0 -1
  226. package/storages/access_checking.js.map +0 -1
  227. package/storages/dataset.d.ts.map +0 -1
  228. package/storages/dataset.js.map +0 -1
  229. package/storages/index.d.ts.map +0 -1
  230. package/storages/index.js.map +0 -1
  231. package/storages/key_value_store.d.ts.map +0 -1
  232. package/storages/key_value_store.js.map +0 -1
  233. package/storages/request_list.d.ts.map +0 -1
  234. package/storages/request_list.js.map +0 -1
  235. package/storages/request_provider.d.ts +0 -307
  236. package/storages/request_provider.d.ts.map +0 -1
  237. package/storages/request_provider.js +0 -555
  238. package/storages/request_provider.js.map +0 -1
  239. package/storages/request_queue.d.ts.map +0 -1
  240. package/storages/request_queue.js.map +0 -1
  241. package/storages/request_queue_v2.d.ts +0 -87
  242. package/storages/request_queue_v2.d.ts.map +0 -1
  243. package/storages/request_queue_v2.js +0 -438
  244. package/storages/request_queue_v2.js.map +0 -1
  245. package/storages/sitemap_request_list.d.ts.map +0 -1
  246. package/storages/sitemap_request_list.js.map +0 -1
  247. package/storages/storage_manager.d.ts +0 -58
  248. package/storages/storage_manager.d.ts.map +0 -1
  249. package/storages/storage_manager.js +0 -105
  250. package/storages/storage_manager.js.map +0 -1
  251. package/storages/utils.d.ts.map +0 -1
  252. package/storages/utils.js.map +0 -1
  253. package/tsconfig.build.tsbuildinfo +0 -1
  254. package/typedefs.d.ts.map +0 -1
  255. package/typedefs.js.map +0 -1
  256. package/validators.d.ts.map +0 -1
  257. package/validators.js.map +0 -1
@@ -1,16 +1,25 @@
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 { chunkedAsyncIterable, downloadListOfUrls, getObjectType, isAsyncIterable, isIterable, peekableAsyncIterable, sleep, } from '@crawlee/utils';
3
+ import ow from 'ow';
4
+ import { LruCache } from '@apify/datastructures';
3
5
  import { Configuration } from '../configuration.js';
6
+ import { Request } from '../request.js';
7
+ import { serviceLocator } from '../service_locator.js';
4
8
  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;
9
+ import { StorageStatsTracker } from './storage_stats.js';
10
+ import { resolveStorageIdentifier } from './storage_instance_manager.js';
11
+ import { getRequestId, purgeDefaultStorages } from './utils.js';
12
+ import { RequestDeduplicationCache } from './request_dedup_cache.js';
8
13
  /**
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.
14
+ * The maximum number of requests cached locally to avoid redundant calls to the storage backend.
11
15
  * @internal
12
16
  */
13
- const RECENTLY_HANDLED_CACHE_SIZE = 1000;
17
+ const MAX_CACHED_REQUESTS = 2_000_000;
18
+ /**
19
+ * The maximum number of consecutive no-progress retries for unprocessed requests in `addRequestsBatched()`.
20
+ * @internal
21
+ */
22
+ const MAX_UNPROCESSED_REQUESTS_RETRIES = 3;
14
23
  /**
15
24
  * Represents a queue of URLs to crawl, which is used for deep crawling of websites
16
25
  * where you start with several URLs and then recursively
@@ -29,18 +38,6 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
29
38
  * Unlike {@link RequestList}, `RequestQueue` supports dynamic adding and removing of requests.
30
39
  * On the other hand, the queue is not optimized for operations that add or remove a large number of URLs in a batch.
31
40
  *
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
41
  * **Example usage:**
45
42
  *
46
43
  * ```javascript
@@ -56,34 +53,374 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
56
53
  * await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });
57
54
  * ```
58
55
  * @category Sources
59
- *
60
- * @deprecated RequestQueue v1 is deprecated and will be removed in the future. Please use {@link RequestQueue} instead.
61
56
  */
62
- class RequestQueue extends RequestProvider {
63
- queryQueueHeadPromise = null;
64
- inProgress = new Set();
57
+ export class RequestQueue {
58
+ config;
59
+ id;
60
+ name;
61
+ backend;
62
+ proxyConfiguration;
63
+ log;
64
+ requestCache;
65
+ /**
66
+ * Remembers the `requestId` of every request already submitted to the client — including background
67
+ * batches that `requestCache` skips — so overlapping URL sets aren't re-submitted.
68
+ * See {@link RequestDeduplicationCache} for why this is a separate, cheaper cache.
69
+ */
70
+ requestSeenCache;
71
+ queuePausedForMigration = false;
72
+ inProgressRequestBatchCount = 0;
73
+ /**
74
+ * The largest expected request-processing time (in seconds) seen so far via
75
+ * {@link setExpectedRequestProcessingTimeSecs}. Used to ensure that value is only ever raised, never
76
+ * lowered, before being forwarded to the storage backend.
77
+ */
78
+ expectedRequestProcessingSecs = 0;
79
+ httpClient;
80
+ events;
81
+ statsTracker = new StorageStatsTracker({
82
+ writeCount: 0,
83
+ headItemReadCount: 0,
84
+ });
85
+ /**
86
+ * Backend-independent usage counters tracked for this request queue (write operations and
87
+ * queue-head reads issued to the underlying storage backend). Counted per backend call.
88
+ */
89
+ get stats() {
90
+ return this.statsTracker.current;
91
+ }
65
92
  /**
66
93
  * @internal
67
94
  */
68
95
  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);
96
+ this.config = config;
97
+ this.id = options.metadata.id;
98
+ this.name = options.metadata.name;
99
+ this.events = serviceLocator.getEventManager();
100
+ this.backend = options.backend;
101
+ this.proxyConfiguration = options.proxyConfiguration;
102
+ this.requestCache = new LruCache({ maxLength: MAX_CACHED_REQUESTS });
103
+ this.requestSeenCache = new RequestDeduplicationCache();
104
+ this.log = serviceLocator.getLogger().child({ prefix: `RequestQueue(${this.id}, ${this.name ?? 'no-name'})` });
105
+ this.events.on("migrating" /* EventType.MIGRATING */, async () => {
106
+ this.queuePausedForMigration = true;
107
+ });
75
108
  }
76
109
  /**
77
- * @internal
110
+ * Returns the total number of requests in the queue (i.e. pending + handled).
111
+ *
112
+ * Survives restarts and actor migrations.
113
+ */
114
+ async getTotalCount() {
115
+ const { totalRequestCount } = await this.getInfo();
116
+ return totalRequestCount;
117
+ }
118
+ /**
119
+ * Returns the total number of pending requests in the queue.
120
+ *
121
+ * Survives restarts and Actor migrations.
78
122
  */
79
- inProgressCount() {
80
- return this.inProgress.size;
123
+ async getPendingCount() {
124
+ const { totalRequestCount, handledRequestCount } = await this.getInfo();
125
+ return totalRequestCount - handledRequestCount;
126
+ }
127
+ /**
128
+ * Adds a request to the queue.
129
+ *
130
+ * If a request with the same `uniqueKey` property is already present in the queue,
131
+ * it will not be updated. You can find out whether this happened from the resulting
132
+ * {@link QueueOperationInfo} object.
133
+ *
134
+ * To add multiple requests to the queue by extracting links from a webpage,
135
+ * see the {@link enqueueLinks} helper function.
136
+ *
137
+ * @param requestLike {@link Request} object or vanilla object with request data.
138
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed Request.
139
+ * @param [options] Request queue operation options.
140
+ */
141
+ async addRequest(requestLike, options = {}) {
142
+ checkStorageAccess();
143
+ ow(requestLike, ow.object);
144
+ ow(options, ow.object.exactShape({
145
+ forefront: ow.optional.boolean,
146
+ }));
147
+ const { forefront = false } = options;
148
+ if ('requestsFromUrl' in requestLike) {
149
+ const requests = await this._fetchRequestsFromUrl(requestLike);
150
+ const processedRequests = await this._addFetchedRequests(requestLike, requests, options);
151
+ return { ...processedRequests[0], forefront };
152
+ }
153
+ ow(requestLike, ow.object.partialShape({
154
+ url: ow.string,
155
+ id: ow.undefined,
156
+ }));
157
+ const request = requestLike instanceof Request ? requestLike : new Request(requestLike);
158
+ const cacheKey = getRequestId(request.uniqueKey);
159
+ const cachedInfo = this.requestCache.get(cacheKey);
160
+ if (cachedInfo) {
161
+ request.id = cachedInfo.id;
162
+ return {
163
+ wasAlreadyPresent: true,
164
+ // We may assume that if request is in local cache then also the information if the
165
+ // request was already handled is there because just one client should be using one queue.
166
+ wasAlreadyHandled: cachedInfo.isHandled,
167
+ requestId: cachedInfo.id,
168
+ uniqueKey: cachedInfo.uniqueKey,
169
+ forefront,
170
+ };
171
+ }
172
+ this.statsTracker.add('writeCount');
173
+ const { processedRequests } = await this.backend.addBatchOfRequests([request], { forefront });
174
+ const queueOperationInfo = {
175
+ ...processedRequests[0],
176
+ uniqueKey: request.uniqueKey,
177
+ forefront,
178
+ };
179
+ this._cacheRequest(cacheKey, queueOperationInfo);
180
+ this.requestSeenCache.add(cacheKey, request.id);
181
+ return queueOperationInfo;
182
+ }
183
+ /**
184
+ * Adds requests to the queue in batches of 25. This method will wait till all the requests are added
185
+ * to the queue before resolving. You should prefer using `queue.addRequestsBatched()` or `crawler.addRequests()`
186
+ * if you don't want to block the processing, as those methods will only wait for the initial 1000 requests,
187
+ * start processing right after that happens, and continue adding more in the background.
188
+ *
189
+ * If a request passed in is already present due to its `uniqueKey` property being the same,
190
+ * it will not be updated. You can find out whether this happened by finding the request in the resulting
191
+ * {@link BatchAddRequestsResult} object.
192
+ *
193
+ * @param requestsLike {@link Request} objects or vanilla objects with request data.
194
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed requests if missing.
195
+ * @param [options] Request queue operation options.
196
+ */
197
+ async addRequests(requestsLike, options = {}) {
198
+ checkStorageAccess();
199
+ ow(requestsLike, ow.object
200
+ .is((value) => isIterable(value) || isAsyncIterable(value))
201
+ .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`));
202
+ ow(options, ow.object.exactShape({
203
+ forefront: ow.optional.boolean,
204
+ cache: ow.optional.boolean,
205
+ }));
206
+ const { forefront = false, cache = true } = options;
207
+ const uniqueKeyToCacheKey = new Map();
208
+ const getCachedRequestId = (uniqueKey) => {
209
+ const cached = uniqueKeyToCacheKey.get(uniqueKey);
210
+ if (cached)
211
+ return cached;
212
+ const newCacheKey = getRequestId(uniqueKey);
213
+ uniqueKeyToCacheKey.set(uniqueKey, newCacheKey);
214
+ return newCacheKey;
215
+ };
216
+ const results = {
217
+ processedRequests: [],
218
+ unprocessedRequests: [],
219
+ };
220
+ const requests = [];
221
+ for await (const requestLike of requestsLike) {
222
+ if (typeof requestLike === 'string') {
223
+ requests.push(new Request({ url: requestLike }));
224
+ }
225
+ else if ('requestsFromUrl' in requestLike) {
226
+ const fetchedRequests = await this._fetchRequestsFromUrl(requestLike);
227
+ await this._addFetchedRequests(requestLike, fetchedRequests, options);
228
+ }
229
+ else {
230
+ requests.push(requestLike instanceof Request ? requestLike : new Request(requestLike));
231
+ }
232
+ }
233
+ const requestsToAdd = new Map();
234
+ for (const request of requests) {
235
+ const cacheKey = getCachedRequestId(request.uniqueKey);
236
+ // Prefer the full `requestCache` record; fall back to the dedup cache for background batches it skips.
237
+ const cachedInfo = this.requestCache.get(cacheKey);
238
+ const knownRequestId = cachedInfo?.id ?? this.requestSeenCache.get(cacheKey);
239
+ if (knownRequestId) {
240
+ request.id = knownRequestId;
241
+ results.processedRequests.push({
242
+ wasAlreadyPresent: true,
243
+ // The dedup cache doesn't track the handled state; only the full record does.
244
+ wasAlreadyHandled: cachedInfo?.isHandled ?? false,
245
+ requestId: knownRequestId,
246
+ uniqueKey: request.uniqueKey,
247
+ });
248
+ }
249
+ else if (!requestsToAdd.has(request.uniqueKey)) {
250
+ requestsToAdd.set(request.uniqueKey, request);
251
+ }
252
+ }
253
+ // Early exit if all provided requests were already added
254
+ if (!requestsToAdd.size) {
255
+ return results;
256
+ }
257
+ this.statsTracker.add('writeCount');
258
+ const apiResults = await this.backend.addBatchOfRequests([...requestsToAdd.values()], { forefront });
259
+ // Report unprocessed requests
260
+ results.unprocessedRequests = apiResults.unprocessedRequests;
261
+ // Add all new requests to the requestCache
262
+ for (const newRequest of apiResults.processedRequests) {
263
+ // Add the new request to the processed list
264
+ results.processedRequests.push(newRequest);
265
+ const cacheKey = getCachedRequestId(newRequest.uniqueKey);
266
+ if (cache) {
267
+ this._cacheRequest(cacheKey, { ...newRequest, forefront });
268
+ }
269
+ // Unlike `requestCache`, populate this on every batch (including background ones).
270
+ this.requestSeenCache.add(cacheKey, newRequest.requestId);
271
+ }
272
+ return results;
273
+ }
274
+ /**
275
+ * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
276
+ * adding the rest in the background. You can configure the batch size via `batchSize` option and the sleep time in between
277
+ * the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
278
+ * the `waitForAllRequestsToBeAdded` promise you get in the response object.
279
+ *
280
+ * @param requests The requests to add
281
+ * @param options Options for the request queue
282
+ */
283
+ async addRequestsBatched(requests, options = {}) {
284
+ checkStorageAccess();
285
+ ow(requests, ow.object
286
+ .is((value) => isIterable(value) || isAsyncIterable(value))
287
+ .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`));
288
+ ow(options, ow.object.exactShape({
289
+ forefront: ow.optional.boolean,
290
+ waitForAllRequestsToBeAdded: ow.optional.boolean,
291
+ batchSize: ow.optional.number,
292
+ waitBetweenBatchesMillis: ow.optional.number,
293
+ maxNewRequests: ow.optional.number,
294
+ }));
295
+ const addRequest = this.addRequest.bind(this);
296
+ async function* generateRequests() {
297
+ for await (const opts of requests) {
298
+ // Validate the input
299
+ if (typeof opts === 'object' && opts !== null) {
300
+ if (opts.url !== undefined && typeof opts.url !== 'string') {
301
+ throw new Error(`Request options are not valid, the 'url' property is not a string. Input: ${inspect(opts)}`);
302
+ }
303
+ if (opts.id !== undefined) {
304
+ throw new Error(`Request options are not valid, the 'id' property must not be present. Input: ${inspect(opts)}`);
305
+ }
306
+ if (opts.requestsFromUrl !== undefined &&
307
+ typeof opts.requestsFromUrl !== 'string') {
308
+ throw new Error(`Request options are not valid, the 'requestsFromUrl' property is not a string. Input: ${inspect(opts)}`);
309
+ }
310
+ }
311
+ if (opts && typeof opts === 'object' && 'requestsFromUrl' in opts) {
312
+ // Handle URL lists right away
313
+ await addRequest(opts, { forefront: options.forefront });
314
+ }
315
+ else {
316
+ // Yield valid requests
317
+ yield typeof opts === 'string' ? { url: opts } : opts;
318
+ }
319
+ }
320
+ }
321
+ const { batchSize = 1000, waitBetweenBatchesMillis = 1000, maxNewRequests = undefined } = options;
322
+ let remainingBudget = maxNewRequests ?? Infinity;
323
+ const requestsOverLimit = [];
324
+ // If there's a limit on the number of added requests, do not send batches bigger than the limit
325
+ const effectiveChunkSize = maxNewRequests !== undefined ? () => Math.min(batchSize, remainingBudget) : batchSize;
326
+ // Hold onto the underlying iterator so we can drain leftovers from it in buildResult
327
+ const requestIterator = generateRequests();
328
+ const chunks = peekableAsyncIterable(chunkedAsyncIterable(requestIterator, effectiveChunkSize));
329
+ const chunksIterator = chunks[Symbol.asyncIterator]();
330
+ const attemptToAddToQueueAndAddAnyUnprocessed = async (providedRequests, cache = true, unsuccessfulAttempts = 0) => {
331
+ const resultsToReturn = [];
332
+ const apiResult = await this.addRequests(providedRequests, { forefront: options.forefront, cache });
333
+ resultsToReturn.push(...apiResult.processedRequests);
334
+ if (apiResult.unprocessedRequests.length) {
335
+ // Count attempts that make no progress, so permanently rejected requests (e.g. a malformed
336
+ // `userData` shape causing a 400) don't loop forever. Any progress resets the counter.
337
+ const attempts = apiResult.processedRequests.length ? 0 : unsuccessfulAttempts + 1;
338
+ if (attempts >= MAX_UNPROCESSED_REQUESTS_RETRIES) {
339
+ this.log.warning(`Some requests were consistently rejected by the request queue and will be skipped after ${MAX_UNPROCESSED_REQUESTS_RETRIES} attempts. This usually means the request data is malformed (e.g. an invalid 'userData' shape).`, { unprocessedRequests: apiResult.unprocessedRequests });
340
+ return resultsToReturn;
341
+ }
342
+ await sleep(waitBetweenBatchesMillis);
343
+ resultsToReturn.push(...(await attemptToAddToQueueAndAddAnyUnprocessed(providedRequests.filter((r) => !apiResult.processedRequests.some((pr) => pr.uniqueKey === r.uniqueKey)), false, attempts)));
344
+ }
345
+ return resultsToReturn;
346
+ };
347
+ /**
348
+ * Process a chunk: send it to the queue, then update the remaining budget if maxNewRequests is active.
349
+ */
350
+ const processChunk = async (chunk, cache = true) => {
351
+ const results = await attemptToAddToQueueAndAddAnyUnprocessed(chunk, cache);
352
+ if (maxNewRequests !== undefined) {
353
+ remainingBudget -= results.filter((r) => !r.wasAlreadyPresent).length;
354
+ }
355
+ return results;
356
+ };
357
+ /**
358
+ * Build the final result. When maxNewRequests is set, drains any remaining items
359
+ * from the underlying request iterator into requestsOverLimit.
360
+ *
361
+ * We accept the iterator explicitly (rather than closing over it) to make it obvious
362
+ * that this is the *same* iterator that `chunkedAsyncIterable` has been consuming —
363
+ * so only unconsumed items are drained. We drain `requestIterator` (not `chunks`)
364
+ * because `chunkedAsyncIterable` stops yielding when the budget-based chunk size
365
+ * drops to 0, leaving unconsumed items in the underlying iterator.
366
+ */
367
+ const buildResult = async (addedRequests, waitForAllRequestsToBeAdded, unconsumedIterator) => {
368
+ if (maxNewRequests !== undefined) {
369
+ for await (const request of unconsumedIterator) {
370
+ requestsOverLimit.push(request);
371
+ }
372
+ }
373
+ return { addedRequests, waitForAllRequestsToBeAdded, requestsOverLimit };
374
+ };
375
+ // Add initial batch to process right away
376
+ const initialChunk = await chunksIterator.peek();
377
+ if (initialChunk === undefined) {
378
+ return buildResult([], Promise.resolve([]), requestIterator);
379
+ }
380
+ const addedRequests = await processChunk(initialChunk);
381
+ await chunksIterator.next();
382
+ // If we have no more requests to add (either exhausted or budget hit), return immediately
383
+ if ((await chunksIterator.peek()) === undefined) {
384
+ return buildResult(addedRequests, Promise.resolve([]), requestIterator);
385
+ }
386
+ // eslint-disable-next-line no-async-promise-executor
387
+ const promise = new Promise(async (resolve) => {
388
+ const finalAddedRequests = [];
389
+ for await (const requestChunk of chunks) {
390
+ finalAddedRequests.push(...(await processChunk(requestChunk, false)));
391
+ await sleep(waitBetweenBatchesMillis);
392
+ }
393
+ resolve(finalAddedRequests);
394
+ });
395
+ this.inProgressRequestBatchCount += 1;
396
+ void promise.finally(() => {
397
+ this.inProgressRequestBatchCount -= 1;
398
+ });
399
+ // When maxNewRequests is set, we must wait for all batches so we can accurately report skipped requests.
400
+ if (options.waitForAllRequestsToBeAdded || maxNewRequests !== undefined) {
401
+ addedRequests.push(...(await promise));
402
+ }
403
+ return buildResult(addedRequests, promise, requestIterator);
404
+ }
405
+ /**
406
+ * Gets the request from the queue specified by its `uniqueKey`.
407
+ *
408
+ * @param uniqueKey Unique key of the request.
409
+ * @returns Returns the request object, or `null` if it was not found.
410
+ */
411
+ async getRequest(uniqueKey) {
412
+ checkStorageAccess();
413
+ ow(uniqueKey, ow.string);
414
+ const requestOptions = await this.backend.getRequest(uniqueKey);
415
+ if (!requestOptions)
416
+ return null;
417
+ return new Request(requestOptions);
81
418
  }
82
419
  /**
83
420
  * Returns a next request in the queue to be processed, or `null` if there are no more pending requests.
84
421
  *
85
422
  * Once you successfully finish processing of the request, you need to call
86
- * {@link RequestQueue.markRequestHandled}
423
+ * {@link RequestQueue.markRequestAsHandled}
87
424
  * to mark the request as handled in the queue. If there was some error in processing the request,
88
425
  * call {@link RequestQueue.reclaimRequest} instead,
89
426
  * so that the queue will give the request to some other consumer in another call to the `fetchNextRequest` function.
@@ -98,203 +435,262 @@ class RequestQueue extends RequestProvider {
98
435
  */
99
436
  async fetchNextRequest() {
100
437
  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
- });
438
+ if (this.queuePausedForMigration) {
114
439
  return null;
115
440
  }
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);
441
+ this.statsTracker.add('headItemReadCount');
442
+ const requestOptions = await this.backend.fetchNextRequest();
443
+ if (!requestOptions)
140
444
  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);
445
+ return new Request(requestOptions);
446
+ }
447
+ /**
448
+ * Marks a request that was previously returned by the
449
+ * {@link RequestQueue.fetchNextRequest}
450
+ * function as handled after successful processing.
451
+ * Handled requests will never again be returned by the `fetchNextRequest` function.
452
+ */
453
+ async markRequestAsHandled(request) {
454
+ checkStorageAccess();
455
+ ow(request, ow.object.partialShape({
456
+ id: ow.string,
457
+ uniqueKey: ow.string,
458
+ handledAt: ow.optional.string,
459
+ }));
460
+ const forefront = this.requestCache.get(getRequestId(request.uniqueKey))?.forefront ?? false;
461
+ const handledAt = request.handledAt ?? new Date().toISOString();
462
+ this.statsTracker.add('writeCount');
463
+ const processedRequest = await this.backend.markRequestAsHandled({
464
+ ...request,
465
+ handledAt,
466
+ });
467
+ // The request was not in progress (e.g. already handled) — nothing to do.
468
+ if (!processedRequest) {
149
469
  return null;
150
470
  }
151
- return request;
471
+ request.handledAt = handledAt;
472
+ const queueOperationInfo = {
473
+ ...processedRequest,
474
+ uniqueKey: request.uniqueKey,
475
+ forefront,
476
+ };
477
+ this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
478
+ return queueOperationInfo;
152
479
  }
153
- async ensureHeadIsNonEmpty() {
154
- // Alias for backwards compatibility
155
- await this._ensureHeadIsNonEmpty();
480
+ /**
481
+ * Reclaims a failed request back to the queue, so that it can be returned for processing later again
482
+ * by another call to {@link RequestQueue.fetchNextRequest}.
483
+ * The request record in the queue is updated using the provided `request` parameter.
484
+ * For example, this lets you store the number of retries or error messages for the request.
485
+ */
486
+ async reclaimRequest(request, options = {}) {
487
+ checkStorageAccess();
488
+ ow(request, ow.object.partialShape({
489
+ id: ow.string,
490
+ uniqueKey: ow.string,
491
+ }));
492
+ ow(options, ow.object.exactShape({
493
+ forefront: ow.optional.boolean,
494
+ }));
495
+ const { forefront = false } = options;
496
+ this.statsTracker.add('writeCount');
497
+ const processedRequest = await this.backend.reclaimRequest(request, { forefront });
498
+ // The request was not in progress — nothing to reclaim.
499
+ if (!processedRequest) {
500
+ return null;
501
+ }
502
+ const queueOperationInfo = {
503
+ ...processedRequest,
504
+ uniqueKey: request.uniqueKey,
505
+ forefront,
506
+ };
507
+ this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
508
+ return queueOperationInfo;
156
509
  }
157
510
  /**
158
- * We always request more items than is in progress to ensure that something falls into head.
511
+ * Resolves to `true` if the next call to {@link RequestQueue.fetchNextRequest} would return
512
+ * `null`, i.e. there are no pending requests to fetch right now. Otherwise it resolves to `false`.
159
513
  *
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).
514
+ * Note that even if the queue is empty, there might be some requests currently being processed
515
+ * (fetched but not yet handled or reclaimed). An empty queue therefore does not mean crawling is
516
+ * finished — those in-progress requests may still be reclaimed, and background tasks may still be
517
+ * adding more requests. To check whether all activity in the queue has finished, use
518
+ * {@link RequestQueue.isFinished}.
167
519
  */
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)
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);
242
- }
243
- return this._ensureHeadIsNonEmpty(ensureConsistency, nextLimit, iteration + 1);
520
+ async isEmpty() {
521
+ checkStorageAccess();
522
+ return this.backend.isEmpty();
244
523
  }
245
- // RequestQueue v1 behavior overrides below
524
+ /**
525
+ * Resolves to `true` if all requests were already handled and there are no more left — including no
526
+ * requests currently in progress (fetched but not yet handled or reclaimed, including requests
527
+ * locked by other clients sharing the same queue) and no background add operations still in flight.
528
+ *
529
+ * Due to the nature of distributed storage used by the queue, the function may occasionally return
530
+ * a false negative, but it shall never return a false positive.
531
+ */
246
532
  async isFinished() {
247
533
  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
- }
534
+ // We are not finished if we're still adding new requests in the background.
253
535
  if (this.inProgressRequestBatchCount > 0) {
254
536
  return false;
255
537
  }
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;
538
+ return this.backend.isFinished();
260
539
  }
261
540
  /**
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.
541
+ * Tells the queue how long a consumer expects to hold a fetched request before marking it handled
542
+ * or reclaiming it (typically the request-handler timeout plus padding), so that a storage backend
543
+ * that reserves requests via locking does not hand the same request out again while it is still
544
+ * being processed.
545
+ *
546
+ * Several consumers may share one queue (and therefore one client) in a single process, so we only
547
+ * ever raise the reservation duration, never lower it — otherwise a short-lived consumer could cut
548
+ * short the reservation of a long-lived one and have its in-flight request stolen.
549
+ */
550
+ async setExpectedRequestProcessingTimeSecs(secs) {
551
+ if (secs <= this.expectedRequestProcessingSecs) {
552
+ return;
553
+ }
554
+ this.expectedRequestProcessingSecs = secs;
555
+ await this.backend.setExpectedRequestProcessingTimeSecs?.(secs);
556
+ }
557
+ /**
558
+ * Caches information about request to beware of unneeded addRequest() calls.
266
559
  */
267
- async reclaimRequest(...args) {
560
+ _cacheRequest(cacheKey, queueOperationInfo) {
561
+ // Remove the previous entry, as otherwise our cache will never update 👀
562
+ this.requestCache.remove(cacheKey);
563
+ this.requestCache.add(cacheKey, {
564
+ id: queueOperationInfo.requestId,
565
+ isHandled: queueOperationInfo.wasAlreadyHandled,
566
+ uniqueKey: queueOperationInfo.uniqueKey,
567
+ hydrated: null,
568
+ lockExpiresAt: null,
569
+ forefront: queueOperationInfo.forefront,
570
+ });
571
+ }
572
+ /**
573
+ * Removes the queue either from the Apify Cloud storage or from the local database,
574
+ * depending on the mode of operation.
575
+ */
576
+ async drop() {
268
577
  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;
578
+ await this.backend.drop();
579
+ serviceLocator.getStorageInstanceManager().removeFromCache(this);
580
+ }
581
+ /**
582
+ * Remove all requests from the queue but keep the queue itself, resetting it
583
+ * so it can be reused (e.g. across multiple `crawler.run()` calls).
584
+ */
585
+ async purge() {
586
+ checkStorageAccess();
587
+ await this.backend.purge();
588
+ // Reset in-memory bookkeeping so the queue behaves as if freshly opened.
589
+ this.requestCache.clear();
590
+ this.requestSeenCache.clear();
591
+ this.inProgressRequestBatchCount = 0;
592
+ // Reset the expected-processing-time high-water mark too, otherwise the monotonic-raise guard
593
+ // in `setExpectedRequestProcessingTimeSecs` would let a value raised in an earlier run leak into a
594
+ // later one and silently swallow a lower hint (the queue is meant to be reusable across runs).
595
+ this.expectedRequestProcessingSecs = 0;
286
596
  }
287
597
  /**
288
598
  * @inheritdoc
289
599
  */
290
- async markRequestHandled(request) {
291
- const res = await super.markRequestHandled(request);
292
- this.inProgress.delete(request.id);
293
- return res;
600
+ async *[Symbol.asyncIterator]() {
601
+ while (true) {
602
+ const req = await this.fetchNextRequest();
603
+ if (!req)
604
+ break;
605
+ yield req;
606
+ }
294
607
  }
295
- _reset() {
296
- super._reset();
297
- this.inProgress.clear();
608
+ /**
609
+ * Returns the number of handled requests.
610
+ *
611
+ * This function is just a convenient shortcut for:
612
+ *
613
+ * ```javascript
614
+ * const { handledRequestCount } = await queue.getInfo();
615
+ * ```
616
+ * @inheritdoc
617
+ */
618
+ async getHandledCount() {
619
+ // NOTE: We keep this function for compatibility with RequestList.getHandledCount()
620
+ const { handledRequestCount } = await this.getInfo();
621
+ return handledRequestCount;
622
+ }
623
+ /**
624
+ * Returns an object containing general information about the request queue.
625
+ *
626
+ * **Example:**
627
+ * ```
628
+ * {
629
+ * id: "WkzbQMuFYuamGv3YF",
630
+ * name: "my-queue",
631
+ * createdAt: new Date("2015-12-12T07:34:14.202Z"),
632
+ * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
633
+ * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
634
+ * totalRequestCount: 25,
635
+ * handledRequestCount: 5,
636
+ * pendingRequestCount: 20,
637
+ * }
638
+ * ```
639
+ *
640
+ * @throws If the underlying storage no longer exists (e.g. it was deleted externally).
641
+ */
642
+ async getInfo() {
643
+ checkStorageAccess();
644
+ return this.backend.getMetadata();
645
+ }
646
+ /**
647
+ * Fetches URLs from requestsFromUrl and returns them in format of list of requests
648
+ */
649
+ async _fetchRequestsFromUrl(source) {
650
+ const { requestsFromUrl, regex, ...sharedOpts } = source;
651
+ // Download remote resource and parse URLs.
652
+ let urlsArr;
653
+ try {
654
+ urlsArr = await this._downloadListOfUrls({
655
+ url: requestsFromUrl,
656
+ urlRegExp: regex,
657
+ proxyUrl: await this.proxyConfiguration?.newUrl(),
658
+ });
659
+ }
660
+ catch (err) {
661
+ throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
662
+ }
663
+ // Skip if resource contained no URLs.
664
+ if (!urlsArr.length) {
665
+ this.log.warning('The fetched list contains no valid URLs.', { requestsFromUrl, regex });
666
+ return [];
667
+ }
668
+ return urlsArr.map((url) => ({ url, ...sharedOpts }));
669
+ }
670
+ /**
671
+ * Adds all fetched requests from a URL from a remote resource.
672
+ */
673
+ async _addFetchedRequests(source, fetchedRequests, options) {
674
+ const { requestsFromUrl, regex } = source;
675
+ const { addedRequests } = await this.addRequestsBatched(fetchedRequests, options);
676
+ this.log.info('Fetched and loaded Requests from a remote resource.', {
677
+ requestsFromUrl,
678
+ regex,
679
+ fetchedCount: fetchedRequests.length,
680
+ importedCount: addedRequests.length,
681
+ duplicateCount: fetchedRequests.length - addedRequests.length,
682
+ sample: JSON.stringify(fetchedRequests.slice(0, 5)),
683
+ });
684
+ return addedRequests;
685
+ }
686
+ /**
687
+ * @internal wraps public utility for mocking purposes
688
+ */
689
+ async _downloadListOfUrls(options) {
690
+ return downloadListOfUrls({
691
+ ...options,
692
+ httpClient: this.httpClient,
693
+ });
298
694
  }
299
695
  /**
300
696
  * Opens a request queue and returns a promise resolving to an instance
@@ -307,14 +703,33 @@ class RequestQueue extends RequestProvider {
307
703
  *
308
704
  * For more details and code examples, see the {@link RequestQueue} class.
309
705
  *
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.
706
+ * @param [identifier]
707
+ * ID or name of the request queue to be opened. If a string is provided, it will first be
708
+ * looked up as an ID; if no such storage exists, it will be treated as a name.
709
+ * If `null` or `undefined`, the function returns the default request queue associated with the crawler run.
313
710
  * @param [options] Open Request Queue options.
314
711
  */
315
- static async open(...args) {
316
- return super.open(...args);
712
+ static async open(identifier, options = {}) {
713
+ checkStorageAccess();
714
+ ow(options, ow.object.exactShape({
715
+ config: ow.optional.object.instanceOf(Configuration),
716
+ storageBackend: ow.optional.object,
717
+ proxyConfiguration: ow.optional.object,
718
+ httpClient: ow.optional.object,
719
+ }));
720
+ const storageBackend = options.storageBackend ?? serviceLocator.getStorageBackend();
721
+ const config = options.config ?? serviceLocator.getConfiguration();
722
+ await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, config });
723
+ const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'RequestQueue');
724
+ const queue = await serviceLocator
725
+ .getStorageInstanceManager()
726
+ .openStorage(this, {
727
+ ...resolved,
728
+ backendOpener: () => storageBackend.createRequestQueueBackend(resolved),
729
+ backendCacheKey: storageBackend.getStorageBackendCacheKey?.() ?? storageBackend.constructor.name,
730
+ });
731
+ queue.proxyConfiguration = options.proxyConfiguration;
732
+ queue.httpClient = options.httpClient;
733
+ return queue;
317
734
  }
318
735
  }
319
- export { RequestQueue as RequestQueueV1 };
320
- //# sourceMappingURL=request_queue.js.map