@crawlee/core 4.0.0-beta.7 → 4.0.0-beta.70

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