@crawlee/basic 4.0.0-rc.0 → 4.0.0-rc.1
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 +1 -1
- package/index.d.ts +11 -1
- package/index.js +11 -0
- package/internals/autoscaling/autoscaled_pool.d.ts +178 -0
- package/internals/autoscaling/autoscaled_pool.js +387 -0
- package/internals/autoscaling/concurrency_system.d.ts +235 -0
- package/internals/autoscaling/concurrency_system.js +357 -0
- package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
- package/internals/autoscaling/cpu_load_signal.js +46 -0
- package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/internals/autoscaling/event_loop_load_signal.js +60 -0
- package/internals/autoscaling/index.d.ts +9 -0
- package/internals/autoscaling/index.js +9 -0
- package/internals/autoscaling/load_signal.d.ts +98 -0
- package/internals/autoscaling/load_signal.js +103 -0
- package/internals/autoscaling/memory_load_signal.d.ts +45 -0
- package/internals/autoscaling/memory_load_signal.js +104 -0
- package/internals/autoscaling/snapshotter.d.ts +84 -0
- package/internals/autoscaling/snapshotter.js +67 -0
- package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/internals/autoscaling/storage_backend_load_signal.js +73 -0
- package/internals/autoscaling/system_status.d.ts +112 -0
- package/internals/autoscaling/system_status.js +139 -0
- package/internals/autoscaling/weighted_avg.d.ts +5 -0
- package/internals/autoscaling/weighted_avg.js +14 -0
- package/internals/basic-crawler.d.ts +77 -310
- package/internals/basic-crawler.js +680 -564
- package/internals/cookie_utils.d.ts +40 -0
- package/internals/cookie_utils.js +122 -0
- package/internals/crawler-run.d.ts +76 -0
- package/internals/crawler-run.js +142 -0
- package/internals/crawlers/context_pipeline.d.ts +75 -0
- package/internals/crawlers/context_pipeline.js +109 -0
- package/internals/crawlers/crawler_commons.d.ts +216 -0
- package/internals/crawlers/crawler_commons.js +1 -0
- package/internals/crawlers/error_snapshotter.d.ts +29 -0
- package/internals/crawlers/error_snapshotter.js +116 -0
- package/internals/crawlers/error_tracker.d.ts +51 -0
- package/internals/crawlers/error_tracker.js +316 -0
- package/internals/crawlers/index.d.ts +4 -0
- package/internals/crawlers/index.js +3 -0
- package/internals/crawlers/internals/types.d.ts +7 -0
- package/internals/crawlers/internals/types.js +1 -0
- package/internals/crawlers/statistics.d.ts +316 -0
- package/internals/crawlers/statistics.js +525 -0
- package/internals/crawling_request.d.ts +86 -0
- package/internals/crawling_request.js +127 -0
- package/internals/enqueue_links/enqueue_links.d.ts +152 -0
- package/internals/enqueue_links/enqueue_links.js +76 -0
- package/internals/enqueue_links/index.d.ts +3 -0
- package/internals/enqueue_links/index.js +3 -0
- package/internals/enqueue_links/shared.d.ts +106 -0
- package/internals/enqueue_links/shared.js +258 -0
- package/internals/errors.d.ts +68 -0
- package/internals/errors.js +83 -0
- package/internals/http.d.ts +9 -0
- package/internals/http.js +28 -0
- package/internals/request-timeout.d.ts +6 -0
- package/internals/request-timeout.js +27 -2
- package/internals/router.d.ts +299 -0
- package/internals/router.js +312 -0
- package/internals/session_pool/consts.d.ts +1 -0
- package/internals/session_pool/consts.js +1 -0
- package/internals/session_pool/errors.d.ts +7 -0
- package/internals/session_pool/errors.js +11 -0
- package/internals/session_pool/fingerprint.d.ts +9 -0
- package/internals/session_pool/fingerprint.js +30 -0
- package/internals/session_pool/index.d.ts +4 -0
- package/internals/session_pool/index.js +4 -0
- package/internals/session_pool/session.d.ts +151 -0
- package/internals/session_pool/session.js +225 -0
- package/internals/session_pool/session_pool.d.ts +193 -0
- package/internals/session_pool/session_pool.js +453 -0
- package/internals/sitemap_request_loader.d.ts +158 -0
- package/internals/sitemap_request_loader.js +432 -0
- package/internals/throttling_request_manager.d.ts +229 -0
- package/internals/throttling_request_manager.js +843 -0
- package/package.json +16 -12
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
|
-
import {
|
|
3
|
+
import { bindMethodsToServiceLocator, Configuration, createStorageTransaction, Request, CriticalError, currentStorageTransaction, Dataset, EnqueueStrategy, EventManager, EventType, getObjectType, KeyValueStore, log, NonRetryableError, OwnedOrInjected, purgeDefaultStorages, RequestManagerTandem, RequestQueue, ServiceLocator, serviceLocator, SessionError, validators, withDirectStorageAccess, } from '@crawlee/core';
|
|
4
4
|
import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client';
|
|
5
|
-
import { isAsyncIterable, isIterable, ROTATE_PROXY_ERRORS } from '@crawlee/utils/internal';
|
|
5
|
+
import { isAsyncIterable, isIterable, parseArgument, ROTATE_PROXY_ERRORS, schemas } from '@crawlee/utils/internal';
|
|
6
6
|
import { RobotsTxtFile } from '@crawlee/utils';
|
|
7
7
|
import { getDomain } from 'tldts';
|
|
8
8
|
import { z } from 'zod';
|
|
9
9
|
import { LruCache } from '@apify/datastructures';
|
|
10
|
-
import { addTimeoutToPromise, extendTimeout, TimeoutError } from '@apify/timeout';
|
|
10
|
+
import { addTimeoutToPromise, extendTimeout, storage as timeoutStorage, TimeoutError, tryCancel } from '@apify/timeout';
|
|
11
11
|
import { cryptoRandomObjectId } from '@apify/utilities';
|
|
12
|
-
import {
|
|
12
|
+
import { ConcurrencySystem } from './autoscaling/concurrency_system.js';
|
|
13
|
+
import { mergeCookies } from './cookie_utils.js';
|
|
14
|
+
import { ContextPipeline } from './crawlers/context_pipeline.js';
|
|
15
|
+
import { CrawlingRequest, RequestState } from './crawling_request.js';
|
|
16
|
+
import { ContextPipelineCleanupError, ContextPipelineInterruptedError, MissingSessionError, NavigationSkippedError, PersistentRateLimitError, ContextPipelineInitializationError, RequestHandlerError, RequestThrottledError, RetryRequestError, } from './errors.js';
|
|
17
|
+
import { Statistics } from './crawlers/statistics.js';
|
|
18
|
+
import { applyRequestTransform, buildEnqueueStrategyPatterns, constructUrlPatternObjects, createRequestOptions, createSkippedRequestArgs, filterRequestOptionsByPatterns, } from './enqueue_links/index.js';
|
|
19
|
+
import { parseRetryAfterHeader } from './http.js';
|
|
20
|
+
import { CrawlerRun } from './crawler-run.js';
|
|
21
|
+
import { extendTimeoutKey, navigationDeadlineKey, raceWithTimeout, suspendTimeoutKey, timeoutExpiredKey, } from './request-timeout.js';
|
|
13
22
|
import { createSendRequest } from './send-request.js';
|
|
23
|
+
import { Router, validateUserData } from './router.js';
|
|
24
|
+
import { BLOCKED_STATUS_CODES } from './session_pool/consts.js';
|
|
25
|
+
import { Session } from './session_pool/session.js';
|
|
26
|
+
import { SessionPool } from './session_pool/session_pool.js';
|
|
27
|
+
import { ThrottlingRequestManager } from './throttling_request_manager.js';
|
|
14
28
|
class LazyDefaultHttpClient extends BaseHttpClient {
|
|
15
29
|
#delegatePromise;
|
|
16
30
|
constructor(options) {
|
|
@@ -40,7 +54,6 @@ class LazyDefaultHttpClient extends BaseHttpClient {
|
|
|
40
54
|
* @ignore
|
|
41
55
|
*/
|
|
42
56
|
const SAFE_MIGRATION_WAIT_MILLIS = 20000;
|
|
43
|
-
const deferredCleanupKey = Symbol('deferredCleanup');
|
|
44
57
|
// The request timeout plumbing (the window helper, the context symbols, and the race) lives in its own module.
|
|
45
58
|
export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
|
|
46
59
|
const urlPatternSchema = z.union([
|
|
@@ -71,14 +84,13 @@ const addRequestsOptionsSchema = z.looseObject({
|
|
|
71
84
|
onSkippedRequest: schemas.anyFunction.optional(),
|
|
72
85
|
});
|
|
73
86
|
export class BasicCrawler {
|
|
74
|
-
static CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
|
|
87
|
+
static #CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
|
|
75
88
|
/**
|
|
76
89
|
* Tracks the number of crawler instances created. The first crawler uses the default
|
|
77
90
|
* request queue; subsequent ones get their own queue via a unique alias so they don't
|
|
78
91
|
* collide.
|
|
79
92
|
*/
|
|
80
|
-
|
|
81
|
-
static instanceCount = 0;
|
|
93
|
+
static #instanceCount = 0;
|
|
82
94
|
/**
|
|
83
95
|
* Tracks crawler instances that accessed shared state without having an explicit id.
|
|
84
96
|
* Used to detect and warn about multiple crawlers sharing the same state.
|
|
@@ -93,12 +105,15 @@ export class BasicCrawler {
|
|
|
93
105
|
get statistics() {
|
|
94
106
|
return this.#statisticsDep.value;
|
|
95
107
|
}
|
|
108
|
+
#requestManager;
|
|
96
109
|
/**
|
|
97
110
|
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
|
|
98
111
|
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
|
|
99
112
|
* via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
|
|
100
113
|
*/
|
|
101
|
-
requestManager
|
|
114
|
+
get requestManager() {
|
|
115
|
+
return this.#requestManager;
|
|
116
|
+
}
|
|
102
117
|
/** Backs the {@link BasicCrawler.sessionPool|`sessionPool`} getter. */
|
|
103
118
|
#sessionPoolDep;
|
|
104
119
|
/**
|
|
@@ -108,12 +123,6 @@ export class BasicCrawler {
|
|
|
108
123
|
get sessionPool() {
|
|
109
124
|
return this.#sessionPoolDep.value;
|
|
110
125
|
}
|
|
111
|
-
/**
|
|
112
|
-
* Tracks **only** the queue the crawler opens for itself — not the {@link RequestManagerTandem} that may wrap it
|
|
113
|
-
* around a user-supplied `requestList` — so the owned-only purge between repeated `run()` calls never reaches
|
|
114
|
-
* through to a borrowed loader. Filled lazily in {@link BasicCrawler.openOwnedRequestQueue|`openOwnedRequestQueue()`}.
|
|
115
|
-
*/
|
|
116
|
-
#ownedRequestQueue = OwnedOrInjected.resolve();
|
|
117
126
|
/**
|
|
118
127
|
* Whether the request-processing-time hint has already been forwarded to the request manager. The hint
|
|
119
128
|
* derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
|
|
@@ -126,31 +135,36 @@ export class BasicCrawler {
|
|
|
126
135
|
* the concurrency shortcuts folded in (owned, so the crawler starts and stops it).
|
|
127
136
|
*/
|
|
128
137
|
#resolveConcurrencySystem;
|
|
129
|
-
/**
|
|
130
|
-
#
|
|
138
|
+
/** The last run started on this instance. It outlives the run, so anything that drives one goes through `#liveRun`. */
|
|
139
|
+
#run;
|
|
140
|
+
#concurrencySystem;
|
|
141
|
+
/** The run in progress, if any — a finished run is history and cannot be driven. */
|
|
142
|
+
get #liveRun() {
|
|
143
|
+
return this.#run?.isLive === true ? this.#run : undefined;
|
|
144
|
+
}
|
|
145
|
+
/** The run whose task loop is dispatching, if any — only that one can be paused and resumed. */
|
|
146
|
+
get #dispatchingRun() {
|
|
147
|
+
return this.#liveRun?.isDispatching === true ? this.#liveRun : undefined;
|
|
148
|
+
}
|
|
149
|
+
/** Whether a {@link BasicCrawler.run|`run()`} is in progress on this instance. */
|
|
150
|
+
get running() {
|
|
151
|
+
return this.#liveRun !== undefined;
|
|
152
|
+
}
|
|
131
153
|
/**
|
|
132
|
-
* The concurrency governor
|
|
154
|
+
* The concurrency governor the run in progress is booking its requests against — either the
|
|
133
155
|
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
|
|
134
156
|
* crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
|
|
135
157
|
*
|
|
136
|
-
* > *NOTE:* `undefined`
|
|
137
|
-
*
|
|
158
|
+
* > *NOTE:* `undefined` outside a run, and a crawler-owned default is rebuilt for every run — so read it
|
|
159
|
+
* during a run rather than caching it across runs.
|
|
138
160
|
*
|
|
139
161
|
* {@link IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
|
|
140
162
|
* owning the instance: build a {@link ConcurrencySystem} yourself and inject it, then set
|
|
141
163
|
* `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
|
|
142
164
|
*/
|
|
143
165
|
get concurrencySystem() {
|
|
144
|
-
return this.#
|
|
166
|
+
return this.#concurrencySystem?.value;
|
|
145
167
|
}
|
|
146
|
-
/**
|
|
147
|
-
* The task loop that dispatches this run's requests. Private on purpose — it is a bare parallel task runner with
|
|
148
|
-
* no configuration left of its own (see {@link ConcurrencySystem}), and everything a caller legitimately did
|
|
149
|
-
* with it now has a crawler-level counterpart: {@link BasicCrawler.pause|`pause()`},
|
|
150
|
-
* {@link BasicCrawler.resume|`resume()`}, {@link BasicCrawler.teardown|`teardown()`} and
|
|
151
|
-
* {@link BasicCrawler.concurrencySystem|`concurrencySystem`}.
|
|
152
|
-
*/
|
|
153
|
-
#autoscaledPool;
|
|
154
168
|
/**
|
|
155
169
|
* A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
|
|
156
170
|
* Only available if used by the crawler.
|
|
@@ -168,40 +182,38 @@ export class BasicCrawler {
|
|
|
168
182
|
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
169
183
|
*
|
|
170
184
|
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
171
|
-
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
172
185
|
*/
|
|
173
|
-
get
|
|
174
|
-
|
|
175
|
-
this.#basicContextPipeline = this.buildBasicContextPipeline();
|
|
176
|
-
}
|
|
186
|
+
get #basicPipeline() {
|
|
187
|
+
this.#basicContextPipeline ??= this.#buildBasicContextPipeline();
|
|
177
188
|
return this.#basicContextPipeline;
|
|
178
189
|
}
|
|
179
190
|
#contextPipeline;
|
|
191
|
+
/** @internal */
|
|
180
192
|
get contextPipeline() {
|
|
181
193
|
if (this.#contextPipeline === undefined) {
|
|
182
|
-
this.#contextPipeline = this
|
|
194
|
+
this.#contextPipeline = this.#buildFinalContextPipeline();
|
|
183
195
|
}
|
|
184
196
|
return this.#contextPipeline;
|
|
185
197
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
198
|
+
#hasFinishedBefore = false;
|
|
199
|
+
/** Whether a `run()` on this instance has already finished - a repeated one continues where it left off. */
|
|
200
|
+
get hasFinishedBefore() {
|
|
201
|
+
return this.#hasFinishedBefore;
|
|
202
|
+
}
|
|
189
203
|
#log;
|
|
190
204
|
get log() {
|
|
191
205
|
return this.#log;
|
|
192
206
|
}
|
|
193
207
|
requestHandler;
|
|
194
|
-
errorHandler;
|
|
195
|
-
failedRequestHandler;
|
|
196
|
-
|
|
197
|
-
requestHandlerTimeoutMillis;
|
|
208
|
+
#errorHandler;
|
|
209
|
+
#failedRequestHandler;
|
|
210
|
+
#requestHandlerTimeoutMillis;
|
|
198
211
|
internalTimeoutMillis;
|
|
199
|
-
maxRequestRetries;
|
|
200
|
-
maxCrawlDepth;
|
|
201
|
-
#
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
return this.statistics.state.requestsFinished + this.statistics.state.requestsFailed;
|
|
212
|
+
#maxRequestRetries;
|
|
213
|
+
#maxCrawlDepth;
|
|
214
|
+
#maxRequestsPerCrawl;
|
|
215
|
+
get #handledRequestsCount() {
|
|
216
|
+
return this.statistics.state.requestsSucceeded + this.statistics.state.requestsFailed;
|
|
205
217
|
}
|
|
206
218
|
#statusMessageLoggingInterval;
|
|
207
219
|
#statusMessageCallback;
|
|
@@ -214,8 +226,7 @@ export class BasicCrawler {
|
|
|
214
226
|
* {@link ConcurrencySystem} instead, and the loop's `consumer` identity is the crawler's own, so neither is
|
|
215
227
|
* settable here.
|
|
216
228
|
*/
|
|
217
|
-
|
|
218
|
-
taskLoopOptions;
|
|
229
|
+
#taskLoopOptions;
|
|
219
230
|
httpClient;
|
|
220
231
|
retryOnBlocked;
|
|
221
232
|
#respectRobotsTxtFile;
|
|
@@ -223,12 +234,13 @@ export class BasicCrawler {
|
|
|
223
234
|
#transactionalStorageEnabled;
|
|
224
235
|
/** The resolved per-storage-type write policy overrides forwarded to each request's transaction. */
|
|
225
236
|
#storageWritePolicy;
|
|
226
|
-
onSkippedRequest;
|
|
227
|
-
#closeEvents;
|
|
228
|
-
#loggedPerRun = new Set();
|
|
237
|
+
#onSkippedRequest;
|
|
229
238
|
#robotsTxtFileCache;
|
|
230
|
-
identity;
|
|
239
|
+
#identity;
|
|
231
240
|
#contextPipelineOptions;
|
|
241
|
+
/**
|
|
242
|
+
* @internal
|
|
243
|
+
*/
|
|
232
244
|
static optionsShape = {
|
|
233
245
|
contextPipelineBuilder: schemas.anyObject.optional(),
|
|
234
246
|
extendContext: schemas.anyFunction.optional(),
|
|
@@ -270,6 +282,7 @@ export class BasicCrawler {
|
|
|
270
282
|
// AutoscaledPool shorthands
|
|
271
283
|
minConcurrency: schemas.anyNumber.optional(),
|
|
272
284
|
maxConcurrency: schemas.anyNumber.optional(),
|
|
285
|
+
initialConcurrency: schemas.anyNumber.optional(),
|
|
273
286
|
maxRequestsPerMinute: schemas.anyNumber
|
|
274
287
|
.refine((value) => Number.isInteger(value) || value === Infinity, 'Expected an integer or infinite number')
|
|
275
288
|
.refine((value) => value >= 1, 'Expected a number greater than or equal to 1')
|
|
@@ -278,12 +291,12 @@ export class BasicCrawler {
|
|
|
278
291
|
statistics: schemas.anyObject.optional(),
|
|
279
292
|
id: z.string().optional(),
|
|
280
293
|
};
|
|
281
|
-
static optionsSchema = z.strictObject(BasicCrawler.optionsShape);
|
|
294
|
+
static #optionsSchema = z.strictObject(BasicCrawler.optionsShape);
|
|
282
295
|
/**
|
|
283
296
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
284
297
|
*/
|
|
285
298
|
constructor(options = {}) {
|
|
286
|
-
const parsedOptions = parseArgument(options, BasicCrawler
|
|
299
|
+
const parsedOptions = parseArgument(options, BasicCrawler.#optionsSchema, 'BasicCrawlerOptions');
|
|
287
300
|
const {
|
|
288
301
|
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
|
|
289
302
|
requestList,
|
|
@@ -292,15 +305,18 @@ export class BasicCrawler {
|
|
|
292
305
|
// Service locator options
|
|
293
306
|
configuration, storageBackend, eventManager, logger,
|
|
294
307
|
// AutoscaledPool shorthands
|
|
295
|
-
minConcurrency, maxConcurrency, maxRequestsPerMinute, blockedStatusCodes: blockedStatusCodesInput, retryOnBlocked, respectRobotsTxtFile, transactionalStorage, onSkippedRequest, requestHandler, requestHandlerTimeoutSecs, errorHandler, failedRequestHandler, statusMessageLoggingInterval, statusMessageCallback, statistics, httpClient, id, } = parsedOptions;
|
|
308
|
+
minConcurrency, maxConcurrency, initialConcurrency, maxRequestsPerMinute, blockedStatusCodes: blockedStatusCodesInput, retryOnBlocked, respectRobotsTxtFile, transactionalStorage, onSkippedRequest, requestHandler, requestHandlerTimeoutSecs, errorHandler, failedRequestHandler, statusMessageLoggingInterval, statusMessageCallback, statistics, httpClient, id, } = parsedOptions;
|
|
296
309
|
// All concurrency configuration lives on the `ConcurrencySystem`, so the shortcuts have nowhere to go once
|
|
297
310
|
// one is supplied - and silently dropping a `maxConcurrency` the user asked for is how crawls end up
|
|
298
311
|
// hammering a site.
|
|
299
312
|
if (concurrencySystem !== undefined &&
|
|
300
|
-
(minConcurrency !== undefined ||
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
313
|
+
(minConcurrency !== undefined ||
|
|
314
|
+
maxConcurrency !== undefined ||
|
|
315
|
+
initialConcurrency !== undefined ||
|
|
316
|
+
maxRequestsPerMinute !== undefined)) {
|
|
317
|
+
throw new Error('The `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute` shortcuts ' +
|
|
318
|
+
'cannot be combined with `concurrencySystem` - they configure the default `ConcurrencySystem` ' +
|
|
319
|
+
'that a supplied one replaces. Pass them to the `ConcurrencySystem` constructor instead.');
|
|
304
320
|
}
|
|
305
321
|
// Create per-crawler service locator if custom services were provided.
|
|
306
322
|
// This wraps every method on the crawler instance so that calls to the global `serviceLocator`
|
|
@@ -328,50 +344,58 @@ export class BasicCrawler {
|
|
|
328
344
|
this.#log = serviceLocator.getLogger().child({ prefix: this.constructor.name });
|
|
329
345
|
// Initialize the Configuration instance to avoid lazy loading in the components
|
|
330
346
|
serviceLocator.getConfiguration();
|
|
331
|
-
const instanceIndex = BasicCrawler
|
|
332
|
-
this
|
|
333
|
-
if (requestManager !== undefined) {
|
|
334
|
-
|
|
335
|
-
throw new Error('The `requestManager` option cannot be used in conjunction with `requestList` and/or `requestQueue`');
|
|
336
|
-
}
|
|
337
|
-
// Both would pace the same domains, from different keys and with no idea of one another.
|
|
338
|
-
if (sameDomainDelaySecs > 0 && supportsDomainThrottling(requestManager)) {
|
|
339
|
-
throw new Error('The `sameDomainDelaySecs` option cannot be combined with a `requestManager` that throttles ' +
|
|
340
|
-
'per domain on its own. Configure the delay on the manager instead, via the ' +
|
|
341
|
-
'`minCrawlDelaySecs` option of `ThrottlingRequestManager`.');
|
|
342
|
-
}
|
|
343
|
-
this.requestManager = requestManager;
|
|
347
|
+
const instanceIndex = BasicCrawler.#instanceCount++;
|
|
348
|
+
this.#identity = { instanceIndex, hasExplicitId: id !== undefined, id: id ?? String(instanceIndex) };
|
|
349
|
+
if (requestManager !== undefined && (requestList !== undefined || requestQueue !== undefined)) {
|
|
350
|
+
throw new Error('The `requestManager` option cannot be used in conjunction with `requestList` and/or `requestQueue`');
|
|
344
351
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
352
|
+
const suppliedManager = requestManager ?? requestQueue;
|
|
353
|
+
// Offered before building a pacer of our own: anything that paces takes the floor - through any
|
|
354
|
+
// number of wrappers, since they all forward - so no domain ends up with two clocks.
|
|
355
|
+
const floorTaken = sameDomainDelaySecs > 0 &&
|
|
356
|
+
(suppliedManager?.recordPacingSignal({
|
|
357
|
+
reason: 'minIntervalEverywhere',
|
|
358
|
+
intervalMs: sameDomainDelaySecs * 1000,
|
|
359
|
+
// What `sameDomainDelaySecs` has always meant: one clock per site, subdomains included.
|
|
360
|
+
scope: 'registrableDomain',
|
|
361
|
+
}) ??
|
|
362
|
+
false);
|
|
363
|
+
const pacerNeeded = sameDomainDelaySecs > 0 && !floorTaken;
|
|
364
|
+
// Built here rather than at first use so it can sit *inside* the tandem below, which is where a
|
|
365
|
+
// loader's transferred requests pass through it.
|
|
366
|
+
const writableManager = pacerNeeded
|
|
367
|
+
? new ThrottlingRequestManager({
|
|
368
|
+
domains: 'all',
|
|
369
|
+
minCrawlDelaySecs: sameDomainDelaySecs,
|
|
370
|
+
throttleBy: 'registrableDomain',
|
|
371
|
+
persistStateKey: `CRAWLEE_THROTTLED_DOMAINS_${this.#identity.id}`,
|
|
372
|
+
// A factory, because the default queue is only opened on first use.
|
|
373
|
+
inner: suppliedManager ?? (() => this.#openOwnedRequestQueue()),
|
|
374
|
+
})
|
|
375
|
+
: suppliedManager;
|
|
376
|
+
if (requestList !== undefined) {
|
|
377
|
+
// The list is read first, while new requests still have somewhere writable to go.
|
|
378
|
+
this.#requestManager = new RequestManagerTandem(requestList, writableManager ?? (() => this.#openOwnedRequestQueue()));
|
|
348
379
|
}
|
|
349
|
-
else if (
|
|
380
|
+
else if (writableManager !== undefined) {
|
|
350
381
|
// A RequestQueue is itself a request manager.
|
|
351
|
-
this
|
|
352
|
-
}
|
|
353
|
-
else if (requestList !== undefined) {
|
|
354
|
-
// A lone read-only `requestList` (deprecated option) is combined with a lazily-opened default queue
|
|
355
|
-
// into a tandem, so that its requests are read first and new ones can still be enqueued during the
|
|
356
|
-
// crawl. The queue is opened on first use; the tandem also forwards `persistState()` to the loader.
|
|
357
|
-
this.requestManager = new RequestManagerTandem(requestList, () => this.openOwnedRequestQueue());
|
|
382
|
+
this.#requestManager = writableManager;
|
|
358
383
|
}
|
|
359
384
|
this.httpClient = httpClient ?? new LazyDefaultHttpClient({ logger: this.log });
|
|
360
385
|
this.proxyConfiguration = proxyConfiguration;
|
|
361
386
|
this.#statusMessageLoggingInterval = statusMessageLoggingInterval;
|
|
362
387
|
this.#statusMessageCallback = statusMessageCallback;
|
|
363
388
|
this.#robotsTxtFileCache = new LruCache({ maxLength: 1000 });
|
|
364
|
-
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
|
|
365
389
|
this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);
|
|
366
390
|
this.#ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);
|
|
367
391
|
this.requestHandler = requestHandler ?? this.router;
|
|
368
|
-
this
|
|
369
|
-
this
|
|
392
|
+
this.#failedRequestHandler = failedRequestHandler;
|
|
393
|
+
this.#errorHandler = errorHandler;
|
|
370
394
|
if (requestHandlerTimeoutSecs) {
|
|
371
|
-
this
|
|
395
|
+
this.#requestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
372
396
|
}
|
|
373
397
|
else {
|
|
374
|
-
this
|
|
398
|
+
this.#requestHandlerTimeoutMillis = 60_000;
|
|
375
399
|
}
|
|
376
400
|
this.retryOnBlocked = retryOnBlocked;
|
|
377
401
|
this.#respectRobotsTxtFile = respectRobotsTxtFile;
|
|
@@ -379,14 +403,13 @@ export class BasicCrawler {
|
|
|
379
403
|
const transactionalStorageOption = transactionalStorage;
|
|
380
404
|
this.#transactionalStorageEnabled = transactionalStorageOption !== false;
|
|
381
405
|
this.#storageWritePolicy = typeof transactionalStorageOption === 'object' ? transactionalStorageOption : {};
|
|
382
|
-
this
|
|
406
|
+
this.#onSkippedRequest = onSkippedRequest;
|
|
383
407
|
// allow at least 5min for internal timeouts
|
|
384
408
|
this.internalTimeoutMillis =
|
|
385
409
|
serviceLocator.getConfiguration().internalTimeoutMillis ??
|
|
386
|
-
Math.max(this
|
|
387
|
-
this
|
|
388
|
-
this
|
|
389
|
-
this.#sameDomainDelaySecs = sameDomainDelaySecs;
|
|
410
|
+
Math.max(this.#requestHandlerTimeoutMillis * 2, 300e3);
|
|
411
|
+
this.#maxRequestRetries = maxRequestRetries;
|
|
412
|
+
this.#maxCrawlDepth = maxCrawlDepth;
|
|
390
413
|
this.#statisticsDep = OwnedOrInjected.resolve(statistics,
|
|
391
414
|
// A crawler-built default tracks the built-in fields only. A non-empty `StatisticStateExtension` can
|
|
392
415
|
// only be satisfied by an injected instance carrying the matching `state`, so this branch does
|
|
@@ -394,7 +417,7 @@ export class BasicCrawler {
|
|
|
394
417
|
() => new Statistics({
|
|
395
418
|
logMessage: `${this.constructor.name} request statistics:`,
|
|
396
419
|
log: this.log,
|
|
397
|
-
id: this
|
|
420
|
+
id: this.#identity.id,
|
|
398
421
|
}));
|
|
399
422
|
if (sessionPool && proxyConfiguration) {
|
|
400
423
|
this.log.warning('Both `sessionPool` and `proxyConfiguration` were provided to the crawler. ' +
|
|
@@ -405,19 +428,21 @@ export class BasicCrawler {
|
|
|
405
428
|
this.#sessionPoolDep = OwnedOrInjected.resolve(sessionPool, () => new SessionPool({
|
|
406
429
|
createSessionFunction: async (opts) => new Session({
|
|
407
430
|
...opts?.sessionOptions,
|
|
408
|
-
proxyInfo:
|
|
431
|
+
proxyInfo: this.proxyConfiguration
|
|
432
|
+
? await this.proxyConfiguration.newProxyInfo(opts?.sessionOptions?.proxyInfo)
|
|
433
|
+
: opts?.sessionOptions?.proxyInfo,
|
|
409
434
|
}),
|
|
410
435
|
}));
|
|
411
436
|
this.blockedStatusCodes = new Set(blockedStatusCodesInput ?? BLOCKED_STATUS_CODES);
|
|
412
437
|
const maxSignedInteger = 2 ** 31 - 1;
|
|
413
|
-
if (this
|
|
414
|
-
this.log.warning(`requestHandlerTimeoutMillis ${this
|
|
438
|
+
if (this.#requestHandlerTimeoutMillis > maxSignedInteger) {
|
|
439
|
+
this.log.warning(`requestHandlerTimeoutMillis ${this.#requestHandlerTimeoutMillis}` +
|
|
415
440
|
` does not fit a signed 32-bit integer. Limiting the value to ${maxSignedInteger}`);
|
|
416
|
-
this
|
|
441
|
+
this.#requestHandlerTimeoutMillis = maxSignedInteger;
|
|
417
442
|
}
|
|
418
443
|
this.internalTimeoutMillis = Math.min(this.internalTimeoutMillis, maxSignedInteger);
|
|
419
|
-
this
|
|
420
|
-
const isMaxPagesExceeded = () => this
|
|
444
|
+
this.#maxRequestsPerCrawl = maxRequestsPerCrawl;
|
|
445
|
+
const isMaxPagesExceeded = () => this.#maxRequestsPerCrawl && this.#maxRequestsPerCrawl <= this.#handledRequestsCount;
|
|
421
446
|
// eslint-disable-next-line prefer-const
|
|
422
447
|
let { isFinishedFunction, isTaskReadyFunction } = taskLoopOptions;
|
|
423
448
|
// override even if `isFinishedFunction` provided by user - `keepAlive` has higher priority
|
|
@@ -429,90 +454,74 @@ export class BasicCrawler {
|
|
|
429
454
|
const source = this.requestManager;
|
|
430
455
|
if (!source)
|
|
431
456
|
throw new Error('Request provider is not initialized!');
|
|
432
|
-
const request = await this
|
|
457
|
+
const request = await this.#resolveRequest();
|
|
433
458
|
if (!request) {
|
|
434
459
|
return;
|
|
435
460
|
}
|
|
436
461
|
// Started here, rather than in `handleRequest`, so that a failure during context pipeline
|
|
437
462
|
// initialization (e.g. a browser page timing out before the request handler ever runs) is
|
|
438
|
-
// still accounted for by `
|
|
439
|
-
|
|
463
|
+
// still accounted for by `recordRequestFailure` below - which is a no-op without a
|
|
464
|
+
// matching `recordRequestStart`.
|
|
465
|
+
this.statistics.recordRequestStart(request.id || request.uniqueKey);
|
|
440
466
|
const crawlingContext = { request };
|
|
441
467
|
try {
|
|
442
468
|
// The transaction spans the whole pipeline call, covering the navigation hooks
|
|
443
|
-
// and `extendContext` too; `handleRequest`
|
|
469
|
+
// and `extendContext` too; `handleRequest` commits it and `handleRequestFailure` rolls it back.
|
|
444
470
|
await this.runInStorageTransaction(async () =>
|
|
445
471
|
// Navigation, the navigation hooks and the request handler are timed individually, but the
|
|
446
472
|
// phases between them are not, so a request could still get stuck indefinitely. This is the
|
|
447
473
|
// catch-all for that - see `raceWithTimeout` for why it is a bare timer, not a timeout frame.
|
|
448
|
-
await this
|
|
449
|
-
.chain(this.contextPipeline)
|
|
450
|
-
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request))));
|
|
474
|
+
await this.#withRequestTimeout(crawlingContext, this.#basicPipeline.chain(this.contextPipeline).call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request), (error) => this.#handleRequestFailure(error, crawlingContext, source, request))));
|
|
451
475
|
}
|
|
452
476
|
catch (error) {
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
if (error instanceof
|
|
456
|
-
this
|
|
457
|
-
await this.timeoutAndRetry(async () => this.requestManager?.markRequestAsHandled(request), this.internalTimeoutMillis, `Marking request ${crawlingContext.request.url} (${crawlingContext.request.id}) as handled timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
458
|
-
return;
|
|
459
|
-
}
|
|
460
|
-
// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
|
|
461
|
-
// i.e. not in user's requestHandler), handle it through the normal error flow. A bare `TimeoutError`
|
|
462
|
-
// here is the internal timeout above firing - anything else thrown inside the pipeline arrives wrapped.
|
|
463
|
-
const isPipelineError = error instanceof ContextPipelineInitializationError ||
|
|
464
|
-
error instanceof SessionError ||
|
|
465
|
-
error instanceof TimeoutError;
|
|
466
|
-
if (isPipelineError) {
|
|
467
|
-
const unwrappedError = this.unwrapError(error);
|
|
477
|
+
// The internal timeout above fired, or `handleRequestFailure` threw a `SessionError` - both
|
|
478
|
+
// take the normal error flow. Anything else is fatal.
|
|
479
|
+
if (error instanceof SessionError || crawlingContext[timeoutExpiredKey]?.()) {
|
|
480
|
+
const unwrappedError = this.#unwrapError(error);
|
|
468
481
|
await this.requestFunctionErrorHandler(unwrappedError, crawlingContext, request, this.requestManager);
|
|
469
|
-
|
|
470
|
-
// skip `markBad` to avoid double-counting usage/error score.
|
|
471
|
-
if (!this.errorAbsolvesSession(unwrappedError)) {
|
|
482
|
+
if (!this.#errorAbsolvesSession(unwrappedError)) {
|
|
472
483
|
crawlingContext.session?.markBad();
|
|
473
484
|
}
|
|
474
485
|
return;
|
|
475
486
|
}
|
|
476
|
-
throw this
|
|
477
|
-
}
|
|
478
|
-
finally {
|
|
479
|
-
// Run request-scoped deferred cleanups only after the whole request lifecycle - including the user's error handler - has finished.
|
|
480
|
-
const deferredCleanup = crawlingContext[deferredCleanupKey] ?? [];
|
|
481
|
-
await Promise.all(deferredCleanup.map((fn) => fn().catch((cleanupError) => this.log.debug('Error in deferred cleanup', { error: cleanupError }))));
|
|
487
|
+
throw this.#unwrapError(error);
|
|
482
488
|
}
|
|
483
489
|
},
|
|
484
490
|
isTaskReadyFunction: async () => {
|
|
485
491
|
if (isMaxPagesExceeded()) {
|
|
486
|
-
this
|
|
487
|
-
`${this
|
|
492
|
+
this.#liveRun?.logOnce('shuttingDown', 'Crawler reached the maxRequestsPerCrawl limit of ' +
|
|
493
|
+
`${this.#maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`);
|
|
488
494
|
return false;
|
|
489
495
|
}
|
|
490
|
-
if (this.#
|
|
491
|
-
this
|
|
496
|
+
if (this.#run?.stopRequested) {
|
|
497
|
+
this.#liveRun?.logOnce('shuttingDown', 'No new requests are allowed because the `stop()` method has been called. ' +
|
|
492
498
|
'Ongoing requests will be allowed to complete.');
|
|
493
499
|
return false;
|
|
494
500
|
}
|
|
495
|
-
return isTaskReadyFunction ? await isTaskReadyFunction() : await this
|
|
501
|
+
return isTaskReadyFunction ? await isTaskReadyFunction() : await this.#isTaskReadyFunction();
|
|
496
502
|
},
|
|
497
503
|
isFinishedFunction: async () => {
|
|
498
504
|
if (isMaxPagesExceeded()) {
|
|
499
|
-
this.log.info(`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${this
|
|
505
|
+
this.log.info(`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${this.#maxRequestsPerCrawl} requests ` +
|
|
500
506
|
'and all requests that were in progress at that time have now finished. ' +
|
|
501
|
-
`In total, the crawler processed ${this
|
|
507
|
+
`In total, the crawler processed ${this.#handledRequestsCount} requests and will shut down.`);
|
|
502
508
|
return true;
|
|
503
509
|
}
|
|
504
|
-
if (this.#
|
|
510
|
+
if (this.#run?.stopRequested) {
|
|
505
511
|
this.log.info('The crawler has finished all the remaining ongoing requests and will shut down now.');
|
|
506
512
|
return true;
|
|
507
513
|
}
|
|
508
|
-
//
|
|
509
|
-
// crawl that cannot progress
|
|
510
|
-
|
|
511
|
-
|
|
514
|
+
// `maybeFinish()` calls this only once nothing is in flight (`autoscaled_pool.ts`) - the point
|
|
515
|
+
// where a crawl that cannot progress becomes distinguishable from one that is merely waiting,
|
|
516
|
+
// and the only place where throwing does not abandon requests mid-processing.
|
|
517
|
+
const state = await this.requestManager?.checkReadiness();
|
|
518
|
+
// Under `keepAlive`, outliving a domain that will not let us through is the whole point.
|
|
519
|
+
if (state?.status === 'stalled' && !keepAlive) {
|
|
520
|
+
throw new PersistentRateLimitError(`Giving up: ${state.reason}`);
|
|
512
521
|
}
|
|
513
522
|
const isFinished = isFinishedFunction
|
|
514
523
|
? await isFinishedFunction()
|
|
515
|
-
:
|
|
524
|
+
: state === undefined || state.status === 'finished';
|
|
516
525
|
if (isFinished) {
|
|
517
526
|
const reason = isFinishedFunction
|
|
518
527
|
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
|
|
@@ -523,11 +532,14 @@ export class BasicCrawler {
|
|
|
523
532
|
},
|
|
524
533
|
log: this.log,
|
|
525
534
|
};
|
|
526
|
-
this
|
|
535
|
+
this.#taskLoopOptions = { ...taskLoopOptions, ...crawlerOwnedTaskLoopConfiguration };
|
|
527
536
|
this.#resolveConcurrencySystem = () => OwnedOrInjected.resolve(concurrencySystem, () => this.createDefaultConcurrencySystem({
|
|
528
537
|
minConcurrency,
|
|
529
538
|
maxConcurrency,
|
|
530
539
|
maxTasksPerMinute: maxRequestsPerMinute,
|
|
540
|
+
// Spread conditionally - an explicit `undefined` would clobber a subclass default, see
|
|
541
|
+
// `HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS`.
|
|
542
|
+
...(initialConcurrency !== undefined && { desiredConcurrency: initialConcurrency }),
|
|
531
543
|
log: this.log,
|
|
532
544
|
}));
|
|
533
545
|
}
|
|
@@ -537,7 +549,7 @@ export class BasicCrawler {
|
|
|
537
549
|
}
|
|
538
550
|
/**
|
|
539
551
|
* Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
|
|
540
|
-
* `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
552
|
+
* `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
541
553
|
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
|
|
542
554
|
*
|
|
543
555
|
* Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
|
|
@@ -561,35 +573,21 @@ export class BasicCrawler {
|
|
|
561
573
|
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
562
574
|
* This handles base context creation, session resolution, and context helpers.
|
|
563
575
|
*/
|
|
564
|
-
buildBasicContextPipeline() {
|
|
576
|
+
#buildBasicContextPipeline() {
|
|
565
577
|
return ContextPipeline.create()
|
|
566
|
-
.compose(
|
|
567
|
-
.compose(
|
|
568
|
-
.compose(
|
|
569
|
-
.compose(
|
|
578
|
+
.compose(this.#checkRobotsTxt.bind(this))
|
|
579
|
+
.compose(this.#createBaseContext.bind(this))
|
|
580
|
+
.compose(this.#resolveSession.bind(this))
|
|
581
|
+
.compose(this.#createContextHelpers.bind(this));
|
|
570
582
|
}
|
|
571
|
-
async checkRobotsTxt({ request }) {
|
|
572
|
-
if (!(await this
|
|
583
|
+
async #checkRobotsTxt({ request }) {
|
|
584
|
+
if (!(await this.#isAllowedBasedOnRobotsTxtFile(request.url))) {
|
|
573
585
|
this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`);
|
|
574
|
-
|
|
575
|
-
request.noRetry = true;
|
|
576
|
-
await this.handleSkippedRequest({
|
|
577
|
-
url: request.url,
|
|
578
|
-
reason: 'robotsTxt',
|
|
579
|
-
});
|
|
580
|
-
throw new ContextPipelineInterruptedError(`Skipping request ${request.url} as disallowed by robots.txt`);
|
|
586
|
+
throw new ContextPipelineInterruptedError('robotsTxt');
|
|
581
587
|
}
|
|
582
588
|
return {};
|
|
583
589
|
}
|
|
584
|
-
|
|
585
|
-
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
586
|
-
* Subclasses should override this to add their own pipeline stages.
|
|
587
|
-
*/
|
|
588
|
-
buildContextPipeline() {
|
|
589
|
-
return ContextPipeline.create();
|
|
590
|
-
}
|
|
591
|
-
createBaseContext(context) {
|
|
592
|
-
const deferredCleanup = [];
|
|
590
|
+
#createBaseContext(context, onCleanup) {
|
|
593
591
|
return {
|
|
594
592
|
id: cryptoRandomObjectId(10),
|
|
595
593
|
log: this.log,
|
|
@@ -597,7 +595,23 @@ export class BasicCrawler {
|
|
|
597
595
|
useState: this.useState.bind(this),
|
|
598
596
|
getKeyValueStore: async (identifier) => KeyValueStore.open(identifier),
|
|
599
597
|
registerDeferredCleanup: (cleanup) => {
|
|
600
|
-
|
|
598
|
+
onCleanup(async () => {
|
|
599
|
+
try {
|
|
600
|
+
await cleanup();
|
|
601
|
+
}
|
|
602
|
+
catch (error) {
|
|
603
|
+
this.log.debug('Error in deferred cleanup', { error });
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
},
|
|
607
|
+
afterStorageCommit: (callback) => {
|
|
608
|
+
const transaction = currentStorageTransaction();
|
|
609
|
+
if (transaction === undefined) {
|
|
610
|
+
throw new Error('afterStorageCommit() needs an active storage transaction, and there is none. ' +
|
|
611
|
+
"With `transactionalStorage: false` the request's writes are applied as they are " +
|
|
612
|
+
'made, so they throw at the call site instead of at commit time.');
|
|
613
|
+
}
|
|
614
|
+
transaction.afterCommit(callback);
|
|
601
615
|
},
|
|
602
616
|
extendTimeout: (secs) => {
|
|
603
617
|
const extraMillis = secs * 1000;
|
|
@@ -610,29 +624,43 @@ export class BasicCrawler {
|
|
|
610
624
|
if (context[navigationDeadlineKey] !== undefined) {
|
|
611
625
|
context[navigationDeadlineKey] += extraMillis;
|
|
612
626
|
}
|
|
627
|
+
// Extension failure must not fail the request that asked for more time.
|
|
628
|
+
this.requestManager?.extendRequestProcessingTimeSecs?.(context.request, secs)?.catch((error) => {
|
|
629
|
+
this.log.debug('Extending the request processing time failed', { url: context.request.url, error });
|
|
630
|
+
});
|
|
631
|
+
},
|
|
632
|
+
skipRequest: (message) => {
|
|
633
|
+
this.log.debug(`Skipping request ${context.request.url} (${context.request.id})${message ? `: ${message}` : ''}`);
|
|
634
|
+
throw new ContextPipelineInterruptedError('manual', message);
|
|
613
635
|
},
|
|
614
|
-
[deferredCleanupKey]: deferredCleanup,
|
|
615
636
|
};
|
|
616
637
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
638
|
+
/**
|
|
639
|
+
* Fetches the next request and rebuilds it as a {@link CrawlingRequest}. A copy rather than the manager's
|
|
640
|
+
* instance: managers key on `uniqueKey`/`id`, and it is this copy that flows back into `reclaimRequest` /
|
|
641
|
+
* `markRequestAsHandled`, so nothing observes the difference.
|
|
642
|
+
*/
|
|
643
|
+
async #resolveRequest() {
|
|
644
|
+
const fetched = await this.#timeoutAndRetry(this.#fetchNextRequest.bind(this), this.internalTimeoutMillis, `Fetching next request timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
645
|
+
if (!fetched) {
|
|
646
|
+
return null;
|
|
622
647
|
}
|
|
648
|
+
const request = CrawlingRequest.fromSchema(fetched);
|
|
649
|
+
// Reset loadedUrl so an old one is not carried over to retries.
|
|
650
|
+
request.loadedUrl = undefined;
|
|
623
651
|
return request;
|
|
624
652
|
}
|
|
625
|
-
async resolveSession({ request }) {
|
|
626
|
-
const session = await this
|
|
653
|
+
async #resolveSession({ request }) {
|
|
654
|
+
const session = await this.#timeoutAndRetry(async () => {
|
|
627
655
|
const existingSession = await this.sessionPool.getSession(request.sessionId);
|
|
628
656
|
if (!existingSession) {
|
|
629
|
-
throw new
|
|
657
|
+
throw new MissingSessionError(request.sessionId);
|
|
630
658
|
}
|
|
631
659
|
return existingSession;
|
|
632
660
|
}, this.internalTimeoutMillis, `Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
633
661
|
return { session, proxyInfo: session?.proxyInfo };
|
|
634
662
|
}
|
|
635
|
-
async createContextHelpers({ request, session }) {
|
|
663
|
+
async #createContextHelpers({ request, session }) {
|
|
636
664
|
const addRequests = async (requests, options = {}) => {
|
|
637
665
|
const newCrawlDepth = request.crawlDepth + 1;
|
|
638
666
|
const requestsGenerator = this.addCrawlDepthRequestGenerator(requests, newCrawlDepth);
|
|
@@ -641,9 +669,9 @@ export class BasicCrawler {
|
|
|
641
669
|
const sendRequest = createSendRequest(this.httpClient, request, session);
|
|
642
670
|
return { addRequests, sendRequest };
|
|
643
671
|
}
|
|
644
|
-
buildFinalContextPipeline() {
|
|
672
|
+
#buildFinalContextPipeline() {
|
|
645
673
|
const subclassPipeline = (this.#contextPipelineOptions.contextPipelineBuilder?.() ??
|
|
646
|
-
|
|
674
|
+
ContextPipeline.create());
|
|
647
675
|
// `extendContext` runs *before* the subclass navigation pipeline (which includes the
|
|
648
676
|
// pre/post-navigation hooks). This makes the extension visible to those hooks and to the
|
|
649
677
|
// request handler alike. The trade-off is that `extendContext` cannot access
|
|
@@ -658,26 +686,21 @@ export class BasicCrawler {
|
|
|
658
686
|
let contextPipeline;
|
|
659
687
|
if (extendContext !== undefined) {
|
|
660
688
|
contextPipeline = ContextPipeline.create()
|
|
661
|
-
.compose(
|
|
689
|
+
.compose(async (context) => await extendContext(context))
|
|
662
690
|
.chain(subclassPipeline);
|
|
663
691
|
}
|
|
664
692
|
else {
|
|
665
693
|
contextPipeline = subclassPipeline;
|
|
666
694
|
}
|
|
667
|
-
contextPipeline = contextPipeline.compose({
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
await this.handleSkippedRequest({ url: request.url, reason: 'redirect' });
|
|
677
|
-
throw new ContextPipelineInterruptedError(message);
|
|
678
|
-
}
|
|
679
|
-
return context;
|
|
680
|
-
},
|
|
695
|
+
contextPipeline = contextPipeline.compose(async (context) => {
|
|
696
|
+
const { request } = context;
|
|
697
|
+
if (request && !this.#requestMatchesEnqueueStrategy(request)) {
|
|
698
|
+
// eslint-disable-next-line dot-notation
|
|
699
|
+
const message = `Skipping request ${request.id} (starting url: ${request.url} -> loaded url: ${request.loadedUrl}) because it does not match the enqueue strategy (${request['enqueueStrategy']}).`;
|
|
700
|
+
this.log.debug(message);
|
|
701
|
+
throw new ContextPipelineInterruptedError('redirect');
|
|
702
|
+
}
|
|
703
|
+
return context;
|
|
681
704
|
});
|
|
682
705
|
return contextPipeline;
|
|
683
706
|
}
|
|
@@ -688,7 +711,7 @@ export class BasicCrawler {
|
|
|
688
711
|
* @param error The error to check.
|
|
689
712
|
*/
|
|
690
713
|
isProxyError(error) {
|
|
691
|
-
return ROTATE_PROXY_ERRORS.some((x) => this.getMessageFromError(error)
|
|
714
|
+
return ROTATE_PROXY_ERRORS.some((x) => this.getMessageFromError(error).includes(x));
|
|
692
715
|
}
|
|
693
716
|
/**
|
|
694
717
|
* Sets the status message for the current crawler run.
|
|
@@ -701,19 +724,21 @@ export class BasicCrawler {
|
|
|
701
724
|
*/
|
|
702
725
|
setStatusMessage(message, options = {}) {
|
|
703
726
|
const data = options.isStatusMessageTerminal != null ? { terminal: options.isStatusMessageTerminal } : undefined;
|
|
704
|
-
|
|
727
|
+
// Each allowed level has its own method on the logger, so this goes through them rather than through
|
|
728
|
+
// `logWithLevel`, which is abstract and therefore cannot be instrumented.
|
|
729
|
+
this.log[{ DEBUG: 'debug', INFO: 'info', WARNING: 'warning', ERROR: 'error' }[options.level ?? 'DEBUG']](message, data);
|
|
705
730
|
// Broadcast the status message through the event system. Consumers (e.g. the Apify SDK) can
|
|
706
731
|
// subscribe to `EventType.STATUS_MESSAGE` and propagate it to their status-reporting backend.
|
|
707
732
|
// Setting the status message is not a storage concern, so we intentionally don't route it
|
|
708
733
|
// through the storage client anymore.
|
|
709
734
|
serviceLocator.getEventManager().emit(EventType.STATUS_MESSAGE, {
|
|
710
|
-
crawlerId: this
|
|
735
|
+
crawlerId: this.#identity.id,
|
|
711
736
|
message,
|
|
712
737
|
isStatusMessageTerminal: options.isStatusMessageTerminal,
|
|
713
738
|
level: options.level,
|
|
714
739
|
});
|
|
715
740
|
}
|
|
716
|
-
getPeriodicLogger() {
|
|
741
|
+
#getPeriodicLogger() {
|
|
717
742
|
let previousState = { ...this.statistics.state };
|
|
718
743
|
const getOperationMode = () => {
|
|
719
744
|
const { requestsFailed } = this.statistics.state;
|
|
@@ -733,7 +758,7 @@ export class BasicCrawler {
|
|
|
733
758
|
}
|
|
734
759
|
else {
|
|
735
760
|
const total = await this.requestManager?.getTotalCount();
|
|
736
|
-
message = `Crawled ${this.statistics.state.
|
|
761
|
+
message = `Crawled ${this.statistics.state.requestsSucceeded}${total ? `/${total}` : ''} pages, ${this.statistics.state.requestsFailed} failed requests, desired concurrency ${this.concurrencySystem?.desiredConcurrency ?? 0}.`;
|
|
737
762
|
}
|
|
738
763
|
if (this.#statusMessageCallback) {
|
|
739
764
|
await this.#statusMessageCallback({
|
|
@@ -757,120 +782,141 @@ export class BasicCrawler {
|
|
|
757
782
|
* We can use the `requests` parameter to enqueue the initial requests — it is a shortcut for
|
|
758
783
|
* running {@link BasicCrawler.addRequests|`crawler.addRequests()`} before {@link BasicCrawler.run|`crawler.run()`}.
|
|
759
784
|
*
|
|
785
|
+
* Calling `run()` again on the same instance keeps crawling the same request manager - requests the previous
|
|
786
|
+
* run handled (a failed one counts as handled) are not processed again. Purge the queue or open a fresh one
|
|
787
|
+
* if that is what you want.
|
|
788
|
+
*
|
|
760
789
|
* @param [requests] The requests to add.
|
|
761
|
-
* @param [options] Options for the
|
|
790
|
+
* @param [options] Options for adding the initial requests.
|
|
762
791
|
*/
|
|
763
792
|
async run(requests, options) {
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
if (this.hasFinishedBefore) {
|
|
769
|
-
// When executing the run method for the second time explicitly,
|
|
770
|
-
// we need to purge the RQ to allow processing the same requests again — this is important so users can
|
|
771
|
-
// pass in failed requests back to the `crawler.run()`, otherwise they would be considered as handled and
|
|
772
|
-
// ignored — as a failed request is still handled.
|
|
773
|
-
// By default (`purgeRequestQueue` unset), only the queue we opened ourselves is purged.
|
|
774
|
-
// When `purgeRequestQueue` is explicitly `true`, we also purge a user-supplied manager.
|
|
775
|
-
// When `purgeRequestQueue` is explicitly `false`, nothing is purged.
|
|
776
|
-
const shouldPurge = purgeRequestQueue !== false;
|
|
777
|
-
const managerToPurge = this.#ownedRequestQueue.maybeValue ?? (purgeRequestQueue === true ? this.requestManager : undefined);
|
|
778
|
-
if (shouldPurge) {
|
|
779
|
-
await managerToPurge?.purge?.();
|
|
780
|
-
// The per-domain queues a `sameDomainDelaySecs` wrapper created are the crawler's own, whatever
|
|
781
|
-
// sits underneath them - so they are emptied even when the manager they wrap is spared. Purging
|
|
782
|
-
// the wrapper itself has already covered them.
|
|
783
|
-
if (this.requestManager instanceof ThrottlingRequestManager && managerToPurge !== this.requestManager) {
|
|
784
|
-
await this.requestManager.purgeDomainQueues();
|
|
785
|
-
}
|
|
793
|
+
// A crawl is the top level of its own transaction and timeout scope, not a participant in the caller's.
|
|
794
|
+
return withDirectStorageAccess(async () => timeoutStorage.exit(async () => {
|
|
795
|
+
if (this.running) {
|
|
796
|
+
throw new Error('This crawler instance is already running, you can add more requests to it via `crawler.addRequests()`.');
|
|
786
797
|
}
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
}
|
|
809
|
-
catch (error) {
|
|
810
|
-
// Clean up here before propagating, otherwise a failed startup would leave the process hanging.
|
|
811
|
-
await this.teardown().catch((teardownError) => {
|
|
812
|
-
this.log.exception(teardownError, 'Cleaning up after a failed crawler startup failed.');
|
|
798
|
+
if (this.#hasFinishedBefore) {
|
|
799
|
+
// A supplied statistics instance keeps whatever state it was handed - only wipe a default we built.
|
|
800
|
+
await this.#statisticsDep.ifOwned(async (stats) => {
|
|
801
|
+
stats.reset();
|
|
802
|
+
await stats.resetStore();
|
|
803
|
+
});
|
|
804
|
+
// A session pool the crawler built follows the same blank-slate rule as its statistics.
|
|
805
|
+
await this.#sessionPoolDep.ifOwned(async (pool) => {
|
|
806
|
+
pool.reset();
|
|
807
|
+
await pool.resetStore();
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
// An owned governor is rebuilt for every run, so it always starts from a clean slate — stale
|
|
811
|
+
// resource snapshots or a previous run's scaled desired concurrency would otherwise distort this
|
|
812
|
+
// run's scaling. An injected one is long-lived and its lifecycle belongs to the caller.
|
|
813
|
+
this.#concurrencySystem = this.#resolveConcurrencySystem();
|
|
814
|
+
const run = new CrawlerRun({
|
|
815
|
+
log: this.log,
|
|
816
|
+
concurrencySystem: this.#concurrencySystem.value,
|
|
817
|
+
taskLoopOptions: this.#taskLoopOptions,
|
|
818
|
+
consumer: this.#identity,
|
|
813
819
|
});
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
const sigintHandler = async () => {
|
|
821
|
-
this.log.warning('Pausing... Press CTRL+C again to force exit. To resume, do: CRAWLEE_PURGE_ON_START=0 npm start');
|
|
822
|
-
await this.pauseOnMigration();
|
|
823
|
-
await this.#autoscaledPool.abort();
|
|
824
|
-
};
|
|
825
|
-
// Attach a listener to handle migration and aborting events gracefully.
|
|
826
|
-
const boundPauseOnMigration = this.pauseOnMigration.bind(this);
|
|
827
|
-
process.once('SIGINT', sigintHandler);
|
|
828
|
-
const eventManager = serviceLocator.getEventManager();
|
|
829
|
-
eventManager.on(EventType.MIGRATING, boundPauseOnMigration);
|
|
830
|
-
eventManager.on(EventType.ABORTING, boundPauseOnMigration);
|
|
831
|
-
let stats = {};
|
|
832
|
-
try {
|
|
833
|
-
await this.#autoscaledPool.run();
|
|
834
|
-
}
|
|
835
|
-
finally {
|
|
836
|
-
await this.statistics.stopCapturing();
|
|
837
|
-
await this.teardown();
|
|
838
|
-
process.off('SIGINT', sigintHandler);
|
|
839
|
-
eventManager.off(EventType.MIGRATING, boundPauseOnMigration);
|
|
840
|
-
eventManager.off(EventType.ABORTING, boundPauseOnMigration);
|
|
841
|
-
const finalStats = this.statistics.calculate();
|
|
842
|
-
stats = {
|
|
843
|
-
requestsFinished: this.statistics.state.requestsFinished,
|
|
844
|
-
requestsFailed: this.statistics.state.requestsFailed,
|
|
845
|
-
retryHistogram: this.statistics.requestRetryHistogram,
|
|
846
|
-
...finalStats,
|
|
847
|
-
};
|
|
848
|
-
this.log.info('Final request statistics:', stats);
|
|
849
|
-
if (this.statistics.errorTracker.total !== 0) {
|
|
850
|
-
const prettify = ([count, info]) => `${count}x: ${info.at(-1).trim()} (${info[0]})`;
|
|
851
|
-
this.log.info(`Error analysis:`, {
|
|
852
|
-
totalErrors: this.statistics.errorTracker.total,
|
|
853
|
-
uniqueErrors: this.statistics.errorTracker.getUniqueErrorCount(),
|
|
854
|
-
mostCommonErrors: this.statistics.errorTracker.getMostPopularErrors(3).map(prettify),
|
|
820
|
+
this.#run = run;
|
|
821
|
+
try {
|
|
822
|
+
await purgeDefaultStorages({
|
|
823
|
+
onlyPurgeOnce: true,
|
|
824
|
+
storageBackend: serviceLocator.getStorageBackend(),
|
|
825
|
+
configuration: serviceLocator.getConfiguration(),
|
|
855
826
|
});
|
|
827
|
+
if (requests) {
|
|
828
|
+
await this.addRequests(requests, options);
|
|
829
|
+
}
|
|
830
|
+
// An injected governor is the caller's to run; an owned one is started here and stopped again
|
|
831
|
+
// below if the startup fails. Either way the task loop rejects one that is not running.
|
|
832
|
+
await this.#concurrencySystem.ifOwned((system) => system.start());
|
|
833
|
+
await this.init();
|
|
834
|
+
await this.statistics.startCapturing();
|
|
835
|
+
}
|
|
836
|
+
catch (error) {
|
|
837
|
+
// Clean up here before propagating, otherwise a failed startup would leave the process hanging.
|
|
838
|
+
await this.teardown().catch((teardownError) => {
|
|
839
|
+
this.log.exception(teardownError, 'Cleaning up after a failed crawler startup failed.');
|
|
840
|
+
});
|
|
841
|
+
// The run never began, so let the instance be run again instead of leaving it wedged as `running`.
|
|
842
|
+
await run.finish();
|
|
843
|
+
await this.#concurrencySystem.ifOwned((system) => system.stop());
|
|
844
|
+
throw error;
|
|
845
|
+
}
|
|
846
|
+
const periodicLogger = this.#getPeriodicLogger();
|
|
847
|
+
this.setStatusMessage('Starting the crawler.', { level: 'INFO' });
|
|
848
|
+
const sigintHandler = async () => {
|
|
849
|
+
this.log.warning('Pausing... Press CTRL+C again to force exit. To resume, do: CRAWLEE_PURGE_ON_START=0 npm start');
|
|
850
|
+
await this.#pauseOnMigration();
|
|
851
|
+
await run.abort();
|
|
852
|
+
};
|
|
853
|
+
// Attach a listener to handle migration and aborting events gracefully.
|
|
854
|
+
const boundPauseOnMigration = this.#pauseOnMigration.bind(this);
|
|
855
|
+
process.once('SIGINT', sigintHandler);
|
|
856
|
+
const eventManager = serviceLocator.getEventManager();
|
|
857
|
+
eventManager.on(EventType.MIGRATING, boundPauseOnMigration);
|
|
858
|
+
eventManager.on(EventType.ABORTING, boundPauseOnMigration);
|
|
859
|
+
let stats = {};
|
|
860
|
+
try {
|
|
861
|
+
await run.dispatchRequests();
|
|
856
862
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
+
finally {
|
|
864
|
+
await this.statistics.stopCapturing();
|
|
865
|
+
await this.teardown();
|
|
866
|
+
process.off('SIGINT', sigintHandler);
|
|
867
|
+
eventManager.off(EventType.MIGRATING, boundPauseOnMigration);
|
|
868
|
+
eventManager.off(EventType.ABORTING, boundPauseOnMigration);
|
|
869
|
+
const finalStats = this.statistics.calculate();
|
|
870
|
+
stats = {
|
|
871
|
+
requestsSucceeded: this.statistics.state.requestsSucceeded,
|
|
872
|
+
requestsFailed: this.statistics.state.requestsFailed,
|
|
873
|
+
retryHistogram: this.statistics.requestRetryHistogram,
|
|
874
|
+
...finalStats,
|
|
875
|
+
};
|
|
876
|
+
this.log.info('Final request statistics:', stats);
|
|
877
|
+
// A crawl that did nothing while the manager holds only handled requests is a mistake whoever
|
|
878
|
+
// handled them - this run, another crawler on the same queue, or a previous process. Starting
|
|
879
|
+
// against handled requests is not: that is what resuming a crawl looks like.
|
|
880
|
+
if (stats.requestsSucceeded + stats.requestsFailed === 0) {
|
|
881
|
+
// Never let the diagnostic itself break the run.
|
|
882
|
+
const alreadyHandled = (await this.requestManager?.getHandledCount().catch(() => 0)) ?? 0;
|
|
883
|
+
if (alreadyHandled > 0) {
|
|
884
|
+
this.log.warningOnce('This crawl processed no requests - the request manager holds ' +
|
|
885
|
+
`${alreadyHandled} request${alreadyHandled === 1 ? '' : 's'}, all of them ` +
|
|
886
|
+
'already handled, and a failed request counts as handled too. Nothing ' +
|
|
887
|
+
'empties a queue between runs, so to crawl them again, purge it ' +
|
|
888
|
+
'(`await queue.purge()`) or use a fresh one (e.g. ' +
|
|
889
|
+
'`RequestQueue.open({ alias: "second-run" })`) with a freshly created ' +
|
|
890
|
+
'crawler instance.');
|
|
863
891
|
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
|
|
892
|
+
}
|
|
893
|
+
if (this.statistics.errorTracker.total !== 0) {
|
|
894
|
+
const prettify = ([count, info]) => `${count}x: ${info.at(-1).trim()} (${info[0]})`;
|
|
895
|
+
this.log.info(`Error analysis:`, {
|
|
896
|
+
totalErrors: this.statistics.errorTracker.total,
|
|
897
|
+
uniqueErrors: this.statistics.errorTracker.getUniqueErrorCount(),
|
|
898
|
+
mostCommonErrors: this.statistics.errorTracker.getMostPopularErrors(3).map(prettify),
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
const client = serviceLocator.getStorageBackend();
|
|
902
|
+
if (client.teardown) {
|
|
903
|
+
let finished = false;
|
|
904
|
+
setTimeout(() => {
|
|
905
|
+
if (!finished) {
|
|
906
|
+
this.log.info('Waiting for the storage to write its state to file system.');
|
|
907
|
+
}
|
|
908
|
+
}, 1000);
|
|
909
|
+
await client.teardown();
|
|
910
|
+
finished = true;
|
|
911
|
+
}
|
|
912
|
+
periodicLogger.stop();
|
|
913
|
+
this.setStatusMessage(`Finished! Total ${this.statistics.state.requestsSucceeded + this.statistics.state.requestsFailed} requests: ${this.statistics.state.requestsSucceeded} succeeded, ${this.statistics.state.requestsFailed} failed.`, { isStatusMessageTerminal: true, level: 'INFO' });
|
|
914
|
+
await run.finish();
|
|
915
|
+
await this.#concurrencySystem.ifOwned((system) => system.stop());
|
|
916
|
+
this.#hasFinishedBefore = true;
|
|
867
917
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
this.running = false;
|
|
871
|
-
this.hasFinishedBefore = true;
|
|
872
|
-
}
|
|
873
|
-
return stats;
|
|
918
|
+
return stats;
|
|
919
|
+
}));
|
|
874
920
|
}
|
|
875
921
|
/**
|
|
876
922
|
* Gracefully stops the current run of the crawler.
|
|
@@ -880,11 +926,12 @@ export class BasicCrawler {
|
|
|
880
926
|
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
881
927
|
*/
|
|
882
928
|
stop(reason = 'The crawler has been gracefully stopped.') {
|
|
883
|
-
|
|
929
|
+
const run = this.#liveRun;
|
|
930
|
+
if (run === undefined) {
|
|
931
|
+
this.log.warning('Cannot stop a crawler that is not running.');
|
|
884
932
|
return;
|
|
885
933
|
}
|
|
886
|
-
|
|
887
|
-
this.#unexpectedStop = true;
|
|
934
|
+
run.stop(reason);
|
|
888
935
|
}
|
|
889
936
|
/**
|
|
890
937
|
* Stops dispatching new requests, letting the in-progress ones finish. Resolves once they have settled, or rejects
|
|
@@ -895,52 +942,41 @@ export class BasicCrawler {
|
|
|
895
942
|
* throughout, since a shared one may still be serving other crawlers.
|
|
896
943
|
*/
|
|
897
944
|
async pause(timeoutSecs) {
|
|
898
|
-
|
|
945
|
+
const run = this.#dispatchingRun;
|
|
946
|
+
if (run === undefined) {
|
|
899
947
|
this.log.warning('Cannot pause a crawler that is not running.');
|
|
900
948
|
return;
|
|
901
949
|
}
|
|
902
|
-
await
|
|
950
|
+
await run.pause(timeoutSecs);
|
|
903
951
|
}
|
|
904
952
|
/**
|
|
905
953
|
* Resumes a run suspended with {@link BasicCrawler.pause|`pause()`}, letting the crawler dispatch requests
|
|
906
954
|
* again. A no-op on a crawler that is not paused.
|
|
907
955
|
*/
|
|
908
956
|
resume() {
|
|
909
|
-
|
|
957
|
+
const run = this.#dispatchingRun;
|
|
958
|
+
if (run === undefined) {
|
|
910
959
|
this.log.warning('Cannot resume a crawler that is not running.');
|
|
911
960
|
return;
|
|
912
961
|
}
|
|
913
|
-
|
|
962
|
+
run.resume();
|
|
914
963
|
}
|
|
915
964
|
/**
|
|
916
965
|
* Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
|
|
917
966
|
* if none has been configured or opened yet.
|
|
918
967
|
*/
|
|
919
968
|
async getRequestManager() {
|
|
920
|
-
if (!this
|
|
921
|
-
this
|
|
922
|
-
}
|
|
923
|
-
// Wrapped here rather than in the constructor, because the manager being wrapped may only be opened at
|
|
924
|
-
// this point - and because everything that enqueues goes through here first, so nothing slips past the
|
|
925
|
-
// wrapper into the queue it hides.
|
|
926
|
-
if (this.#sameDomainDelaySecs > 0 && !supportsDomainThrottling(this.requestManager)) {
|
|
927
|
-
this.requestManager = new ThrottlingRequestManager({
|
|
928
|
-
inner: this.requestManager,
|
|
929
|
-
domains: 'all',
|
|
930
|
-
minCrawlDelaySecs: this.#sameDomainDelaySecs,
|
|
931
|
-
// What `sameDomainDelaySecs` has always meant: one clock for a site, subdomains included.
|
|
932
|
-
throttleBy: 'registrableDomain',
|
|
933
|
-
persistStateKey: `CRAWLEE_THROTTLED_DOMAINS_${this.identity.id}`,
|
|
934
|
-
});
|
|
969
|
+
if (!this.#requestManager) {
|
|
970
|
+
this.#requestManager = await this.#openOwnedRequestQueue();
|
|
935
971
|
}
|
|
936
972
|
// Apply the processing-time hint here (an async lifecycle point) rather than in the constructor,
|
|
937
973
|
// now that `setExpectedRequestProcessingTimeSecs` is async. The hint is raise-only and idempotent,
|
|
938
974
|
// but guard so we do not re-issue it on every call.
|
|
939
975
|
if (!this.#requestManagerTimeoutsApplied) {
|
|
940
976
|
this.#requestManagerTimeoutsApplied = true;
|
|
941
|
-
await this
|
|
977
|
+
await this.#applyRequestManagerTimeouts(this.#requestManager);
|
|
942
978
|
}
|
|
943
|
-
return this
|
|
979
|
+
return this.#requestManager;
|
|
944
980
|
}
|
|
945
981
|
/**
|
|
946
982
|
* @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
|
|
@@ -950,16 +986,13 @@ export class BasicCrawler {
|
|
|
950
986
|
return this.getRequestManager();
|
|
951
987
|
}
|
|
952
988
|
/**
|
|
953
|
-
* Opens the default {@link RequestQueue}
|
|
954
|
-
* crawler-owned queue (so it gets purged between repeated `run()` calls).
|
|
955
|
-
* @private
|
|
989
|
+
* Opens the default {@link RequestQueue} — the crawler's own, read from when the caller supplied nothing.
|
|
956
990
|
*/
|
|
957
|
-
async openOwnedRequestQueue() {
|
|
991
|
+
async #openOwnedRequestQueue() {
|
|
958
992
|
// The first crawler instance uses the default queue (null identifier);
|
|
959
993
|
// subsequent instances get their own queue via a unique alias so they don't collide.
|
|
960
|
-
const identifier = this
|
|
961
|
-
|
|
962
|
-
return this.#ownedRequestQueue.set(requestQueue);
|
|
994
|
+
const identifier = this.#identity.instanceIndex === 0 ? null : { alias: `__default_${this.#identity.id}__` };
|
|
995
|
+
return RequestQueue.open(identifier, { configuration: serviceLocator.getConfiguration() });
|
|
963
996
|
}
|
|
964
997
|
/**
|
|
965
998
|
* Tells a request manager how long we expect to hold a fetched request, so that one backed by a
|
|
@@ -968,12 +1001,12 @@ export class BasicCrawler {
|
|
|
968
1001
|
* request from being handed out a second time while it is still being processed — and it works
|
|
969
1002
|
* regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
|
|
970
1003
|
*/
|
|
971
|
-
async applyRequestManagerTimeouts(requestManager) {
|
|
1004
|
+
async #applyRequestManagerTimeouts(requestManager) {
|
|
972
1005
|
// A router route may hold a request for longer than the crawler's own timeout, and we cannot know
|
|
973
1006
|
// which routes a run will hit, so reserve for the longest one any route asked for. The hint is
|
|
974
1007
|
// raise-only, so erring high here is safe.
|
|
975
1008
|
const maxRouteTimeoutSecs = this.requestHandler.getMaxTimeoutSecs?.() ?? 0;
|
|
976
|
-
const handlerTimeoutSecs = Math.max(this
|
|
1009
|
+
const handlerTimeoutSecs = Math.max(this.#requestHandlerTimeoutMillis / 1000, maxRouteTimeoutSecs);
|
|
977
1010
|
await requestManager.setExpectedRequestProcessingTimeSecs?.(Math.max(handlerTimeoutSecs + 5, 60));
|
|
978
1011
|
}
|
|
979
1012
|
/**
|
|
@@ -983,7 +1016,7 @@ export class BasicCrawler {
|
|
|
983
1016
|
* the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
|
|
984
1017
|
* `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
|
|
985
1018
|
*/
|
|
986
|
-
async validateRequestUserData(source) {
|
|
1019
|
+
async #validateRequestUserData(source) {
|
|
987
1020
|
if (typeof source === 'string') {
|
|
988
1021
|
return;
|
|
989
1022
|
}
|
|
@@ -1004,11 +1037,11 @@ export class BasicCrawler {
|
|
|
1004
1037
|
}
|
|
1005
1038
|
async useState(defaultValue = {}) {
|
|
1006
1039
|
const kvs = await KeyValueStore.open(null, { configuration: serviceLocator.getConfiguration() });
|
|
1007
|
-
if (this
|
|
1008
|
-
const stateKey = `${BasicCrawler
|
|
1040
|
+
if (this.#identity.hasExplicitId) {
|
|
1041
|
+
const stateKey = `${BasicCrawler.#CRAWLEE_STATE_KEY}_${this.#identity.id}`;
|
|
1009
1042
|
return kvs.getAutoSavedValue(stateKey, defaultValue);
|
|
1010
1043
|
}
|
|
1011
|
-
BasicCrawler.#useStateAnonymousIndices.add(this
|
|
1044
|
+
BasicCrawler.#useStateAnonymousIndices.add(this.#identity.instanceIndex);
|
|
1012
1045
|
if (BasicCrawler.#useStateAnonymousIndices.size > 1) {
|
|
1013
1046
|
serviceLocator
|
|
1014
1047
|
.getLogger()
|
|
@@ -1017,38 +1050,36 @@ export class BasicCrawler {
|
|
|
1017
1050
|
'To fix this, provide a unique `id` option to each crawler instance. \n' +
|
|
1018
1051
|
'Example: new BasicCrawler({ id: "my-crawler-1", ... })');
|
|
1019
1052
|
}
|
|
1020
|
-
return kvs.getAutoSavedValue(BasicCrawler
|
|
1053
|
+
return kvs.getAutoSavedValue(BasicCrawler.#CRAWLEE_STATE_KEY, defaultValue);
|
|
1021
1054
|
}
|
|
1022
|
-
async getPendingRequestCountApproximation() {
|
|
1055
|
+
async #getPendingRequestCountApproximation() {
|
|
1023
1056
|
return (await this.requestManager?.getPendingCount()) ?? 0;
|
|
1024
1057
|
}
|
|
1025
|
-
async calculateEnqueuedRequestLimit(explicitLimit) {
|
|
1026
|
-
if (this
|
|
1058
|
+
async #calculateEnqueuedRequestLimit(explicitLimit) {
|
|
1059
|
+
if (this.#maxRequestsPerCrawl === undefined) {
|
|
1027
1060
|
return explicitLimit;
|
|
1028
1061
|
}
|
|
1029
|
-
const limit = Math.max(0, this
|
|
1062
|
+
const limit = Math.max(0, this.#maxRequestsPerCrawl -
|
|
1063
|
+
this.#handledRequestsCount -
|
|
1064
|
+
(await this.#getPendingRequestCountApproximation()));
|
|
1030
1065
|
return Math.min(limit, explicitLimit ?? Infinity);
|
|
1031
1066
|
}
|
|
1032
|
-
async handleSkippedRequest(options) {
|
|
1067
|
+
async #handleSkippedRequest(options) {
|
|
1033
1068
|
// A skipped request is a *successful* outcome, but the interrupt still unwinds through the
|
|
1034
1069
|
// transaction scope, which rolls back - so the skip bookkeeping must write directly.
|
|
1035
1070
|
await withDirectStorageAccess(async () => {
|
|
1071
|
+
// Enqueueing happens outside a run too - `addRequests()` before the first `run()` - so these dedupe
|
|
1072
|
+
// against the logger for the crawler's lifetime rather than per run.
|
|
1036
1073
|
if (options.reason === 'limit') {
|
|
1037
|
-
this.
|
|
1038
|
-
`${this
|
|
1074
|
+
this.log.info('The number of requests enqueued by the crawler reached the maxRequestsPerCrawl limit of ' +
|
|
1075
|
+
`${this.#maxRequestsPerCrawl} requests and no further requests will be added.`, undefined, { once: true });
|
|
1039
1076
|
}
|
|
1040
1077
|
if (options.reason === 'depth') {
|
|
1041
|
-
this.
|
|
1078
|
+
this.log.info(`The crawler reached the maxCrawlDepth limit of ${this.#maxCrawlDepth} and no further requests will be enqueued.`, undefined, { once: true });
|
|
1042
1079
|
}
|
|
1043
|
-
await this
|
|
1080
|
+
await this.#onSkippedRequest?.(options);
|
|
1044
1081
|
});
|
|
1045
1082
|
}
|
|
1046
|
-
logOncePerRun(key, message, level = 'info') {
|
|
1047
|
-
if (!this.#loggedPerRun.has(key)) {
|
|
1048
|
-
this.log[level](message);
|
|
1049
|
-
this.#loggedPerRun.add(key);
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
1083
|
/**
|
|
1053
1084
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
1054
1085
|
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
|
|
@@ -1077,25 +1108,47 @@ export class BasicCrawler {
|
|
|
1077
1108
|
// its own per-item validation below, and validating an absent label/userData here would spuriously
|
|
1078
1109
|
// check them against a registered default-route schema.
|
|
1079
1110
|
if (options.label !== undefined || options.userData !== undefined) {
|
|
1080
|
-
await this
|
|
1111
|
+
await this.#validateRequestUserData({ label: options.label, userData: options.userData });
|
|
1081
1112
|
}
|
|
1082
|
-
const requestLimit = await this
|
|
1113
|
+
const requestLimit = await this.#calculateEnqueuedRequestLimit(options.limit);
|
|
1083
1114
|
const strategy = options.strategy ?? EnqueueStrategy.All;
|
|
1084
|
-
const urlExcludePatternObjects = options.exclude?.length
|
|
1085
|
-
|
|
1086
|
-
: [];
|
|
1087
|
-
const urlPatternObjects = options.include?.length
|
|
1088
|
-
? constructUrlPatternObjects(options.include)
|
|
1089
|
-
: [];
|
|
1115
|
+
const urlExcludePatternObjects = options.exclude?.length ? constructUrlPatternObjects(options.exclude) : [];
|
|
1116
|
+
const urlPatternObjects = options.include?.length ? constructUrlPatternObjects(options.include) : [];
|
|
1090
1117
|
// The strategy always applies, even when `include` patterns are provided - the two are AND-ed together
|
|
1091
1118
|
// (a URL must match an `include` pattern *and* satisfy the strategy). This mirrors crawlee-python.
|
|
1092
|
-
const enqueueStrategyPatterns = options.baseUrl
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
const
|
|
1096
|
-
const maxCrawlDepth = this.maxCrawlDepth;
|
|
1097
|
-
const validateRequestUserData = this.validateRequestUserData.bind(this);
|
|
1119
|
+
const enqueueStrategyPatterns = options.baseUrl ? buildEnqueueStrategyPatterns(options.baseUrl, strategy) : [];
|
|
1120
|
+
const isAllowedBasedOnRobotsTxtFile = this.#isAllowedBasedOnRobotsTxtFile.bind(this);
|
|
1121
|
+
const maxCrawlDepth = this.#maxCrawlDepth;
|
|
1122
|
+
const validateRequestUserData = this.#validateRequestUserData.bind(this);
|
|
1098
1123
|
const allSkipped = [];
|
|
1124
|
+
// A skipped source (which can carry arbitrary userData) is only retained if something reads it -
|
|
1125
|
+
// otherwise the URL alone is enough to build the callback argument and to log with.
|
|
1126
|
+
const hasSkippedRequestCallback = this.#onSkippedRequest !== undefined || options.onSkippedRequest !== undefined;
|
|
1127
|
+
const keepSkippedSource = (source) => (hasSkippedRequestCallback ? source : source.url);
|
|
1128
|
+
const reportSkippedRequests = async () => {
|
|
1129
|
+
const skippedRequests = allSkipped.splice(0);
|
|
1130
|
+
if (skippedRequests.length === 0) {
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
const skippedRobotsUrls = skippedRequests
|
|
1134
|
+
.filter((s) => s.reason === 'robotsTxt')
|
|
1135
|
+
.map(({ source }) => (typeof source === 'string' ? source : source.url));
|
|
1136
|
+
if (skippedRobotsUrls.length > 0) {
|
|
1137
|
+
this.log.warning(`Some requests were skipped because they were disallowed based on the robots.txt file`, { skipped: skippedRobotsUrls });
|
|
1138
|
+
}
|
|
1139
|
+
// Only log the limit message when an explicit `limit` was passed (not the internal
|
|
1140
|
+
// `maxRequestsPerCrawl`-derived one), and only once per call.
|
|
1141
|
+
if (options.limit !== undefined && skippedRequests.some((s) => s.reason === 'limit')) {
|
|
1142
|
+
this.log.info(requestLimit === options.limit
|
|
1143
|
+
? `Skipping requests in this call due to the enqueueLinks limit of ${options.limit}.`
|
|
1144
|
+
: `Skipping requests in this call due to the remaining maxRequestsPerCrawl budget of ${requestLimit}, which is lower than the enqueueLinks limit of ${options.limit}.`);
|
|
1145
|
+
}
|
|
1146
|
+
await Promise.all(skippedRequests.map(async ({ source, reason }) => {
|
|
1147
|
+
const args = createSkippedRequestArgs(source, reason);
|
|
1148
|
+
await this.#handleSkippedRequest(args);
|
|
1149
|
+
await options.onSkippedRequest?.(args);
|
|
1150
|
+
}));
|
|
1151
|
+
};
|
|
1099
1152
|
async function* filteredRequests() {
|
|
1100
1153
|
for await (const request of requests) {
|
|
1101
1154
|
const [requestOptions] = createRequestOptions([typeof request === 'string' ? request : request], { ...options, strategy });
|
|
@@ -1103,24 +1156,24 @@ export class BasicCrawler {
|
|
|
1103
1156
|
continue; // invalid URL, silently dropped (matches `createRequestOptions`'s own filtering)
|
|
1104
1157
|
}
|
|
1105
1158
|
if (maxCrawlDepth !== undefined && requestOptions.crawlDepth > maxCrawlDepth) {
|
|
1106
|
-
allSkipped.push({
|
|
1159
|
+
allSkipped.push({ source: keepSkippedSource(requestOptions), reason: 'depth' });
|
|
1107
1160
|
continue;
|
|
1108
1161
|
}
|
|
1109
1162
|
if (!(await isAllowedBasedOnRobotsTxtFile(requestOptions.url))) {
|
|
1110
|
-
allSkipped.push({
|
|
1163
|
+
allSkipped.push({ source: keepSkippedSource(requestOptions), reason: 'robotsTxt' });
|
|
1111
1164
|
continue;
|
|
1112
1165
|
}
|
|
1113
|
-
const
|
|
1166
|
+
const onSkippedByFilter = (opts) => allSkipped.push({ source: keepSkippedSource(opts), reason: 'filters' });
|
|
1114
1167
|
// Filter by user patterns first (with exclude)...
|
|
1115
|
-
let filtered = filterRequestOptionsByPatterns([requestOptions], urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, strategy,
|
|
1168
|
+
let filtered = filterRequestOptionsByPatterns([requestOptions], urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, strategy, onSkippedByFilter);
|
|
1116
1169
|
// ...then filter by the enqueue strategy (making this an AND check)
|
|
1117
|
-
filtered = filterRequestOptionsByPatterns(filtered, enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined, [], strategy,
|
|
1170
|
+
filtered = filterRequestOptionsByPatterns(filtered, enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined, [], strategy, onSkippedByFilter);
|
|
1118
1171
|
if (filtered.length === 0) {
|
|
1119
1172
|
continue;
|
|
1120
1173
|
}
|
|
1121
1174
|
let [finalOptions] = filtered;
|
|
1122
1175
|
if (options.transformRequestFunction) {
|
|
1123
|
-
const transformed = applyRequestTransform([finalOptions], options.transformRequestFunction, (r) => allSkipped.push({
|
|
1176
|
+
const transformed = applyRequestTransform([finalOptions], options.transformRequestFunction, (r) => allSkipped.push({ source: keepSkippedSource(r), reason: 'transform' }));
|
|
1124
1177
|
if (transformed.length === 0) {
|
|
1125
1178
|
continue;
|
|
1126
1179
|
}
|
|
@@ -1140,31 +1193,23 @@ export class BasicCrawler {
|
|
|
1140
1193
|
// Report requests skipped due to the maxNewRequests budget (i.e. maxRequestsPerCrawl limit, or an
|
|
1141
1194
|
// explicit `limit` option)
|
|
1142
1195
|
for (const request of result.requestsOverLimit ?? []) {
|
|
1143
|
-
allSkipped.push({
|
|
1196
|
+
allSkipped.push({ source: request, reason: 'limit' });
|
|
1144
1197
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
? `Skipping requests in this call due to the enqueueLinks limit of ${options.limit}.`
|
|
1155
|
-
: `Skipping requests in this call due to the remaining maxRequestsPerCrawl budget of ${requestLimit}, which is lower than the enqueueLinks limit of ${options.limit}.`);
|
|
1156
|
-
}
|
|
1157
|
-
await Promise.all(allSkipped.map(async ({ url, reason }) => {
|
|
1158
|
-
await this.handleSkippedRequest({ url, reason });
|
|
1159
|
-
await options.onSkippedRequest?.({ url, reason });
|
|
1160
|
-
}));
|
|
1161
|
-
}
|
|
1162
|
-
return result;
|
|
1198
|
+
await reportSkippedRequests();
|
|
1199
|
+
const waitForAllRequestsToBeAdded = result.waitForAllRequestsToBeAdded.then(async (addedRequests) => {
|
|
1200
|
+
await reportSkippedRequests();
|
|
1201
|
+
return addedRequests;
|
|
1202
|
+
});
|
|
1203
|
+
// Keep callback failures observable to callers that await this promise without emitting an unhandled rejection
|
|
1204
|
+
// when callers intentionally leave background additions running, matching `drainRequestBatches` behavior.
|
|
1205
|
+
void waitForAllRequestsToBeAdded.catch(() => { });
|
|
1206
|
+
return { ...result, waitForAllRequestsToBeAdded };
|
|
1163
1207
|
}
|
|
1164
1208
|
/**
|
|
1165
1209
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
1166
1210
|
*/
|
|
1167
1211
|
async pushData(data, datasetIdentifier) {
|
|
1212
|
+
tryCancel();
|
|
1168
1213
|
const dataset = await this.getDataset(datasetIdentifier);
|
|
1169
1214
|
return dataset.pushData(data);
|
|
1170
1215
|
}
|
|
@@ -1233,31 +1278,25 @@ export class BasicCrawler {
|
|
|
1233
1278
|
* Initializes the crawler.
|
|
1234
1279
|
*/
|
|
1235
1280
|
async init() {
|
|
1281
|
+
const run = this.#liveRun;
|
|
1282
|
+
if (run === undefined) {
|
|
1283
|
+
throw new Error('There is no crawl in progress - `run()` is the only thing that starts one.');
|
|
1284
|
+
}
|
|
1236
1285
|
const eventManager = serviceLocator.getEventManager();
|
|
1237
1286
|
if (!eventManager.isInitialized()) {
|
|
1238
1287
|
await eventManager.init();
|
|
1239
|
-
|
|
1288
|
+
run.ownsEventManager = true;
|
|
1240
1289
|
}
|
|
1241
1290
|
// Warn once at startup if the internal timeout is shorter than the phases it is meant to outlast. It is
|
|
1242
1291
|
// floored per request so it will not actually cut them short, but the configured value is then effectively
|
|
1243
1292
|
// ignored, which is worth flagging. Checked here (not in the constructor) because a subclass sets its
|
|
1244
1293
|
// navigation timeout only after `super()`.
|
|
1245
|
-
const phasesMillis = this.getNavigationTimeoutMillis() + this
|
|
1294
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.#resolveRequestHandlerTimeoutMillis(undefined);
|
|
1246
1295
|
if (this.internalTimeoutMillis < phasesMillis) {
|
|
1247
1296
|
this.log.warning(`CRAWLEE_INTERNAL_TIMEOUT (${this.internalTimeoutMillis / 1000}s) is shorter than the navigation ` +
|
|
1248
1297
|
`and request handler timeouts combined (${phasesMillis / 1000}s); it will be raised per request ` +
|
|
1249
1298
|
`so it does not cut them short.`);
|
|
1250
1299
|
}
|
|
1251
|
-
// An owned governor is rebuilt (and started) for every run, so it always starts from a clean slate — stale
|
|
1252
|
-
// resource snapshots or a previous run's scaled desired concurrency would otherwise distort this run's
|
|
1253
|
-
// scaling. An injected one is long-lived and its lifecycle belongs to the caller.
|
|
1254
|
-
this.#concurrencySystemDep = this.#resolveConcurrencySystem();
|
|
1255
|
-
await this.#concurrencySystemDep.ifOwned((system) => system.start());
|
|
1256
|
-
this.#autoscaledPool = new AutoscaledPool({
|
|
1257
|
-
...this.taskLoopOptions,
|
|
1258
|
-
concurrencySystem: this.#concurrencySystemDep.value,
|
|
1259
|
-
consumer: this.identity,
|
|
1260
|
-
});
|
|
1261
1300
|
await this.getRequestManager();
|
|
1262
1301
|
}
|
|
1263
1302
|
/**
|
|
@@ -1274,9 +1313,9 @@ export class BasicCrawler {
|
|
|
1274
1313
|
* request, a per-route override, or a low `CRAWLEE_INTERNAL_TIMEOUT` is not cut short mid-phase. It takes
|
|
1275
1314
|
* whichever is larger: the configured internal timeout, or this request's combined phase budget.
|
|
1276
1315
|
*/
|
|
1277
|
-
async withRequestTimeout(crawlingContext, work) {
|
|
1316
|
+
async #withRequestTimeout(crawlingContext, work) {
|
|
1278
1317
|
const { request } = crawlingContext;
|
|
1279
|
-
const phasesMillis = this.getNavigationTimeoutMillis() + this
|
|
1318
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.#resolveRequestHandlerTimeoutMillis(request.label);
|
|
1280
1319
|
const timeoutMillis = Math.max(this.internalTimeoutMillis, phasesMillis);
|
|
1281
1320
|
await raceWithTimeout(crawlingContext, work, { timeoutMillis, requestId: request.id });
|
|
1282
1321
|
}
|
|
@@ -1287,14 +1326,14 @@ export class BasicCrawler {
|
|
|
1287
1326
|
* @param label The request's route label, or `undefined` for the default route / no specific request.
|
|
1288
1327
|
* @param fallbackMillis Timeout to use when no route overrides it.
|
|
1289
1328
|
*/
|
|
1290
|
-
resolveRequestHandlerTimeoutMillis(label, fallbackMillis = this
|
|
1291
|
-
return this
|
|
1329
|
+
#resolveRequestHandlerTimeoutMillis(label, fallbackMillis = this.#requestHandlerTimeoutMillis) {
|
|
1330
|
+
return this.#getRouteTimeoutMillis(label) ?? fallbackMillis;
|
|
1292
1331
|
}
|
|
1293
1332
|
/**
|
|
1294
1333
|
* The timeout the router route with the given label asked for, or `undefined` when it did not override one
|
|
1295
1334
|
* (or the request handler is not a router at all).
|
|
1296
1335
|
*/
|
|
1297
|
-
getRouteTimeoutMillis(label) {
|
|
1336
|
+
#getRouteTimeoutMillis(label) {
|
|
1298
1337
|
const getTimeoutSecs = this.requestHandler.getTimeoutSecs;
|
|
1299
1338
|
if (typeof getTimeoutSecs !== 'function') {
|
|
1300
1339
|
return undefined;
|
|
@@ -1303,14 +1342,15 @@ export class BasicCrawler {
|
|
|
1303
1342
|
return timeoutSecs === undefined ? undefined : timeoutSecs * 1000;
|
|
1304
1343
|
}
|
|
1305
1344
|
async runRequestHandler(crawlingContext) {
|
|
1306
|
-
const timeoutMillis = this
|
|
1345
|
+
const timeoutMillis = this.#resolveRequestHandlerTimeoutMillis(crawlingContext.request.label);
|
|
1307
1346
|
await addTimeoutToPromise(async () => this.requestHandler(crawlingContext), timeoutMillis, `requestHandler timed out after ${timeoutMillis / 1000} seconds (${crawlingContext.request.id}).`);
|
|
1308
1347
|
}
|
|
1309
1348
|
/**
|
|
1310
1349
|
* Runs `callback` inside a {@link StorageTransaction}, unless transactional storage is disabled.
|
|
1311
|
-
* Deliberately does **not** commit on return -
|
|
1312
|
-
*
|
|
1350
|
+
* Deliberately does **not** commit on return - the pipeline hands failures to `handleRequestFailure`, so a
|
|
1351
|
+
* normal return says nothing about success. `handleRequest` commits on success.
|
|
1313
1352
|
*/
|
|
1353
|
+
// oxlint-disable-next-line crawlee/prefer-private-fields -- accessed by tests
|
|
1314
1354
|
async runInStorageTransaction(callback) {
|
|
1315
1355
|
if (!this.#transactionalStorageEnabled) {
|
|
1316
1356
|
return callback();
|
|
@@ -1327,7 +1367,7 @@ export class BasicCrawler {
|
|
|
1327
1367
|
}
|
|
1328
1368
|
finally {
|
|
1329
1369
|
if (transaction.state === 'open') {
|
|
1330
|
-
// `handleRequest` commits or rolls back on every normal path, so an open transaction on
|
|
1370
|
+
// `handleRequest` commits or `handleRequestFailure` rolls back on every normal path, so an open transaction on
|
|
1331
1371
|
// a normal return is a wiring bug; on a propagating throw (a pipeline-level failure) it is
|
|
1332
1372
|
// expected. Either way, discard the unvalidated writes; only the former is worth flagging.
|
|
1333
1373
|
if (!threw) {
|
|
@@ -1350,7 +1390,7 @@ export class BasicCrawler {
|
|
|
1350
1390
|
throw new SessionError(`Request blocked - received ${statusCode} status code.`);
|
|
1351
1391
|
}
|
|
1352
1392
|
}
|
|
1353
|
-
async isAllowedBasedOnRobotsTxtFile(url) {
|
|
1393
|
+
async #isAllowedBasedOnRobotsTxtFile(url) {
|
|
1354
1394
|
if (!this.#respectRobotsTxtFile) {
|
|
1355
1395
|
return true;
|
|
1356
1396
|
}
|
|
@@ -1359,45 +1399,52 @@ export class BasicCrawler {
|
|
|
1359
1399
|
if (robotsTxtFile) {
|
|
1360
1400
|
const crawlDelay = robotsTxtFile.getCrawlDelay(userAgent);
|
|
1361
1401
|
if (crawlDelay !== undefined) {
|
|
1362
|
-
this
|
|
1402
|
+
this.#applyCrawlDelay(url, crawlDelay);
|
|
1363
1403
|
}
|
|
1364
1404
|
}
|
|
1365
1405
|
return !robotsTxtFile || robotsTxtFile.isAllowed(url, userAgent);
|
|
1366
1406
|
}
|
|
1367
1407
|
/**
|
|
1368
|
-
* Records an HTTP 429 against the URL's domain so the request manager can
|
|
1408
|
+
* Records an HTTP 429 against the URL's domain so the request manager can hold the retry back.
|
|
1369
1409
|
*
|
|
1370
1410
|
* @param retryAfterHeader The raw `Retry-After` response header, if the server sent one.
|
|
1371
|
-
* @returns `true` if
|
|
1411
|
+
* @returns `true` if the manager took responsibility for the delay, in which case the caller should throw
|
|
1372
1412
|
* {@link RequestThrottledError} rather than treating the response as a blocked session.
|
|
1373
1413
|
*/
|
|
1374
1414
|
recordDomainRateLimit(url, retryAfterHeader) {
|
|
1375
|
-
if (
|
|
1376
|
-
|
|
1415
|
+
if (this.requestManager?.recordPacingSignal({
|
|
1416
|
+
reason: 'rateLimited',
|
|
1417
|
+
url,
|
|
1418
|
+
waitMs: parseRetryAfterHeader(retryAfterHeader) ?? undefined,
|
|
1419
|
+
})) {
|
|
1377
1420
|
return true;
|
|
1378
1421
|
}
|
|
1379
1422
|
const domain = hostnameOrUrl(url);
|
|
1380
|
-
this.
|
|
1381
|
-
'so the response is handled like any other, with no per-domain delay. ' +
|
|
1382
|
-
|
|
1383
|
-
'
|
|
1423
|
+
this.log.warningOnce(`"${domain}" responded with HTTP 429 (Too Many Requests), but the crawler's request manager does not ` +
|
|
1424
|
+
'pace that domain, so the response is handled like any other, with no per-domain delay. Set ' +
|
|
1425
|
+
`\`sameDomainDelaySecs\`, or pass a \`ThrottlingRequestManager\` covering "${domain}" as ` +
|
|
1426
|
+
'`requestManager`, to honour `Retry-After` and apply exponential backoff instead.');
|
|
1384
1427
|
return false;
|
|
1385
1428
|
}
|
|
1386
|
-
/**
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1429
|
+
/** Hands a robots.txt `Crawl-delay` to the request manager, warning if it will not be honoured. */
|
|
1430
|
+
#applyCrawlDelay(url, delaySeconds) {
|
|
1431
|
+
// robots.txt is per-origin; `hostname` is the closest pacing scope and errs wide (http and https to one
|
|
1432
|
+
// host share a clock).
|
|
1433
|
+
if (this.requestManager?.recordPacingSignal({
|
|
1434
|
+
reason: 'minInterval',
|
|
1435
|
+
url,
|
|
1436
|
+
intervalMs: delaySeconds * 1000,
|
|
1437
|
+
scope: 'hostname',
|
|
1438
|
+
})) {
|
|
1394
1439
|
return;
|
|
1395
1440
|
}
|
|
1396
1441
|
const domain = hostnameOrUrl(url);
|
|
1397
|
-
this.
|
|
1398
|
-
'
|
|
1399
|
-
|
|
1442
|
+
this.log.warningOnce(`robots.txt for "${domain}" defines a crawl-delay of ${delaySeconds}s, but the crawler's request ` +
|
|
1443
|
+
'manager does not pace that domain, so its requests will not be paced. Set ' +
|
|
1444
|
+
`\`sameDomainDelaySecs\`, or pass a \`ThrottlingRequestManager\` covering "${domain}" as ` +
|
|
1445
|
+
'`requestManager`.');
|
|
1400
1446
|
}
|
|
1447
|
+
/** @internal */
|
|
1401
1448
|
async getRobotsTxtFileForUrl(url) {
|
|
1402
1449
|
if (!this.#respectRobotsTxtFile) {
|
|
1403
1450
|
return undefined;
|
|
@@ -1417,10 +1464,10 @@ export class BasicCrawler {
|
|
|
1417
1464
|
return undefined;
|
|
1418
1465
|
}
|
|
1419
1466
|
}
|
|
1420
|
-
async pauseOnMigration() {
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
await
|
|
1467
|
+
async #pauseOnMigration() {
|
|
1468
|
+
const run = this.#dispatchingRun;
|
|
1469
|
+
if (run) {
|
|
1470
|
+
await run.pause(SAFE_MIGRATION_WAIT_MILLIS).catch((err) => {
|
|
1424
1471
|
if (err.message.includes('running tasks did not finish')) {
|
|
1425
1472
|
this.log.error('The crawler was paused due to migration to another host, ' +
|
|
1426
1473
|
"but some requests did not finish in time. Those requests' results may be duplicated.");
|
|
@@ -1430,37 +1477,21 @@ export class BasicCrawler {
|
|
|
1430
1477
|
}
|
|
1431
1478
|
});
|
|
1432
1479
|
}
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
if (this.requestManager?.persistState) {
|
|
1437
|
-
if (await this.requestManager.isFinished())
|
|
1438
|
-
return;
|
|
1439
|
-
await this.requestManager.persistState().catch((err) => {
|
|
1440
|
-
if (err.message.includes('Cannot persist state.')) {
|
|
1441
|
-
this.log.error("The crawler attempted to persist its request list's state and failed due to missing or " +
|
|
1442
|
-
'invalid configuration. Make sure to use either RequestList.open() or the "stateKeyPrefix" option of RequestList ' +
|
|
1443
|
-
'constructor to ensure your crawling state is persisted through host migrations and restarts.');
|
|
1444
|
-
}
|
|
1445
|
-
else {
|
|
1446
|
-
this.log.exception(err, 'An unexpected error occurred when the crawler ' +
|
|
1447
|
-
"attempted to persist its request list's state.");
|
|
1448
|
-
}
|
|
1449
|
-
});
|
|
1450
|
-
}
|
|
1451
|
-
})();
|
|
1452
|
-
await Promise.all([requestManagerPersistPromise, this.statistics.persistState?.()]);
|
|
1480
|
+
// Captures the statistics changed while draining above. No PERSIST_STATE event is tied to the drain:
|
|
1481
|
+
// the periodic one is unrelated, and the one the platform emits on migration arrives before any of this.
|
|
1482
|
+
await this.statistics.persistState?.();
|
|
1453
1483
|
}
|
|
1454
1484
|
/**
|
|
1455
1485
|
* Fetches the next request to process from the underlying request provider.
|
|
1456
1486
|
*/
|
|
1457
|
-
async fetchNextRequest() {
|
|
1487
|
+
async #fetchNextRequest() {
|
|
1458
1488
|
if (this.requestManager === undefined) {
|
|
1459
1489
|
throw new Error(`fetchNextRequest called on an uninitialized crawler`);
|
|
1460
1490
|
}
|
|
1461
1491
|
return this.requestManager.fetchNextRequest();
|
|
1462
1492
|
}
|
|
1463
|
-
/**
|
|
1493
|
+
/** Runs the request handler and marks the request as handled. Failures are left to `handleRequestFailure`. */
|
|
1494
|
+
// oxlint-disable-next-line crawlee/prefer-private-fields -- patched by @crawlee/otel
|
|
1464
1495
|
async handleRequest(crawlingContext, requestSource, request) {
|
|
1465
1496
|
// An earlier phase we cannot cancel (e.g. a slow `extendContext`) may have run past the internal timeout,
|
|
1466
1497
|
// which already failed the request in `runTaskFunction`. Bail before running the handler so it does not
|
|
@@ -1468,68 +1499,88 @@ export class BasicCrawler {
|
|
|
1468
1499
|
if (crawlingContext[timeoutExpiredKey]?.()) {
|
|
1469
1500
|
return;
|
|
1470
1501
|
}
|
|
1471
|
-
|
|
1502
|
+
request.state = RequestState.REQUEST_HANDLER;
|
|
1503
|
+
await this.runRequestHandler(crawlingContext);
|
|
1504
|
+
// Commit *before* marking the request as handled, so a commit failure fails the request and
|
|
1505
|
+
// it is retried. This also closes the transaction, so everything below passes through.
|
|
1472
1506
|
// Opened by `runInStorageTransaction`; absent when disabled or when the subclass opens its own.
|
|
1473
|
-
|
|
1474
|
-
|
|
1507
|
+
await currentStorageTransaction()?.commit();
|
|
1508
|
+
await this.#timeoutAndRetry(async () => requestSource.markRequestAsHandled(request), this.internalTimeoutMillis, `Marking request ${request.url} (${request.id}) as handled timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1509
|
+
this.statistics.recordRequestSuccess(request.id || request.uniqueKey, request.retryCount);
|
|
1510
|
+
// reclaim session if request finishes successfully
|
|
1511
|
+
request.state = RequestState.DONE;
|
|
1512
|
+
crawlingContext.session.markGood();
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Handles a request that failed anywhere in the context pipeline - a middleware (e.g. navigation or its hooks)
|
|
1516
|
+
* or `handleRequest`. Runs inside the pipeline call, so the cleanups (e.g. closing the page) only fire after the
|
|
1517
|
+
* error handler has seen the context.
|
|
1518
|
+
*/
|
|
1519
|
+
async #handleRequestFailure(rawError, crawlingContext, requestSource, request) {
|
|
1520
|
+
// Roll back *before* any error handler runs - error handlers write to real storage precisely
|
|
1521
|
+
// because the transaction is already closed. A no-op when the commit in `handleRequest` succeeded.
|
|
1522
|
+
currentStorageTransaction()?.rollback();
|
|
1523
|
+
const resumeRequestTimeout = crawlingContext[suspendTimeoutKey]?.();
|
|
1475
1524
|
try {
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
if (!(err instanceof CriticalError)) {
|
|
1497
|
-
isRequestLocked = false; // requestFunctionErrorHandler calls either markRequestAsHandled or reclaimRequest
|
|
1498
|
-
}
|
|
1525
|
+
const unwrappedError = this.#unwrapError(rawError);
|
|
1526
|
+
// A failing or timed out `onSkippedRequest` makes this an ordinary failure, so the request gets retried.
|
|
1527
|
+
const err = unwrappedError instanceof ContextPipelineInterruptedError
|
|
1528
|
+
? await this.#trySkipRequest(unwrappedError, request, requestSource)
|
|
1529
|
+
: unwrappedError;
|
|
1530
|
+
if (err) {
|
|
1531
|
+
await this.#runErrorHandler(err, crawlingContext, requestSource, request);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
finally {
|
|
1535
|
+
resumeRequestTimeout?.();
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
async #runErrorHandler(err, context, requestSource, request) {
|
|
1539
|
+
const retryCountBefore = request.retryCount;
|
|
1540
|
+
try {
|
|
1541
|
+
request.state = RequestState.ERROR_HANDLER;
|
|
1542
|
+
await addTimeoutToPromise(async () => this.requestFunctionErrorHandler(err, context, request, requestSource), this.internalTimeoutMillis, `Handling request failure of ${request.url} (${request.id}) timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1543
|
+
// The error handler may have set `SKIPPED`; TS keeps the narrowing from the assignment above.
|
|
1544
|
+
if (request.state !== RequestState.SKIPPED) {
|
|
1499
1545
|
request.state = RequestState.DONE;
|
|
1500
1546
|
}
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1547
|
+
}
|
|
1548
|
+
catch (secondaryError) {
|
|
1549
|
+
const unwrappedSecondaryError = this.#unwrapError(secondaryError);
|
|
1550
|
+
const timedOut = unwrappedSecondaryError instanceof TimeoutError;
|
|
1551
|
+
request.state = RequestState.ERROR;
|
|
1552
|
+
if (timedOut) {
|
|
1553
|
+
// Not worth crashing the crawler over. The request's state is unknown, so it gets retried - and the
|
|
1554
|
+
// retry is counted, so that an error handler that always times out does not retry it forever.
|
|
1555
|
+
this.log.warning(unwrappedSecondaryError.message);
|
|
1556
|
+
if (request.retryCount === retryCountBefore) {
|
|
1557
|
+
request.retryCount++;
|
|
1511
1558
|
}
|
|
1512
|
-
request.state = RequestState.ERROR;
|
|
1513
|
-
throw unwrappedSecondaryError;
|
|
1514
1559
|
}
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1560
|
+
else if (!(unwrappedSecondaryError instanceof CriticalError)) {
|
|
1561
|
+
// avoid reprinting the same critical error multiple times, as it will be printed by Nodejs at the end anyway
|
|
1562
|
+
const apifySpecific = process.env.APIFY_IS_AT_HOME
|
|
1563
|
+
? `This may have happened due to an internal error of Apify's API or due to a misconfigured crawler.`
|
|
1564
|
+
: '';
|
|
1565
|
+
this.log.exception(unwrappedSecondaryError, 'An exception occurred during handling of failed request. ' +
|
|
1566
|
+
`This places the crawler and its underlying storages into an unknown state and crawling will be terminated. ${apifySpecific}`);
|
|
1519
1567
|
}
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
await requestSource.reclaimRequest(request);
|
|
1528
|
-
}
|
|
1529
|
-
catch {
|
|
1530
|
-
// The request was never in progress, or could not be reclaimed. Either way it's fine.
|
|
1531
|
-
}
|
|
1568
|
+
// Safety net - the error handler neither marked the request as handled nor reclaimed it (e.g. after a
|
|
1569
|
+
// CriticalError). Reclaiming a request that is no longer in progress is a harmless no-op on the storage backend.
|
|
1570
|
+
try {
|
|
1571
|
+
await addTimeoutToPromise(async () => requestSource.reclaimRequest(request), this.internalTimeoutMillis, `Reclaiming request ${request.url} (${request.id}) timed out.`);
|
|
1572
|
+
}
|
|
1573
|
+
catch {
|
|
1574
|
+
// The request was never in progress, or could not be reclaimed. Either way it's fine.
|
|
1532
1575
|
}
|
|
1576
|
+
if (!timedOut) {
|
|
1577
|
+
throw unwrappedSecondaryError;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
// decrease the session score if the request fails (but the error handler did not throw);
|
|
1581
|
+
// skip when the error is a SessionError, which already retired the session
|
|
1582
|
+
if (!this.#errorAbsolvesSession(err)) {
|
|
1583
|
+
context.session?.markBad();
|
|
1533
1584
|
}
|
|
1534
1585
|
}
|
|
1535
1586
|
/**
|
|
@@ -1541,6 +1592,11 @@ export class BasicCrawler {
|
|
|
1541
1592
|
if (typeof request === 'string') {
|
|
1542
1593
|
yield { url: request, crawlDepth: newRequestDepth };
|
|
1543
1594
|
}
|
|
1595
|
+
else if (request instanceof Request) {
|
|
1596
|
+
const crawlee = (request.userData.__crawlee ??= {});
|
|
1597
|
+
crawlee.crawlDepth ??= newRequestDepth;
|
|
1598
|
+
yield request;
|
|
1599
|
+
}
|
|
1544
1600
|
else {
|
|
1545
1601
|
request.crawlDepth ??= newRequestDepth;
|
|
1546
1602
|
yield request;
|
|
@@ -1551,7 +1607,7 @@ export class BasicCrawler {
|
|
|
1551
1607
|
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
1552
1608
|
* @ignore
|
|
1553
1609
|
*/
|
|
1554
|
-
async timeoutAndRetry(handler, timeout, error, maxRetries = 3, retried = 1) {
|
|
1610
|
+
async #timeoutAndRetry(handler, timeout, error, maxRetries = 3, retried = 1) {
|
|
1555
1611
|
try {
|
|
1556
1612
|
return await addTimeoutToPromise(handler, timeout, error);
|
|
1557
1613
|
}
|
|
@@ -1559,32 +1615,34 @@ export class BasicCrawler {
|
|
|
1559
1615
|
if (retried <= maxRetries) {
|
|
1560
1616
|
// we retry on any error, not just timeout
|
|
1561
1617
|
this.log.warning(`${e.message} (retrying ${retried}/${maxRetries})`);
|
|
1562
|
-
return this
|
|
1618
|
+
return this.#timeoutAndRetry(handler, timeout, error, maxRetries, retried + 1);
|
|
1563
1619
|
}
|
|
1564
1620
|
throw e;
|
|
1565
1621
|
}
|
|
1566
1622
|
}
|
|
1567
1623
|
/**
|
|
1568
|
-
*
|
|
1624
|
+
* Whether the request manager has a request ready for processing. A manager that is only `waiting` also gets a
|
|
1625
|
+
* wake-up scheduled, so a paced crawl resumes on its clock rather than on the task loop's polling interval.
|
|
1569
1626
|
*/
|
|
1570
|
-
async isTaskReadyFunction() {
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1627
|
+
async #isTaskReadyFunction() {
|
|
1628
|
+
if (this.requestManager === undefined) {
|
|
1629
|
+
return false;
|
|
1630
|
+
}
|
|
1631
|
+
const state = await this.requestManager.checkReadiness();
|
|
1632
|
+
if (state.status === 'waiting' && state.readyAt !== undefined) {
|
|
1633
|
+
this.#run?.scheduleWake(state.readyAt);
|
|
1634
|
+
}
|
|
1635
|
+
return state.status === 'ready';
|
|
1578
1636
|
}
|
|
1579
1637
|
/**
|
|
1580
1638
|
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
1581
|
-
* RequestHandlerError and
|
|
1639
|
+
* RequestHandlerError, ContextPipelineInitializationError and ContextPipelineCleanupError wrap the actual error.
|
|
1582
1640
|
*/
|
|
1583
|
-
unwrapError(error) {
|
|
1641
|
+
#unwrapError(error) {
|
|
1584
1642
|
if (error instanceof RequestHandlerError ||
|
|
1585
1643
|
error instanceof ContextPipelineInitializationError ||
|
|
1586
1644
|
error instanceof ContextPipelineCleanupError) {
|
|
1587
|
-
return this
|
|
1645
|
+
return this.#unwrapError(error.cause);
|
|
1588
1646
|
}
|
|
1589
1647
|
return error;
|
|
1590
1648
|
}
|
|
@@ -1593,26 +1651,45 @@ export class BasicCrawler {
|
|
|
1593
1651
|
*
|
|
1594
1652
|
* @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
|
|
1595
1653
|
*/
|
|
1654
|
+
// oxlint-disable-next-line crawlee/prefer-private-fields -- patched by @crawlee/otel
|
|
1596
1655
|
async requestFunctionErrorHandler(error, crawlingContext, request, source) {
|
|
1597
1656
|
if (error instanceof RequestThrottledError) {
|
|
1598
|
-
// The domain told us to come back later, so the request was never really attempted. Put it back
|
|
1599
|
-
// without recording a failure - it costs neither a retry nor session reputation.
|
|
1657
|
+
// The domain told us to come back later, so the request was never really attempted. Put it back where
|
|
1658
|
+
// it was, without recording a failure - it costs neither a retry nor session reputation.
|
|
1600
1659
|
this.log.debug(`Deferring request because its domain is rate-limiting us. ${error.message}`, {
|
|
1601
1660
|
id: request.id,
|
|
1602
1661
|
url: request.url,
|
|
1603
1662
|
});
|
|
1604
|
-
await source.reclaimRequest(request, { forefront:
|
|
1663
|
+
await source.reclaimRequest(request, { forefront: true });
|
|
1605
1664
|
return;
|
|
1606
1665
|
}
|
|
1607
1666
|
request.pushErrorMessage(error);
|
|
1608
1667
|
if (error instanceof CriticalError) {
|
|
1609
1668
|
throw error;
|
|
1610
1669
|
}
|
|
1611
|
-
const shouldRetryRequest = this
|
|
1670
|
+
const shouldRetryRequest = this.#canRequestBeRetried(request, error);
|
|
1612
1671
|
if (shouldRetryRequest) {
|
|
1613
1672
|
await this.statistics.errorTrackerRetry.addAsync(error, crawlingContext);
|
|
1614
|
-
|
|
1615
|
-
|
|
1673
|
+
try {
|
|
1674
|
+
await this.#errorHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1675
|
+
error);
|
|
1676
|
+
}
|
|
1677
|
+
catch (handlerError) {
|
|
1678
|
+
if (handlerError instanceof ContextPipelineInterruptedError) {
|
|
1679
|
+
const skipError = await this.#trySkipRequest(handlerError, request, source);
|
|
1680
|
+
if (!skipError) {
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
// Retry for the original error. Routing `skipError` through `errorHandler` again
|
|
1684
|
+
// would loop forever with a handler that always skips.
|
|
1685
|
+
this.log.warning(`Skipping request ${request.url} failed, retrying it instead.`, {
|
|
1686
|
+
error: skipError.message,
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
else {
|
|
1690
|
+
throw handlerError;
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1616
1693
|
if (error instanceof SessionError) {
|
|
1617
1694
|
crawlingContext.session?.retire();
|
|
1618
1695
|
}
|
|
@@ -1627,7 +1704,7 @@ export class BasicCrawler {
|
|
|
1627
1704
|
url,
|
|
1628
1705
|
retryCount,
|
|
1629
1706
|
});
|
|
1630
|
-
await source.reclaimRequest(request
|
|
1707
|
+
await source.reclaimRequest(request);
|
|
1631
1708
|
return;
|
|
1632
1709
|
}
|
|
1633
1710
|
}
|
|
@@ -1648,18 +1725,38 @@ export class BasicCrawler {
|
|
|
1648
1725
|
// or failed more than retryCount times and will not be retried anymore.
|
|
1649
1726
|
// Mark the request as failed and do not retry.
|
|
1650
1727
|
await source.markRequestAsHandled(request);
|
|
1651
|
-
this.statistics.
|
|
1728
|
+
this.statistics.recordRequestFailure(request.id || request.uniqueKey, request.retryCount);
|
|
1652
1729
|
await this.handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
|
|
1653
1730
|
}
|
|
1731
|
+
/** Settles a skipped request. Returns the error that prevented that, leaving the request untouched if `onSkippedRequest` failed. */
|
|
1732
|
+
async #trySkipRequest(error, request, source) {
|
|
1733
|
+
try {
|
|
1734
|
+
await addTimeoutToPromise(async () => this.#handleSkippedRequest({ request, reason: error.reason, message: error.skipMessage }), this.internalTimeoutMillis, `onSkippedRequest for ${request.url} (${request.id}) timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1735
|
+
request.state = RequestState.SKIPPED;
|
|
1736
|
+
request.noRetry = true;
|
|
1737
|
+
await this.#timeoutAndRetry(async () => source.markRequestAsHandled(request), this.internalTimeoutMillis, `Marking request ${request.url} (${request.id}) as handled timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1738
|
+
this.statistics.discardRequestRecord(request.id || request.uniqueKey);
|
|
1739
|
+
return undefined;
|
|
1740
|
+
}
|
|
1741
|
+
catch (settleError) {
|
|
1742
|
+
return this.#unwrapError(settleError);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
// oxlint-disable-next-line crawlee/prefer-private-fields -- patched by @crawlee/otel
|
|
1654
1746
|
async handleFailedRequestHandler(crawlingContext, error) {
|
|
1655
1747
|
// Always log the last error regardless if the user provided a failedRequestHandler
|
|
1656
1748
|
const { id, url, method, uniqueKey } = crawlingContext.request;
|
|
1657
1749
|
const message = this.getMessageFromError(error, true);
|
|
1658
1750
|
this.log.error(`Request failed and reached maximum retries. ${message}`, { id, url, method, uniqueKey });
|
|
1659
|
-
|
|
1660
|
-
await this
|
|
1751
|
+
try {
|
|
1752
|
+
await this.#failedRequestHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1661
1753
|
error);
|
|
1662
1754
|
}
|
|
1755
|
+
catch (handlerError) {
|
|
1756
|
+
if (!(handlerError instanceof ContextPipelineInterruptedError))
|
|
1757
|
+
throw handlerError;
|
|
1758
|
+
this.log.warning(`skipRequest() has no effect in failedRequestHandler, request ${url} (${id}) has already failed.`);
|
|
1759
|
+
}
|
|
1663
1760
|
}
|
|
1664
1761
|
/**
|
|
1665
1762
|
* Resolves the most verbose error message from a thrown error
|
|
@@ -1674,7 +1771,8 @@ export class BasicCrawler {
|
|
|
1674
1771
|
const baseDir = process.cwd();
|
|
1675
1772
|
const userLine = stackLines.find((line) => line.includes(baseDir) && !line.includes('node_modules'));
|
|
1676
1773
|
if (error instanceof TimeoutError) {
|
|
1677
|
-
|
|
1774
|
+
// stack in timeout errors does not really help
|
|
1775
|
+
return (process.env.CRAWLEE_VERBOSE_LOG && error.stack) || error.message;
|
|
1678
1776
|
}
|
|
1679
1777
|
return process.env.CRAWLEE_VERBOSE_LOG || forceStack
|
|
1680
1778
|
? (error.stack ?? [error.message || error, ...stackLines].join('\n'))
|
|
@@ -1684,10 +1782,12 @@ export class BasicCrawler {
|
|
|
1684
1782
|
* Whether the session should be spared for this error - either because it was already retired, or because the
|
|
1685
1783
|
* failure says nothing about the session (a rate limit is a property of the domain).
|
|
1686
1784
|
*/
|
|
1687
|
-
errorAbsolvesSession(error) {
|
|
1688
|
-
return error instanceof SessionError ||
|
|
1785
|
+
#errorAbsolvesSession(error) {
|
|
1786
|
+
return (error instanceof SessionError ||
|
|
1787
|
+
error instanceof RequestThrottledError ||
|
|
1788
|
+
error instanceof ContextPipelineInterruptedError);
|
|
1689
1789
|
}
|
|
1690
|
-
canRequestBeRetried(request, error) {
|
|
1790
|
+
#canRequestBeRetried(request, error) {
|
|
1691
1791
|
// Request should never be retried, or the error encountered makes it not able to be retried.
|
|
1692
1792
|
if (request.noRetry || error instanceof NonRetryableError) {
|
|
1693
1793
|
return false;
|
|
@@ -1697,29 +1797,46 @@ export class BasicCrawler {
|
|
|
1697
1797
|
return true;
|
|
1698
1798
|
}
|
|
1699
1799
|
// Ensure there are more retries available for the request
|
|
1700
|
-
const maxRequestRetries = request.maxRetries ?? this
|
|
1800
|
+
const maxRequestRetries = request.maxRetries ?? this.#maxRequestRetries;
|
|
1701
1801
|
return request.retryCount < maxRequestRetries;
|
|
1702
1802
|
}
|
|
1703
1803
|
/**
|
|
1704
|
-
*
|
|
1804
|
+
* Ends the run in progress immediately, without waiting for the requests already in flight.
|
|
1705
1805
|
*
|
|
1706
|
-
* This
|
|
1806
|
+
* This runs at the end of every {@link BasicCrawler.run|`run()`}, so what it releases is per-run only, and
|
|
1807
|
+
* a repeated `run()` has to find everything it needs either intact or re-establishable. What outlives a run is
|
|
1808
|
+
* released by {@link BasicCrawler.destroy|`destroy()`} instead.
|
|
1707
1809
|
*
|
|
1708
1810
|
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
1709
1811
|
*/
|
|
1710
1812
|
async teardown() {
|
|
1813
|
+
const eventManager = serviceLocator.getEventManager();
|
|
1814
|
+
const ownsEventManager = this.#run?.ownsEventManager === true;
|
|
1815
|
+
// First, so that the pool writes its final state once - its teardown stops it listening before the
|
|
1816
|
+
// persistence event below goes out.
|
|
1817
|
+
await this.#sessionPoolDep.ifOwned(async (pool) => pool.teardown());
|
|
1711
1818
|
// When this crawler initialized the event manager, its close() call emits
|
|
1712
1819
|
// the final persistence event after the crawler-specific state has been
|
|
1713
1820
|
// saved. External event managers still need an explicit event here.
|
|
1714
|
-
if (!
|
|
1715
|
-
|
|
1821
|
+
if (!ownsEventManager) {
|
|
1822
|
+
eventManager.emit(EventType.PERSIST_STATE, { isMigrating: false });
|
|
1716
1823
|
}
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
await serviceLocator.getEventManager().close();
|
|
1824
|
+
if (ownsEventManager) {
|
|
1825
|
+
await eventManager.close();
|
|
1720
1826
|
}
|
|
1721
|
-
await this.#
|
|
1722
|
-
|
|
1827
|
+
await this.#run?.end();
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Releases what the crawler owns beyond a single run — in the browser crawlers, the browser pool. A finished
|
|
1831
|
+
* `run()` has already released everything a run owns, so this is only needed before dropping a crawler you
|
|
1832
|
+
* could otherwise have run again.
|
|
1833
|
+
*/
|
|
1834
|
+
async destroy() {
|
|
1835
|
+
// An abandoned run - one whose `run()` never returned - would otherwise keep dispatching requests.
|
|
1836
|
+
await this.#run?.end();
|
|
1837
|
+
}
|
|
1838
|
+
async [Symbol.asyncDispose]() {
|
|
1839
|
+
await this.destroy();
|
|
1723
1840
|
}
|
|
1724
1841
|
getCookieHeaderFromRequest(request) {
|
|
1725
1842
|
if (request.headers?.Cookie && request.headers?.cookie) {
|
|
@@ -1728,7 +1845,7 @@ export class BasicCrawler {
|
|
|
1728
1845
|
}
|
|
1729
1846
|
return request.headers?.Cookie || request.headers?.cookie || '';
|
|
1730
1847
|
}
|
|
1731
|
-
requestMatchesEnqueueStrategy(request) {
|
|
1848
|
+
#requestMatchesEnqueueStrategy(request) {
|
|
1732
1849
|
// If `skipNavigation` was used, just return `true`
|
|
1733
1850
|
try {
|
|
1734
1851
|
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
|
@@ -1741,8 +1858,7 @@ export class BasicCrawler {
|
|
|
1741
1858
|
throw err;
|
|
1742
1859
|
}
|
|
1743
1860
|
const { url, loadedUrl } = request;
|
|
1744
|
-
|
|
1745
|
-
const strategy = request['enqueueStrategy'];
|
|
1861
|
+
const strategy = request.enqueueStrategy;
|
|
1746
1862
|
// No strategy set, so we assume it matches, or it was added outside of enqueueLinks
|
|
1747
1863
|
if (!strategy) {
|
|
1748
1864
|
return true;
|