@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
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { AsyncQueue } from '@sapphire/async-queue';
|
|
3
|
+
import { s } from '@sapphire/shapeshift';
|
|
4
|
+
import { purgeNullsFromObject, uniqueKeyToRequestId } from '../utils.js';
|
|
5
|
+
import { BaseClient } from './common/base-client.js';
|
|
6
|
+
const requestShape = s
|
|
7
|
+
.object({
|
|
8
|
+
id: s.string(),
|
|
9
|
+
url: s.string().url({ allowedProtocols: ['http:', 'https:'] }),
|
|
10
|
+
uniqueKey: s.string(),
|
|
11
|
+
method: s.string().optional(),
|
|
12
|
+
retryCount: s.number().int().optional(),
|
|
13
|
+
handledAt: s.union([s.string(), s.date().valid()]).optional(),
|
|
14
|
+
})
|
|
15
|
+
.passthrough();
|
|
16
|
+
const requestShapeWithoutId = requestShape.omit(['id']);
|
|
17
|
+
const batchRequestShapeWithoutId = requestShapeWithoutId.array();
|
|
18
|
+
const requestOptionsShape = s.object({
|
|
19
|
+
forefront: s.boolean().optional(),
|
|
20
|
+
});
|
|
21
|
+
export class RequestQueueBackend extends BaseClient {
|
|
22
|
+
name;
|
|
23
|
+
/**
|
|
24
|
+
* The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
|
|
25
|
+
* storages, this is the alias string. Falls back to id.
|
|
26
|
+
*/
|
|
27
|
+
cacheKey;
|
|
28
|
+
createdAt = new Date();
|
|
29
|
+
accessedAt = new Date();
|
|
30
|
+
modifiedAt = new Date();
|
|
31
|
+
handledRequestCount = 0;
|
|
32
|
+
pendingRequestCount = 0;
|
|
33
|
+
/**
|
|
34
|
+
* Serializes every operation that reads-then-writes this backend's shared queue state — the
|
|
35
|
+
* `requests` map, the `forefrontRequestIds` array, the `inProgressRequestIds` set and the request
|
|
36
|
+
* counts. Those mutations span `await` points, so without this mutex a concurrent operation could
|
|
37
|
+
* interleave and corrupt them (e.g. a head scan pruning `forefrontRequestIds` while
|
|
38
|
+
* `addBatchOfRequests` pushes to it). Held by every mutating method as well as by `isEmpty`/
|
|
39
|
+
* `isFinished`, whose head scan also prunes `forefrontRequestIds`.
|
|
40
|
+
*/
|
|
41
|
+
queueStateMutex = new AsyncQueue();
|
|
42
|
+
forefrontRequestIds = [];
|
|
43
|
+
/**
|
|
44
|
+
* IDs of requests currently fetched but not yet handled or reclaimed. A request in this set is
|
|
45
|
+
* "in progress" and will not be handed out again by {@link fetchNextRequest}.
|
|
46
|
+
*
|
|
47
|
+
* Unlike the file-system / platform clients, the in-memory queue lives entirely within a single
|
|
48
|
+
* process and is never shared with another consumer, so there is no need for an expiring,
|
|
49
|
+
* cross-process-visible lock — tracking in-progress requests in this set is enough.
|
|
50
|
+
*/
|
|
51
|
+
inProgressRequestIds = new Set();
|
|
52
|
+
requests = new Map();
|
|
53
|
+
storageBackend;
|
|
54
|
+
constructor(options) {
|
|
55
|
+
super(options.id ?? randomUUID());
|
|
56
|
+
this.name = options.name;
|
|
57
|
+
this.cacheKey = options.cacheKey ?? this.name ?? this.id;
|
|
58
|
+
this.storageBackend = options.storageBackend;
|
|
59
|
+
}
|
|
60
|
+
async getMetadata() {
|
|
61
|
+
this.updateTimestamps(false);
|
|
62
|
+
return this.toRequestQueueInfo();
|
|
63
|
+
}
|
|
64
|
+
async drop() {
|
|
65
|
+
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
|
|
66
|
+
// operation cannot observe half-cleared state — e.g. a forefront id whose request has already been
|
|
67
|
+
// removed, which `listPendingHead` would then dereference as `undefined`.
|
|
68
|
+
await this.queueStateMutex.wait();
|
|
69
|
+
try {
|
|
70
|
+
const storeIndex = this.storageBackend.requestQueueBackendCache.findIndex((queue) => queue.id === this.id);
|
|
71
|
+
if (storeIndex !== -1) {
|
|
72
|
+
const [oldBackend] = this.storageBackend.requestQueueBackendCache.splice(storeIndex, 1);
|
|
73
|
+
oldBackend.pendingRequestCount = 0;
|
|
74
|
+
// Clear all in-memory state, consistent with `purge`. Clearing `requests` alone would
|
|
75
|
+
// leave dangling ids in `forefrontRequestIds`/`inProgressRequestIds`, which a later head
|
|
76
|
+
// scan would resolve to a missing request and dereference.
|
|
77
|
+
oldBackend.requests.clear();
|
|
78
|
+
oldBackend.forefrontRequestIds = [];
|
|
79
|
+
oldBackend.inProgressRequestIds.clear();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
this.queueStateMutex.shift();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async purge() {
|
|
87
|
+
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
|
|
88
|
+
// operation cannot observe or repopulate half-cleared state across the `await` below.
|
|
89
|
+
await this.queueStateMutex.wait();
|
|
90
|
+
try {
|
|
91
|
+
// Clear all in-memory state
|
|
92
|
+
this.requests.clear();
|
|
93
|
+
this.forefrontRequestIds = [];
|
|
94
|
+
this.inProgressRequestIds.clear();
|
|
95
|
+
this.handledRequestCount = 0;
|
|
96
|
+
this.pendingRequestCount = 0;
|
|
97
|
+
this.updateTimestamps(true);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
this.queueStateMutex.shift();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
*requestKeyIterator() {
|
|
104
|
+
for (let i = this.forefrontRequestIds.length - 1; i >= 0; i--) {
|
|
105
|
+
yield this.forefrontRequestIds[i];
|
|
106
|
+
}
|
|
107
|
+
for (const key of this.requests.keys()) {
|
|
108
|
+
yield key;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Scans the queue and returns the pending head — requests that are neither handled nor currently
|
|
113
|
+
* in progress — ordered by `orderNo`, deduplicated.
|
|
114
|
+
*
|
|
115
|
+
* When `detectInProgressRequests` is set, the result also carries an `hasInProgressRequests` flag
|
|
116
|
+
* telling whether any unhandled-but-in-progress request was skipped along the way. It lets
|
|
117
|
+
* {@link isFinished} distinguish "no work left at all" from "work remains, but it is currently being
|
|
118
|
+
* processed". Without it, a consumer with concurrency could consider the queue finished and shut the
|
|
119
|
+
* crawler down while it is still handling the last requests.
|
|
120
|
+
*
|
|
121
|
+
* Computing the flag is expensive: because an in-progress request may sit anywhere in the queue, it
|
|
122
|
+
* forces a scan of every pending entry even when only `limit` items are wanted. Callers that only
|
|
123
|
+
* need the head (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as
|
|
124
|
+
* soon as the page is filled, keeping those calls O(head) instead of O(N).
|
|
125
|
+
*/
|
|
126
|
+
async listPendingHead(limit, detectInProgressRequests = false) {
|
|
127
|
+
const items = [];
|
|
128
|
+
let hasInProgressRequests = false;
|
|
129
|
+
// Tracks processed request IDs to avoid duplicates (request in both `forefrontRequestIds` and `requests`).
|
|
130
|
+
const seenRequestIds = new Set();
|
|
131
|
+
// Tracks handled request IDs from `forefrontRequestIds` to be removed.
|
|
132
|
+
const handledForefrontIds = new Set();
|
|
133
|
+
for (const requestId of this.requestKeyIterator()) {
|
|
134
|
+
// Once the requested page is filled we can stop — unless the caller asked us to detect
|
|
135
|
+
// in-progress requests and we have not yet seen one, in which case we must keep scanning.
|
|
136
|
+
if (items.length >= limit && (!detectInProgressRequests || hasInProgressRequests)) {
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
if (seenRequestIds.has(requestId)) {
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
seenRequestIds.add(requestId);
|
|
143
|
+
const request = this.requests.get(requestId);
|
|
144
|
+
// Permanently-handled requests (`orderNo === null`) are in a terminal state and can be skipped.
|
|
145
|
+
if (request.orderNo === null) {
|
|
146
|
+
if (this.forefrontRequestIds.includes(requestId)) {
|
|
147
|
+
handledForefrontIds.add(requestId);
|
|
148
|
+
}
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
// In progress (fetched but not yet handled or reclaimed) — skip it, but remember that the
|
|
152
|
+
// queue is not truly empty.
|
|
153
|
+
if (this.inProgressRequestIds.has(requestId)) {
|
|
154
|
+
hasInProgressRequests = true;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (items.length < limit) {
|
|
158
|
+
items.push(request);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
this.forefrontRequestIds = this.forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
|
|
162
|
+
return {
|
|
163
|
+
items: items.sort((a, b) => a.orderNo - b.orderNo),
|
|
164
|
+
hasInProgressRequests: detectInProgressRequests ? hasInProgressRequests : undefined,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
async fetchNextRequest() {
|
|
168
|
+
this.updateTimestamps(false);
|
|
169
|
+
await this.queueStateMutex.wait();
|
|
170
|
+
try {
|
|
171
|
+
const { items: [head], } = await this.listPendingHead(1);
|
|
172
|
+
if (!head) {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
// Mark the request as in progress so it is not handed out again until it is handled or
|
|
176
|
+
// reclaimed. The request keeps its `orderNo` (and thus its forefront / normal ordering).
|
|
177
|
+
this.inProgressRequestIds.add(head.id);
|
|
178
|
+
return this._jsonToRequest(head.json) ?? undefined;
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
this.queueStateMutex.shift();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async addBatchOfRequests(requests, options = {}) {
|
|
185
|
+
batchRequestShapeWithoutId.parse(requests);
|
|
186
|
+
requestOptionsShape.parse(options);
|
|
187
|
+
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
|
|
188
|
+
// shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
|
|
189
|
+
// concurrent operation interleaving at one of the `await` points below.
|
|
190
|
+
await this.queueStateMutex.wait();
|
|
191
|
+
try {
|
|
192
|
+
const result = {
|
|
193
|
+
processedRequests: [],
|
|
194
|
+
unprocessedRequests: [],
|
|
195
|
+
};
|
|
196
|
+
for (const model of requests) {
|
|
197
|
+
const requestModel = this._createInternalRequest(model, options.forefront);
|
|
198
|
+
const existingRequestWithId = this.requests.get(requestModel.id);
|
|
199
|
+
if (existingRequestWithId) {
|
|
200
|
+
result.processedRequests.push({
|
|
201
|
+
requestId: existingRequestWithId.id,
|
|
202
|
+
uniqueKey: existingRequestWithId.uniqueKey,
|
|
203
|
+
wasAlreadyHandled: existingRequestWithId.orderNo === null,
|
|
204
|
+
wasAlreadyPresent: true,
|
|
205
|
+
});
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
this.requests.set(requestModel.id, requestModel);
|
|
209
|
+
if (requestModel.orderNo) {
|
|
210
|
+
this.pendingRequestCount += 1;
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
this.handledRequestCount += 1;
|
|
214
|
+
}
|
|
215
|
+
if (options.forefront) {
|
|
216
|
+
this.forefrontRequestIds.push(requestModel.id);
|
|
217
|
+
}
|
|
218
|
+
result.processedRequests.push({
|
|
219
|
+
requestId: requestModel.id,
|
|
220
|
+
uniqueKey: requestModel.uniqueKey,
|
|
221
|
+
// We return wasAlreadyHandled: false even though the request may
|
|
222
|
+
// have been added as handled, because that's how API behaves.
|
|
223
|
+
wasAlreadyHandled: false,
|
|
224
|
+
wasAlreadyPresent: false,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
this.updateTimestamps(true);
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
this.queueStateMutex.shift();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async getRequest(uniqueKey) {
|
|
235
|
+
s.string().parse(uniqueKey);
|
|
236
|
+
this.updateTimestamps(false);
|
|
237
|
+
const id = uniqueKeyToRequestId(uniqueKey);
|
|
238
|
+
const json = this.requests.get(id)?.json;
|
|
239
|
+
return this._jsonToRequest(json);
|
|
240
|
+
}
|
|
241
|
+
async markRequestAsHandled(request) {
|
|
242
|
+
requestShape.parse(request);
|
|
243
|
+
this.updateTimestamps(false);
|
|
244
|
+
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
|
|
245
|
+
// `requests` map, `inProgressRequestIds` set and request counts stay consistent across the
|
|
246
|
+
// `await` points below.
|
|
247
|
+
await this.queueStateMutex.wait();
|
|
248
|
+
try {
|
|
249
|
+
const id = uniqueKeyToRequestId(request.uniqueKey);
|
|
250
|
+
const existingRequest = this.requests.get(id);
|
|
251
|
+
// The request must exist to be marked as handled. We intentionally do NOT require it to still
|
|
252
|
+
// be in progress: marking an already-released request handled must still succeed, otherwise
|
|
253
|
+
// the request could be handed out again and the queue would never finish.
|
|
254
|
+
if (!existingRequest) {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
// A handled request has `orderNo === null`. Marking it again is an idempotent no-op.
|
|
258
|
+
const wasAlreadyHandled = existingRequest.orderNo === null;
|
|
259
|
+
const handledAt = request.handledAt ?? new Date().toISOString();
|
|
260
|
+
const requestModel = this._createInternalRequest({ ...request, handledAt }, false);
|
|
261
|
+
this.requests.set(id, requestModel);
|
|
262
|
+
// The request is no longer in progress for this client.
|
|
263
|
+
this.inProgressRequestIds.delete(id);
|
|
264
|
+
if (!wasAlreadyHandled) {
|
|
265
|
+
this.pendingRequestCount -= 1;
|
|
266
|
+
this.handledRequestCount += 1;
|
|
267
|
+
}
|
|
268
|
+
this.updateTimestamps(true);
|
|
269
|
+
return {
|
|
270
|
+
requestId: id,
|
|
271
|
+
wasAlreadyHandled,
|
|
272
|
+
wasAlreadyPresent: true,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
this.queueStateMutex.shift();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async reclaimRequest(request, options = {}) {
|
|
280
|
+
requestShape.parse(request);
|
|
281
|
+
requestOptionsShape.parse(options);
|
|
282
|
+
this.updateTimestamps(false);
|
|
283
|
+
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
|
|
284
|
+
// `requests` map, `forefrontRequestIds` array and `inProgressRequestIds` set stay consistent
|
|
285
|
+
// across the `await` points below.
|
|
286
|
+
await this.queueStateMutex.wait();
|
|
287
|
+
try {
|
|
288
|
+
const id = uniqueKeyToRequestId(request.uniqueKey);
|
|
289
|
+
const existingRequest = this.requests.get(id);
|
|
290
|
+
// The request must exist and not already be handled to be reclaimed. As with
|
|
291
|
+
// `markRequestAsHandled`, we do NOT require it to still be in progress — returning an
|
|
292
|
+
// already-released request to the queue (e.g. to honor a `forefront` reorder) must still
|
|
293
|
+
// work, rather than have the reclaim silently dropped.
|
|
294
|
+
if (!existingRequest || existingRequest.orderNo === null) {
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
// Reclaiming resets the `orderNo` to a fresh timestamp, restoring the request to the queue
|
|
298
|
+
// (at the front if `forefront`).
|
|
299
|
+
const requestModel = this._createInternalRequest(request, options.forefront);
|
|
300
|
+
this.requests.set(id, requestModel);
|
|
301
|
+
// The request is no longer in progress for this client.
|
|
302
|
+
this.inProgressRequestIds.delete(id);
|
|
303
|
+
if (options.forefront) {
|
|
304
|
+
this.forefrontRequestIds.push(id);
|
|
305
|
+
}
|
|
306
|
+
this.updateTimestamps(true);
|
|
307
|
+
return {
|
|
308
|
+
requestId: id,
|
|
309
|
+
wasAlreadyHandled: false,
|
|
310
|
+
wasAlreadyPresent: true,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
finally {
|
|
314
|
+
this.queueStateMutex.shift();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async isEmpty() {
|
|
318
|
+
this.updateTimestamps(false);
|
|
319
|
+
// "Empty" means there is nothing left to fetch right now — i.e. the next `fetchNextRequest`
|
|
320
|
+
// would return `null`. Requests that are currently in progress are intentionally NOT counted
|
|
321
|
+
// here: they are not fetchable, so the queue is empty from a consumer's point of view. Whether
|
|
322
|
+
// those in-progress requests mean crawling is not yet done is a separate question, answered by
|
|
323
|
+
// `isFinished`.
|
|
324
|
+
//
|
|
325
|
+
// `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
|
|
326
|
+
// racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
|
|
327
|
+
await this.queueStateMutex.wait();
|
|
328
|
+
try {
|
|
329
|
+
const { items } = await this.listPendingHead(1);
|
|
330
|
+
return items.length === 0;
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
this.queueStateMutex.shift();
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
async isFinished() {
|
|
337
|
+
this.updateTimestamps(false);
|
|
338
|
+
// The queue is finished only when there is nothing left to fetch AND nothing currently in
|
|
339
|
+
// progress. Counting in-progress requests is what allows a crawler with concurrency to keep
|
|
340
|
+
// waiting while it still holds the last requests, instead of finishing prematurely.
|
|
341
|
+
//
|
|
342
|
+
// Detecting in-progress requests requires a full scan, hence the `detectInProgressRequests`
|
|
343
|
+
// flag — unlike `fetchNextRequest`/`isEmpty`, which only need the head and can stop early.
|
|
344
|
+
//
|
|
345
|
+
// `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
|
|
346
|
+
// racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
|
|
347
|
+
await this.queueStateMutex.wait();
|
|
348
|
+
try {
|
|
349
|
+
const { items, hasInProgressRequests } = await this.listPendingHead(1, true);
|
|
350
|
+
return items.length === 0 && !hasInProgressRequests;
|
|
351
|
+
}
|
|
352
|
+
finally {
|
|
353
|
+
this.queueStateMutex.shift();
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
|
|
358
|
+
* the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
|
|
359
|
+
* nothing is marked in progress.
|
|
360
|
+
*/
|
|
361
|
+
async listItems() {
|
|
362
|
+
this.updateTimestamps(false);
|
|
363
|
+
// `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state
|
|
364
|
+
// mutex to avoid racing a concurrent mutator at its `await` points.
|
|
365
|
+
await this.queueStateMutex.wait();
|
|
366
|
+
try {
|
|
367
|
+
const { items } = await this.listPendingHead(Number.POSITIVE_INFINITY);
|
|
368
|
+
return items.map((request) => this._jsonToRequest(request.json));
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
this.queueStateMutex.shift();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
toRequestQueueInfo() {
|
|
375
|
+
return {
|
|
376
|
+
accessedAt: this.accessedAt,
|
|
377
|
+
createdAt: this.createdAt,
|
|
378
|
+
handledRequestCount: this.handledRequestCount,
|
|
379
|
+
id: this.id,
|
|
380
|
+
modifiedAt: this.modifiedAt,
|
|
381
|
+
name: this.name,
|
|
382
|
+
pendingRequestCount: this.pendingRequestCount,
|
|
383
|
+
totalRequestCount: this.requests.size,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
updateTimestamps(hasBeenModified) {
|
|
387
|
+
this.accessedAt = new Date();
|
|
388
|
+
if (hasBeenModified) {
|
|
389
|
+
this.modifiedAt = new Date();
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
_jsonToRequest(requestJson) {
|
|
393
|
+
if (!requestJson)
|
|
394
|
+
return undefined;
|
|
395
|
+
const request = JSON.parse(requestJson);
|
|
396
|
+
return purgeNullsFromObject(request);
|
|
397
|
+
}
|
|
398
|
+
_createInternalRequest(request, forefront) {
|
|
399
|
+
const orderNo = this._calculateOrderNo(request, forefront);
|
|
400
|
+
const id = uniqueKeyToRequestId(request.uniqueKey);
|
|
401
|
+
if (request.id && request.id !== id) {
|
|
402
|
+
throw new Error('Request ID does not match its uniqueKey.');
|
|
403
|
+
}
|
|
404
|
+
const json = JSON.stringify({ ...request, id });
|
|
405
|
+
return {
|
|
406
|
+
id,
|
|
407
|
+
json,
|
|
408
|
+
method: request.method,
|
|
409
|
+
orderNo,
|
|
410
|
+
retryCount: request.retryCount ?? 0,
|
|
411
|
+
uniqueKey: request.uniqueKey,
|
|
412
|
+
url: request.url,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
_calculateOrderNo(request, forefront) {
|
|
416
|
+
if (request.handledAt)
|
|
417
|
+
return null;
|
|
418
|
+
const timestamp = Date.now();
|
|
419
|
+
return forefront ? -timestamp : timestamp;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { isBuffer, isStream, toBuffer } from '@crawlee/utils';
|
|
2
|
+
/**
|
|
3
|
+
* Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
|
|
4
|
+
* Storage names and record keys are used as filesystem path components, so a value containing `..`
|
|
5
|
+
* or an absolute path could otherwise escape the intended directory.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveWithinDirectory(baseDirectory: string, segment: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Removes all properties with a null value
|
|
10
|
+
* from the provided object.
|
|
11
|
+
*/
|
|
12
|
+
export declare function purgeNullsFromObject<T>(object: T): T;
|
|
13
|
+
/**
|
|
14
|
+
* Creates a standard request ID (same as Platform).
|
|
15
|
+
*/
|
|
16
|
+
export declare function uniqueKeyToRequestId(uniqueKey: string): string;
|
|
17
|
+
export { isBuffer, isStream, toBuffer };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { resolve, sep } from 'node:path';
|
|
3
|
+
import { isBuffer, isStream, toBuffer } from '@crawlee/utils';
|
|
4
|
+
import { REQUEST_ID_LENGTH } from './consts.js';
|
|
5
|
+
/**
|
|
6
|
+
* Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
|
|
7
|
+
* Storage names and record keys are used as filesystem path components, so a value containing `..`
|
|
8
|
+
* or an absolute path could otherwise escape the intended directory.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveWithinDirectory(baseDirectory, segment) {
|
|
11
|
+
const base = resolve(baseDirectory);
|
|
12
|
+
const resolved = resolve(base, segment);
|
|
13
|
+
if (resolved !== base && !resolved.startsWith(`${base}${sep}`)) {
|
|
14
|
+
throw new Error(`"${segment}" is not allowed because it would resolve outside of the storage directory. ` +
|
|
15
|
+
`Storage names and record keys must not contain path traversal segments ("..") or absolute paths.`);
|
|
16
|
+
}
|
|
17
|
+
return resolved;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Removes all properties with a null value
|
|
21
|
+
* from the provided object.
|
|
22
|
+
*/
|
|
23
|
+
export function purgeNullsFromObject(object) {
|
|
24
|
+
if (object && typeof object === 'object' && !Array.isArray(object)) {
|
|
25
|
+
for (const [key, value] of Object.entries(object)) {
|
|
26
|
+
if (value === null)
|
|
27
|
+
Reflect.deleteProperty(object, key);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return object;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a standard request ID (same as Platform).
|
|
34
|
+
*/
|
|
35
|
+
export function uniqueKeyToRequestId(uniqueKey) {
|
|
36
|
+
const str = createHash('sha256')
|
|
37
|
+
.update(uniqueKey)
|
|
38
|
+
.digest('base64')
|
|
39
|
+
.replace(/(\+|\/|=)/g, '');
|
|
40
|
+
return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;
|
|
41
|
+
}
|
|
42
|
+
export { isBuffer, isStream, toBuffer };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crawlee/core",
|
|
3
|
-
"version": "4.0.0-beta.
|
|
3
|
+
"version": "4.0.0-beta.81",
|
|
4
4
|
"description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.0.0"
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
},
|
|
39
39
|
"homepage": "https://crawlee.dev",
|
|
40
40
|
"scripts": {
|
|
41
|
-
"build": "
|
|
41
|
+
"build": "pnpm clean && pnpm compile && pnpm copy",
|
|
42
42
|
"clean": "rimraf ./dist",
|
|
43
43
|
"compile": "tsc -p tsconfig.build.json",
|
|
44
44
|
"copy": "tsx ../../scripts/copy.ts"
|
|
@@ -53,22 +53,24 @@
|
|
|
53
53
|
"@apify/pseudo_url": "^2.0.59",
|
|
54
54
|
"@apify/timeout": "^0.3.2",
|
|
55
55
|
"@apify/utilities": "^2.15.5",
|
|
56
|
-
"@crawlee/
|
|
57
|
-
"@crawlee/types": "4.0.0-beta.
|
|
58
|
-
"@crawlee/utils": "4.0.0-beta.
|
|
56
|
+
"@crawlee/fs-storage": "4.0.0-beta.81",
|
|
57
|
+
"@crawlee/types": "4.0.0-beta.81",
|
|
58
|
+
"@crawlee/utils": "4.0.0-beta.81",
|
|
59
59
|
"@sapphire/async-queue": "^1.5.5",
|
|
60
|
+
"@sapphire/shapeshift": "^4.0.0",
|
|
60
61
|
"@vladfrangu/async_event_emitter": "^2.4.6",
|
|
62
|
+
"content-type": "^1.0.5",
|
|
61
63
|
"csv-stringify": "^6.5.2",
|
|
62
|
-
"fs-extra": "^11.3.0",
|
|
63
|
-
"got-scraping": "^4.1.1",
|
|
64
64
|
"json5": "^2.2.3",
|
|
65
|
+
"mime-types": "^3.0.1",
|
|
65
66
|
"minimatch": "^10.0.1",
|
|
66
67
|
"ow": "^2.0.0",
|
|
67
68
|
"stream-json": "^1.9.1",
|
|
68
69
|
"tldts": "^7.0.6",
|
|
69
|
-
"tough-cookie": "^
|
|
70
|
+
"tough-cookie": "^6.0.0",
|
|
70
71
|
"tslib": "^2.8.1",
|
|
71
|
-
"type-fest": "^4.41.0"
|
|
72
|
+
"type-fest": "^4.41.0",
|
|
73
|
+
"zod": "^3.24.0 || ^4.0.0"
|
|
72
74
|
},
|
|
73
75
|
"lerna": {
|
|
74
76
|
"command": {
|
|
@@ -77,5 +79,5 @@
|
|
|
77
79
|
}
|
|
78
80
|
}
|
|
79
81
|
},
|
|
80
|
-
"gitHead": "
|
|
82
|
+
"gitHead": "80dc6b4fc82237e63a51a71153809ec8dfd0cc50"
|
|
81
83
|
}
|