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