@crawlee/basic 4.0.0-beta.15 → 4.0.0-beta.150
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 +14 -14
- package/index.d.ts +0 -2
- package/index.js +0 -1
- package/internals/basic-crawler.d.ts +442 -324
- package/internals/basic-crawler.js +1302 -746
- package/internals/request-timeout.d.ts +48 -0
- package/internals/request-timeout.js +73 -0
- package/internals/send-request.d.ts +4 -4
- package/internals/send-request.js +21 -23
- package/package.json +14 -12
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/internals/basic-crawler.d.ts.map +0 -1
- package/internals/basic-crawler.js.map +0 -1
- package/internals/send-request.d.ts.map +0 -1
- package/internals/send-request.js.map +0 -1
|
@@ -1,16 +1,35 @@
|
|
|
1
|
-
import { writeFile } from 'node:fs/promises';
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
|
-
import { AutoscaledPool, Configuration, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, CriticalError,
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import ow from 'ow';
|
|
3
|
+
import { applyRequestTransform, AutoscaledPool, bindMethodsToServiceLocator, BLOCKED_STATUS_CODES, buildEnqueueStrategyPatterns, ConcurrencySystem, Configuration, constructUrlPatternObjects, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, createRequestOptions, createSkippedRequestArgs, createStorageTransaction, Request, CriticalError, currentStorageTransaction, Dataset, EnqueueStrategy, EventManager, EventType, filterRequestOptionsByPatterns, getObjectType, KeyValueStore, log, LogLevel, mergeCookies, MissingSessionError, NavigationSkippedError, NonRetryableError, OwnedOrInjected, PersistentRateLimitError, purgeDefaultStorages, RequestHandlerError, parseRetryAfterHeader, RequestThrottledError, RequestManagerTandem, RequestQueue, RequestState, RetryRequestError, Router, ServiceLocator, serviceLocator, Session, SessionError, SessionPool, Statistics, ThrottlingRequestManager, validateUserData, validators, withDirectStorageAccess, } from '@crawlee/core';
|
|
4
|
+
import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client';
|
|
5
|
+
import { isAsyncIterable, isIterable, parseArgument, ROTATE_PROXY_ERRORS, schemas } from '@crawlee/utils/internal';
|
|
6
|
+
import { RobotsTxtFile } from '@crawlee/utils';
|
|
8
7
|
import { getDomain } from 'tldts';
|
|
8
|
+
import { z } from 'zod';
|
|
9
9
|
import { LruCache } from '@apify/datastructures';
|
|
10
|
-
import
|
|
11
|
-
import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
|
|
10
|
+
import { addTimeoutToPromise, extendTimeout, TimeoutError, tryCancel } from '@apify/timeout';
|
|
12
11
|
import { cryptoRandomObjectId } from '@apify/utilities';
|
|
12
|
+
import { extendTimeoutKey, navigationDeadlineKey, raceWithTimeout, timeoutExpiredKey, } from './request-timeout.js';
|
|
13
13
|
import { createSendRequest } from './send-request.js';
|
|
14
|
+
class LazyDefaultHttpClient extends BaseHttpClient {
|
|
15
|
+
#delegatePromise;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
super(options);
|
|
18
|
+
this.#delegatePromise = import('@crawlee/impit-client')
|
|
19
|
+
.then(({ ImpitHttpClient }) => new ImpitHttpClient(options))
|
|
20
|
+
.catch(() => {
|
|
21
|
+
(options?.logger ?? log).warning('Optional dependency @crawlee/impit-client is not installed. ' +
|
|
22
|
+
'Falling back to native fetch — proxy support and browser fingerprinting are unavailable.');
|
|
23
|
+
return new FetchHttpClient(options);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
fetch() {
|
|
27
|
+
throw new Error('LazyDefaultHttpClient delegates `sendRequest` entirely; `fetch` is never called.');
|
|
28
|
+
}
|
|
29
|
+
async sendRequest(...args) {
|
|
30
|
+
return (await this.#delegatePromise).sendRequest(...args);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
14
33
|
/**
|
|
15
34
|
* Since there's no set number of seconds before the container is terminated after
|
|
16
35
|
* a migration event, we need some reasonable number to use for RequestList persistence.
|
|
@@ -21,107 +40,117 @@ import { createSendRequest } from './send-request.js';
|
|
|
21
40
|
* @ignore
|
|
22
41
|
*/
|
|
23
42
|
const SAFE_MIGRATION_WAIT_MILLIS = 20000;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
* underlying {@link AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
|
|
55
|
-
*
|
|
56
|
-
* **Example usage:**
|
|
57
|
-
*
|
|
58
|
-
* ```javascript
|
|
59
|
-
* import { BasicCrawler, Dataset } from 'crawlee';
|
|
60
|
-
*
|
|
61
|
-
* // Create a crawler instance
|
|
62
|
-
* const crawler = new BasicCrawler({
|
|
63
|
-
* async requestHandler({ request, sendRequest }) {
|
|
64
|
-
* // 'request' contains an instance of the Request class
|
|
65
|
-
* // Here we simply fetch the HTML of the page and store it to a dataset
|
|
66
|
-
* const { body } = await sendRequest({
|
|
67
|
-
* url: request.url,
|
|
68
|
-
* method: request.method,
|
|
69
|
-
* body: request.payload,
|
|
70
|
-
* headers: request.headers,
|
|
71
|
-
* });
|
|
72
|
-
*
|
|
73
|
-
* await Dataset.pushData({
|
|
74
|
-
* url: request.url,
|
|
75
|
-
* html: body,
|
|
76
|
-
* })
|
|
77
|
-
* },
|
|
78
|
-
* });
|
|
79
|
-
*
|
|
80
|
-
* // Enqueue the initial requests and run the crawler
|
|
81
|
-
* await crawler.run([
|
|
82
|
-
* 'http://www.example.com/page-1',
|
|
83
|
-
* 'http://www.example.com/page-2',
|
|
84
|
-
* ]);
|
|
85
|
-
* ```
|
|
86
|
-
* @category Crawlers
|
|
87
|
-
*/
|
|
43
|
+
const deferredCleanupKey = Symbol('deferredCleanup');
|
|
44
|
+
// The request timeout plumbing (the window helper, the context symbols, and the race) lives in its own module.
|
|
45
|
+
export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
|
|
46
|
+
const urlPatternSchema = z.union([
|
|
47
|
+
z.string(),
|
|
48
|
+
z.instanceof(RegExp),
|
|
49
|
+
schemas.objectWithKeys(['glob']),
|
|
50
|
+
schemas.objectWithKeys(['regexp']),
|
|
51
|
+
]);
|
|
52
|
+
// `looseObject` (rather than `strictObject`) lets subclasses forward their own extraction-only options
|
|
53
|
+
// (e.g. `selector`) straight through without having to strip them out first.
|
|
54
|
+
const addRequestsOptionsSchema = z.looseObject({
|
|
55
|
+
forefront: z.boolean().optional(),
|
|
56
|
+
cache: z.boolean().optional(),
|
|
57
|
+
waitForAllRequestsToBeAdded: z.boolean().optional(),
|
|
58
|
+
batchSize: schemas.anyNumber.optional(),
|
|
59
|
+
waitBetweenBatchesMillis: schemas.anyNumber.optional(),
|
|
60
|
+
maxNewRequests: schemas.anyNumber.optional(),
|
|
61
|
+
limit: schemas.anyNumber.optional(),
|
|
62
|
+
baseUrl: z.string().optional(),
|
|
63
|
+
userData: schemas.anyObject.optional(),
|
|
64
|
+
label: z.string().optional(),
|
|
65
|
+
sessionId: z.string().optional(),
|
|
66
|
+
skipNavigation: z.boolean().optional(),
|
|
67
|
+
include: schemas.arrayOf(urlPatternSchema, 'URL patterns').min(1).optional(),
|
|
68
|
+
exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
|
|
69
|
+
transformRequestFunction: schemas.anyFunction.optional(),
|
|
70
|
+
strategy: z.enum(EnqueueStrategy).optional(),
|
|
71
|
+
onSkippedRequest: schemas.anyFunction.optional(),
|
|
72
|
+
});
|
|
88
73
|
export class BasicCrawler {
|
|
89
|
-
|
|
90
|
-
static CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
|
|
74
|
+
static #CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
|
|
91
75
|
/**
|
|
92
|
-
*
|
|
76
|
+
* Tracks the number of crawler instances created. The first crawler uses the default
|
|
77
|
+
* request queue; subsequent ones get their own queue via a unique alias so they don't
|
|
78
|
+
* collide.
|
|
93
79
|
*/
|
|
94
|
-
|
|
80
|
+
// kept as TS-private: tests reset the counter at runtime
|
|
81
|
+
static instanceCount = 0;
|
|
95
82
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
83
|
+
* Tracks crawler instances that accessed shared state without having an explicit id.
|
|
84
|
+
* Used to detect and warn about multiple crawlers sharing the same state.
|
|
98
85
|
*/
|
|
99
|
-
|
|
86
|
+
static #useStateAnonymousIndices = new Set();
|
|
87
|
+
/** Backs the {@link BasicCrawler.statistics|`statistics`} getter. */
|
|
88
|
+
#statisticsDep;
|
|
100
89
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* Only available if used by the crawler.
|
|
90
|
+
* The statistics instance collecting the crawler's run statistics - either the injected `statistics` option or a
|
|
91
|
+
* crawler-built default. Typed as {@link IStatistics} so custom implementations can be plugged in.
|
|
104
92
|
*/
|
|
105
|
-
|
|
93
|
+
get statistics() {
|
|
94
|
+
return this.#statisticsDep.value;
|
|
95
|
+
}
|
|
106
96
|
/**
|
|
107
|
-
* The main request-handling component of the crawler. It
|
|
97
|
+
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
|
|
98
|
+
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
|
|
99
|
+
* via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
|
|
108
100
|
*/
|
|
109
101
|
requestManager;
|
|
102
|
+
/** Backs the {@link BasicCrawler.sessionPool|`sessionPool`} getter. */
|
|
103
|
+
#sessionPoolDep;
|
|
110
104
|
/**
|
|
111
|
-
* A reference to the underlying
|
|
112
|
-
*
|
|
105
|
+
* A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
|
|
106
|
+
* {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
|
|
107
|
+
*/
|
|
108
|
+
get sessionPool() {
|
|
109
|
+
return this.#sessionPoolDep.value;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Whether the request-processing-time hint has already been forwarded to the request manager. The hint
|
|
113
|
+
* derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
|
|
114
|
+
* so it only needs to be applied once, at the first async access of the manager.
|
|
115
|
+
*/
|
|
116
|
+
#requestManagerTimeoutsApplied = false;
|
|
117
|
+
/**
|
|
118
|
+
* Resolves the governor for one run: either the injected
|
|
119
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} (borrowed) or a freshly built default with
|
|
120
|
+
* the concurrency shortcuts folded in (owned, so the crawler starts and stops it).
|
|
121
|
+
*/
|
|
122
|
+
#resolveConcurrencySystem;
|
|
123
|
+
/** As resolved by `init()`. Absent until the first run, so a `teardown()` before it is a no-op. */
|
|
124
|
+
#concurrencySystemDep;
|
|
125
|
+
/**
|
|
126
|
+
* The concurrency governor this run is booking its requests against — either the
|
|
127
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
|
|
128
|
+
* crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
|
|
129
|
+
*
|
|
130
|
+
* > *NOTE:* `undefined` until {@link BasicCrawler.run|`crawler.run()`} has resolved it. A crawler-owned default
|
|
131
|
+
* is also rebuilt for every run, so the instance is not stable across runs.
|
|
132
|
+
*
|
|
133
|
+
* {@link IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
|
|
134
|
+
* owning the instance: build a {@link ConcurrencySystem} yourself and inject it, then set
|
|
135
|
+
* `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
|
|
113
136
|
*/
|
|
114
|
-
|
|
137
|
+
get concurrencySystem() {
|
|
138
|
+
return this.#concurrencySystemDep?.maybeValue;
|
|
139
|
+
}
|
|
115
140
|
/**
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
141
|
+
* The task loop that dispatches this run's requests. Private on purpose — it is a bare parallel task runner with
|
|
142
|
+
* no configuration left of its own (see {@link ConcurrencySystem}), and everything a caller legitimately did
|
|
143
|
+
* with it now has a crawler-level counterpart: {@link BasicCrawler.pause|`pause()`},
|
|
144
|
+
* {@link BasicCrawler.resume|`resume()`}, {@link BasicCrawler.teardown|`teardown()`} and
|
|
145
|
+
* {@link BasicCrawler.concurrencySystem|`concurrencySystem`}.
|
|
121
146
|
*/
|
|
122
|
-
autoscaledPool;
|
|
147
|
+
#autoscaledPool;
|
|
148
|
+
/** A pending nudge of the task loop, armed when the request manager announces when it will have work again. */
|
|
149
|
+
#taskLoopWakeTimer;
|
|
150
|
+
/** When the pending wake-up is due, so an earlier one can replace a later one. */
|
|
151
|
+
#taskLoopWakeAt = 0;
|
|
123
152
|
/**
|
|
124
|
-
* A reference to the underlying {@link
|
|
153
|
+
* A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
|
|
125
154
|
* Only available if used by the crawler.
|
|
126
155
|
*/
|
|
127
156
|
proxyConfiguration;
|
|
@@ -130,238 +159,561 @@ export class BasicCrawler {
|
|
|
130
159
|
* See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
|
|
131
160
|
*/
|
|
132
161
|
router = Router.create();
|
|
133
|
-
|
|
134
|
-
|
|
162
|
+
#basicContextPipeline;
|
|
163
|
+
/**
|
|
164
|
+
* The basic part of the context pipeline. Unlike the subclass pipeline, this
|
|
165
|
+
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
|
|
166
|
+
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
167
|
+
*
|
|
168
|
+
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
169
|
+
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
170
|
+
*/
|
|
171
|
+
get basicContextPipeline() {
|
|
172
|
+
if (this.#basicContextPipeline === undefined) {
|
|
173
|
+
this.#basicContextPipeline = this.buildBasicContextPipeline();
|
|
174
|
+
}
|
|
175
|
+
return this.#basicContextPipeline;
|
|
176
|
+
}
|
|
177
|
+
#contextPipeline;
|
|
135
178
|
get contextPipeline() {
|
|
136
|
-
if (this
|
|
137
|
-
this
|
|
179
|
+
if (this.#contextPipeline === undefined) {
|
|
180
|
+
this.#contextPipeline = this.buildFinalContextPipeline();
|
|
138
181
|
}
|
|
139
|
-
return this
|
|
182
|
+
return this.#contextPipeline;
|
|
140
183
|
}
|
|
141
184
|
running = false;
|
|
142
185
|
hasFinishedBefore = false;
|
|
143
|
-
|
|
186
|
+
#unexpectedStop = false;
|
|
187
|
+
#log;
|
|
188
|
+
get log() {
|
|
189
|
+
return this.#log;
|
|
190
|
+
}
|
|
144
191
|
requestHandler;
|
|
145
|
-
errorHandler;
|
|
146
|
-
failedRequestHandler;
|
|
147
|
-
requestHandlerTimeoutMillis;
|
|
192
|
+
#errorHandler;
|
|
193
|
+
#failedRequestHandler;
|
|
194
|
+
#requestHandlerTimeoutMillis;
|
|
148
195
|
internalTimeoutMillis;
|
|
149
|
-
maxRequestRetries;
|
|
150
|
-
maxCrawlDepth;
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
196
|
+
#maxRequestRetries;
|
|
197
|
+
#maxCrawlDepth;
|
|
198
|
+
/**
|
|
199
|
+
* How much of {@link BasicCrawler.requestManager} the crawler may empty between repeated `run()` calls.
|
|
200
|
+
*
|
|
201
|
+
* - `all` — nothing under it came from the caller, so one `purge()` on the outside covers everything.
|
|
202
|
+
* - `none` — the caller supplied it and the crawler put nothing of its own inside.
|
|
203
|
+
* - `ambiguous` — the caller supplied it, but `sameDomainDelaySecs` put the crawler's own per-domain queues
|
|
204
|
+
* underneath: purging empties the caller's storage too, skipping leaves ours stale. A repeated `run()` asks
|
|
205
|
+
* rather than guessing.
|
|
206
|
+
*/
|
|
207
|
+
#purgeableExtent;
|
|
208
|
+
#maxRequestsPerCrawl;
|
|
209
|
+
get handledRequestsCount() {
|
|
210
|
+
return this.statistics.state.requestsFinished + this.statistics.state.requestsFailed;
|
|
211
|
+
}
|
|
212
|
+
#statusMessageLoggingInterval;
|
|
213
|
+
#statusMessageCallback;
|
|
214
|
+
blockedStatusCodes = new Set();
|
|
215
|
+
additionalHttpErrorStatusCodes;
|
|
216
|
+
#ignoreHttpErrorStatusCodes;
|
|
217
|
+
/**
|
|
218
|
+
* The resolved options for the crawler's own task loop — the crawler-owned `runTaskFunction`, the (possibly
|
|
219
|
+
* user-overridden) ready/finished predicates and cadence/logging. Concurrency configuration lives on the
|
|
220
|
+
* {@link ConcurrencySystem} instead, and the loop's `consumer` identity is the crawler's own, so neither is
|
|
221
|
+
* settable here.
|
|
222
|
+
*/
|
|
223
|
+
#taskLoopOptions;
|
|
162
224
|
httpClient;
|
|
163
225
|
retryOnBlocked;
|
|
164
|
-
respectRobotsTxtFile;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
226
|
+
#respectRobotsTxtFile;
|
|
227
|
+
/** Whether `runInStorageTransaction()` opens a transaction at all. */
|
|
228
|
+
#transactionalStorageEnabled;
|
|
229
|
+
/** The resolved per-storage-type write policy overrides forwarded to each request's transaction. */
|
|
230
|
+
#storageWritePolicy;
|
|
231
|
+
#onSkippedRequest;
|
|
232
|
+
#closeEvents;
|
|
233
|
+
#loggedPerRun = new Set();
|
|
234
|
+
#robotsTxtFileCache;
|
|
235
|
+
#identity;
|
|
236
|
+
#contextPipelineOptions;
|
|
237
|
+
/**
|
|
238
|
+
* @internal
|
|
239
|
+
*/
|
|
172
240
|
static optionsShape = {
|
|
173
|
-
contextPipelineBuilder:
|
|
174
|
-
extendContext:
|
|
175
|
-
requestList:
|
|
176
|
-
requestQueue:
|
|
241
|
+
contextPipelineBuilder: schemas.anyObject.optional(),
|
|
242
|
+
extendContext: schemas.anyFunction.optional(),
|
|
243
|
+
requestList: validators.requestList.optional(),
|
|
244
|
+
requestQueue: validators.requestQueue.optional(),
|
|
245
|
+
requestManager: validators.requestManager.optional(),
|
|
177
246
|
// Subclasses override this function instead of passing it
|
|
178
247
|
// in constructor, so this validation needs to apply only
|
|
179
248
|
// if the user creates an instance of BasicCrawler directly.
|
|
180
|
-
requestHandler:
|
|
181
|
-
requestHandlerTimeoutSecs:
|
|
182
|
-
errorHandler:
|
|
183
|
-
failedRequestHandler:
|
|
184
|
-
maxRequestRetries:
|
|
185
|
-
sameDomainDelaySecs:
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
proxyConfiguration:
|
|
193
|
-
statusMessageLoggingInterval:
|
|
194
|
-
statusMessageCallback:
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
249
|
+
requestHandler: schemas.anyFunction.optional(),
|
|
250
|
+
requestHandlerTimeoutSecs: schemas.anyNumber.optional(),
|
|
251
|
+
errorHandler: schemas.anyFunction.optional(),
|
|
252
|
+
failedRequestHandler: schemas.anyFunction.optional(),
|
|
253
|
+
maxRequestRetries: schemas.anyNumber.default(3),
|
|
254
|
+
sameDomainDelaySecs: schemas.anyNumber.default(0),
|
|
255
|
+
maxRequestsPerCrawl: schemas.anyNumber.optional(),
|
|
256
|
+
maxCrawlDepth: schemas.anyNumber.optional(),
|
|
257
|
+
// No zod default — subclasses provide their own fallback (e.g. HTTP-optimized pool options).
|
|
258
|
+
taskLoopOptions: schemas.anyObject.optional(),
|
|
259
|
+
concurrencySystem: schemas.anyObject.optional(),
|
|
260
|
+
sessionPool: validators.sessionPool.optional(),
|
|
261
|
+
proxyConfiguration: validators.proxyConfiguration.optional(),
|
|
262
|
+
statusMessageLoggingInterval: schemas.anyNumber.default(10),
|
|
263
|
+
statusMessageCallback: schemas.anyFunction.optional(),
|
|
264
|
+
additionalHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
|
|
265
|
+
ignoreHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
|
|
266
|
+
blockedStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').optional(),
|
|
267
|
+
retryOnBlocked: z.boolean().default(false),
|
|
268
|
+
respectRobotsTxtFile: z.union([z.boolean(), schemas.anyObject]).default(false),
|
|
269
|
+
transactionalStorage: z
|
|
270
|
+
.union([z.boolean(), z.strictObject({ requestQueue: z.enum(['deferred', 'writeThrough']).optional() })])
|
|
271
|
+
.optional(),
|
|
272
|
+
onSkippedRequest: schemas.anyFunction.optional(),
|
|
273
|
+
httpClient: schemas.httpClient.optional(),
|
|
274
|
+
configuration: z.instanceof(Configuration).optional(),
|
|
275
|
+
storageBackend: validators.storageBackend.optional(),
|
|
276
|
+
eventManager: z.instanceof(EventManager).optional(),
|
|
277
|
+
logger: validators.logger.optional(),
|
|
199
278
|
// AutoscaledPool shorthands
|
|
200
|
-
minConcurrency:
|
|
201
|
-
maxConcurrency:
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
279
|
+
minConcurrency: schemas.anyNumber.optional(),
|
|
280
|
+
maxConcurrency: schemas.anyNumber.optional(),
|
|
281
|
+
initialConcurrency: schemas.anyNumber.optional(),
|
|
282
|
+
maxRequestsPerMinute: schemas.anyNumber
|
|
283
|
+
.refine((value) => Number.isInteger(value) || value === Infinity, 'Expected an integer or infinite number')
|
|
284
|
+
.refine((value) => value >= 1, 'Expected a number greater than or equal to 1')
|
|
285
|
+
.optional(),
|
|
286
|
+
keepAlive: z.boolean().optional(),
|
|
287
|
+
statistics: schemas.anyObject.optional(),
|
|
288
|
+
id: z.string().optional(),
|
|
208
289
|
};
|
|
290
|
+
static #optionsSchema = z.strictObject(BasicCrawler.optionsShape);
|
|
209
291
|
/**
|
|
210
292
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
211
293
|
*/
|
|
212
|
-
constructor(options = {}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
294
|
+
constructor(options = {}) {
|
|
295
|
+
const parsedOptions = parseArgument(options, BasicCrawler.#optionsSchema, 'BasicCrawlerOptions');
|
|
296
|
+
const {
|
|
297
|
+
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
|
|
298
|
+
requestList,
|
|
299
|
+
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
|
|
300
|
+
requestQueue, requestManager, maxRequestRetries, sameDomainDelaySecs, maxRequestsPerCrawl, maxCrawlDepth, taskLoopOptions = {}, concurrencySystem, keepAlive, sessionPool, proxyConfiguration, additionalHttpErrorStatusCodes, ignoreHttpErrorStatusCodes,
|
|
301
|
+
// Service locator options
|
|
302
|
+
configuration, storageBackend, eventManager, logger,
|
|
217
303
|
// AutoscaledPool shorthands
|
|
218
|
-
minConcurrency, maxConcurrency, maxRequestsPerMinute,
|
|
219
|
-
//
|
|
220
|
-
|
|
221
|
-
//
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
304
|
+
minConcurrency, maxConcurrency, initialConcurrency, maxRequestsPerMinute, blockedStatusCodes: blockedStatusCodesInput, retryOnBlocked, respectRobotsTxtFile, transactionalStorage, onSkippedRequest, requestHandler, requestHandlerTimeoutSecs, errorHandler, failedRequestHandler, statusMessageLoggingInterval, statusMessageCallback, statistics, httpClient, id, } = parsedOptions;
|
|
305
|
+
// All concurrency configuration lives on the `ConcurrencySystem`, so the shortcuts have nowhere to go once
|
|
306
|
+
// one is supplied - and silently dropping a `maxConcurrency` the user asked for is how crawls end up
|
|
307
|
+
// hammering a site.
|
|
308
|
+
if (concurrencySystem !== undefined &&
|
|
309
|
+
(minConcurrency !== undefined ||
|
|
310
|
+
maxConcurrency !== undefined ||
|
|
311
|
+
initialConcurrency !== undefined ||
|
|
312
|
+
maxRequestsPerMinute !== undefined)) {
|
|
313
|
+
throw new Error('The `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute` shortcuts ' +
|
|
314
|
+
'cannot be combined with `concurrencySystem` - they configure the default `ConcurrencySystem` ' +
|
|
315
|
+
'that a supplied one replaces. Pass them to the `ConcurrencySystem` constructor instead.');
|
|
316
|
+
}
|
|
317
|
+
// Create per-crawler service locator if custom services were provided.
|
|
318
|
+
// This wraps every method on the crawler instance so that calls to the global `serviceLocator`
|
|
319
|
+
// (via AsyncLocalStorage) resolve to this scoped instance instead.
|
|
320
|
+
// We also enter the scope for the rest of the constructor body, so that any code below
|
|
321
|
+
// that accesses `serviceLocator` will see the correct (scoped) instance.
|
|
322
|
+
let serviceLocatorScope = { enterScope: () => { }, exitScope: () => { } };
|
|
323
|
+
if (storageBackend ||
|
|
324
|
+
eventManager ||
|
|
325
|
+
logger ||
|
|
326
|
+
(configuration !== undefined && configuration !== serviceLocator.getConfiguration())) {
|
|
327
|
+
// Inherit the ambient locator's already-set services for anything not explicitly
|
|
328
|
+
// provided - e.g. only passing a `logger` must not detach the crawler from a globally
|
|
329
|
+
// configured storage backend.
|
|
330
|
+
const ambientServices = serviceLocator.getServicesIfSet();
|
|
331
|
+
const scopedServiceLocator = new ServiceLocator(configuration ?? ambientServices.configuration, eventManager ?? ambientServices.eventManager, storageBackend ?? ambientServices.storageBackend, logger ?? ambientServices.logger);
|
|
332
|
+
serviceLocatorScope = bindMethodsToServiceLocator(scopedServiceLocator, this);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
serviceLocatorScope.enterScope();
|
|
336
|
+
this.#contextPipelineOptions = {
|
|
337
|
+
contextPipelineBuilder: parsedOptions.contextPipelineBuilder,
|
|
338
|
+
extendContext: parsedOptions.extendContext,
|
|
339
|
+
};
|
|
340
|
+
this.#log = serviceLocator.getLogger().child({ prefix: this.constructor.name });
|
|
341
|
+
// Initialize the Configuration instance to avoid lazy loading in the components
|
|
342
|
+
serviceLocator.getConfiguration();
|
|
343
|
+
const instanceIndex = BasicCrawler.instanceCount++;
|
|
344
|
+
this.#identity = { instanceIndex, hasExplicitId: id !== undefined, id: id ?? String(instanceIndex) };
|
|
345
|
+
if (requestManager !== undefined && (requestList !== undefined || requestQueue !== undefined)) {
|
|
346
|
+
throw new Error('The `requestManager` option cannot be used in conjunction with `requestList` and/or `requestQueue`');
|
|
347
|
+
}
|
|
348
|
+
const suppliedManager = requestManager ?? requestQueue;
|
|
349
|
+
// Offered before building a pacer of our own: anything that paces takes the floor - through any
|
|
350
|
+
// number of wrappers, since they all forward - so no domain ends up with two clocks.
|
|
351
|
+
const floorTaken = sameDomainDelaySecs > 0 &&
|
|
352
|
+
(suppliedManager?.recordPacingSignal({
|
|
353
|
+
reason: 'minIntervalEverywhere',
|
|
354
|
+
intervalMs: sameDomainDelaySecs * 1000,
|
|
355
|
+
// What `sameDomainDelaySecs` has always meant: one clock per site, subdomains included.
|
|
356
|
+
scope: 'registrableDomain',
|
|
357
|
+
}) ??
|
|
358
|
+
false);
|
|
359
|
+
const pacerNeeded = sameDomainDelaySecs > 0 && !floorTaken;
|
|
360
|
+
// Our per-domain queues under a manager the caller owns is the case with no right answer; a floor
|
|
361
|
+
// it took leaves nothing of ours behind. See `#purgeableExtent`.
|
|
362
|
+
if (suppliedManager === undefined) {
|
|
363
|
+
this.#purgeableExtent = 'all';
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
this.#purgeableExtent = pacerNeeded ? 'ambiguous' : 'none';
|
|
367
|
+
}
|
|
368
|
+
// Built here rather than at first use so it can sit *inside* the tandem below, which is where a
|
|
369
|
+
// loader's transferred requests pass through it.
|
|
370
|
+
const writableManager = pacerNeeded
|
|
371
|
+
? new ThrottlingRequestManager({
|
|
372
|
+
domains: 'all',
|
|
373
|
+
minCrawlDelaySecs: sameDomainDelaySecs,
|
|
374
|
+
throttleBy: 'registrableDomain',
|
|
375
|
+
persistStateKey: `CRAWLEE_THROTTLED_DOMAINS_${this.#identity.id}`,
|
|
376
|
+
// A factory, because the default queue is only opened on first use.
|
|
377
|
+
inner: suppliedManager ?? (() => this.openOwnedRequestQueue()),
|
|
378
|
+
})
|
|
379
|
+
: suppliedManager;
|
|
380
|
+
if (requestList !== undefined) {
|
|
381
|
+
// The list is read first, while new requests still have somewhere writable to go; the tandem also
|
|
382
|
+
// forwards `persistState()` to the loader.
|
|
383
|
+
this.requestManager = new RequestManagerTandem(requestList, writableManager ?? (() => this.openOwnedRequestQueue()));
|
|
384
|
+
}
|
|
385
|
+
else if (writableManager !== undefined) {
|
|
386
|
+
// A RequestQueue is itself a request manager.
|
|
387
|
+
this.requestManager = writableManager;
|
|
388
|
+
}
|
|
389
|
+
this.httpClient = httpClient ?? new LazyDefaultHttpClient({ logger: this.log });
|
|
390
|
+
this.proxyConfiguration = proxyConfiguration;
|
|
391
|
+
this.#statusMessageLoggingInterval = statusMessageLoggingInterval;
|
|
392
|
+
this.#statusMessageCallback = statusMessageCallback;
|
|
393
|
+
this.#robotsTxtFileCache = new LruCache({ maxLength: 1000 });
|
|
394
|
+
this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);
|
|
395
|
+
this.#ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);
|
|
396
|
+
this.requestHandler = requestHandler ?? this.router;
|
|
397
|
+
this.#failedRequestHandler = failedRequestHandler;
|
|
398
|
+
this.#errorHandler = errorHandler;
|
|
399
|
+
if (requestHandlerTimeoutSecs) {
|
|
400
|
+
this.#requestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
this.#requestHandlerTimeoutMillis = 60_000;
|
|
404
|
+
}
|
|
405
|
+
this.retryOnBlocked = retryOnBlocked;
|
|
406
|
+
this.#respectRobotsTxtFile = respectRobotsTxtFile;
|
|
407
|
+
// The cast undoes ow's assertion signature, which mangles `boolean | object` unions.
|
|
408
|
+
const transactionalStorageOption = transactionalStorage;
|
|
409
|
+
this.#transactionalStorageEnabled = transactionalStorageOption !== false;
|
|
410
|
+
this.#storageWritePolicy = typeof transactionalStorageOption === 'object' ? transactionalStorageOption : {};
|
|
411
|
+
this.#onSkippedRequest = onSkippedRequest;
|
|
412
|
+
// allow at least 5min for internal timeouts
|
|
413
|
+
this.internalTimeoutMillis =
|
|
414
|
+
serviceLocator.getConfiguration().internalTimeoutMillis ??
|
|
415
|
+
Math.max(this.#requestHandlerTimeoutMillis * 2, 300e3);
|
|
416
|
+
this.#maxRequestRetries = maxRequestRetries;
|
|
417
|
+
this.#maxCrawlDepth = maxCrawlDepth;
|
|
418
|
+
this.#statisticsDep = OwnedOrInjected.resolve(statistics,
|
|
419
|
+
// A crawler-built default tracks the built-in fields only. A non-empty `StatisticStateExtension` can
|
|
420
|
+
// only be satisfied by an injected instance carrying the matching `state`, so this branch does
|
|
421
|
+
// not run in that case - hence the cast.
|
|
422
|
+
() => new Statistics({
|
|
423
|
+
logMessage: `${this.constructor.name} request statistics:`,
|
|
424
|
+
log: this.log,
|
|
425
|
+
id: this.#identity.id,
|
|
426
|
+
}));
|
|
427
|
+
if (sessionPool && proxyConfiguration) {
|
|
428
|
+
this.log.warning('Both `sessionPool` and `proxyConfiguration` were provided to the crawler. ' +
|
|
429
|
+
'The `proxyConfiguration` is ignored - sessions from the supplied pool keep whatever ' +
|
|
430
|
+
'`proxyInfo` they were created with. Configure proxies on the pool instead, ' +
|
|
431
|
+
'e.g. via `addSession({ proxyInfo })` or a custom `createSessionFunction`.');
|
|
230
432
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
433
|
+
this.#sessionPoolDep = OwnedOrInjected.resolve(sessionPool, () => new SessionPool({
|
|
434
|
+
createSessionFunction: async (opts) => new Session({
|
|
435
|
+
...opts?.sessionOptions,
|
|
436
|
+
proxyInfo: opts?.sessionOptions?.proxyInfo ?? (await this.proxyConfiguration?.newProxyInfo()),
|
|
437
|
+
}),
|
|
438
|
+
}));
|
|
439
|
+
this.blockedStatusCodes = new Set(blockedStatusCodesInput ?? BLOCKED_STATUS_CODES);
|
|
440
|
+
const maxSignedInteger = 2 ** 31 - 1;
|
|
441
|
+
if (this.#requestHandlerTimeoutMillis > maxSignedInteger) {
|
|
442
|
+
this.log.warning(`requestHandlerTimeoutMillis ${this.#requestHandlerTimeoutMillis}` +
|
|
443
|
+
` does not fit a signed 32-bit integer. Limiting the value to ${maxSignedInteger}`);
|
|
444
|
+
this.#requestHandlerTimeoutMillis = maxSignedInteger;
|
|
445
|
+
}
|
|
446
|
+
this.internalTimeoutMillis = Math.min(this.internalTimeoutMillis, maxSignedInteger);
|
|
447
|
+
this.#maxRequestsPerCrawl = maxRequestsPerCrawl;
|
|
448
|
+
const isMaxPagesExceeded = () => this.#maxRequestsPerCrawl && this.#maxRequestsPerCrawl <= this.handledRequestsCount;
|
|
449
|
+
// eslint-disable-next-line prefer-const
|
|
450
|
+
let { isFinishedFunction, isTaskReadyFunction } = taskLoopOptions;
|
|
451
|
+
// override even if `isFinishedFunction` provided by user - `keepAlive` has higher priority
|
|
452
|
+
if (keepAlive) {
|
|
453
|
+
isFinishedFunction = async () => false;
|
|
454
|
+
}
|
|
455
|
+
const crawlerOwnedTaskLoopConfiguration = {
|
|
456
|
+
runTaskFunction: async () => {
|
|
457
|
+
const source = this.requestManager;
|
|
458
|
+
if (!source)
|
|
459
|
+
throw new Error('Request provider is not initialized!');
|
|
460
|
+
const request = await this.resolveRequest();
|
|
461
|
+
if (!request) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
// Started here, rather than in `handleRequest`, so that a failure during context pipeline
|
|
465
|
+
// initialization (e.g. a browser page timing out before the request handler ever runs) is
|
|
466
|
+
// still accounted for by `failJob` below - which is a no-op without a matching `startJob`.
|
|
467
|
+
this.statistics.startJob(request.id || request.uniqueKey);
|
|
468
|
+
const crawlingContext = { request };
|
|
469
|
+
try {
|
|
470
|
+
// The transaction spans the whole pipeline call, covering the navigation hooks
|
|
471
|
+
// and `extendContext` too; `handleRequest` drives its outcome explicitly.
|
|
472
|
+
await this.runInStorageTransaction(async () =>
|
|
473
|
+
// Navigation, the navigation hooks and the request handler are timed individually, but the
|
|
474
|
+
// phases between them are not, so a request could still get stuck indefinitely. This is the
|
|
475
|
+
// catch-all for that - see `raceWithTimeout` for why it is a bare timer, not a timeout frame.
|
|
476
|
+
await this.withRequestTimeout(crawlingContext, this.basicContextPipeline
|
|
477
|
+
.chain(this.contextPipeline)
|
|
478
|
+
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request))));
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
// ContextPipelineInterruptedError means the request was intentionally skipped
|
|
482
|
+
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
|
|
483
|
+
if (error instanceof ContextPipelineInterruptedError) {
|
|
484
|
+
this.statistics.discardJob(request.id || request.uniqueKey);
|
|
485
|
+
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.`);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
|
|
489
|
+
// i.e. not in user's requestHandler), handle it through the normal error flow. A bare `TimeoutError`
|
|
490
|
+
// here is the internal timeout above firing - anything else thrown inside the pipeline arrives wrapped.
|
|
491
|
+
const isPipelineError = error instanceof ContextPipelineInitializationError ||
|
|
492
|
+
error instanceof SessionError ||
|
|
493
|
+
error instanceof TimeoutError;
|
|
494
|
+
if (isPipelineError) {
|
|
495
|
+
const unwrappedError = this.unwrapError(error);
|
|
496
|
+
await this.requestFunctionErrorHandler(unwrappedError, crawlingContext, request, this.requestManager);
|
|
497
|
+
// SessionError already retired the session in `requestFunctionErrorHandler`;
|
|
498
|
+
// skip `markBad` to avoid double-counting usage/error score.
|
|
499
|
+
if (!this.errorAbsolvesSession(unwrappedError)) {
|
|
500
|
+
crawlingContext.session?.markBad();
|
|
501
|
+
}
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
throw this.unwrapError(error);
|
|
505
|
+
}
|
|
506
|
+
finally {
|
|
507
|
+
// Run request-scoped deferred cleanups only after the whole request lifecycle - including the user's error handler - has finished.
|
|
508
|
+
const deferredCleanup = crawlingContext[deferredCleanupKey] ?? [];
|
|
509
|
+
await Promise.all(deferredCleanup.map((fn) => fn().catch((cleanupError) => this.log.debug('Error in deferred cleanup', { error: cleanupError }))));
|
|
242
510
|
}
|
|
243
|
-
return context;
|
|
244
511
|
},
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
512
|
+
isTaskReadyFunction: async () => {
|
|
513
|
+
if (isMaxPagesExceeded()) {
|
|
514
|
+
this.logOncePerRun('shuttingDown', 'Crawler reached the maxRequestsPerCrawl limit of ' +
|
|
515
|
+
`${this.#maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`);
|
|
516
|
+
return false;
|
|
517
|
+
}
|
|
518
|
+
if (this.#unexpectedStop) {
|
|
519
|
+
this.logOncePerRun('shuttingDown', 'No new requests are allowed because the `stop()` method has been called. ' +
|
|
520
|
+
'Ongoing requests will be allowed to complete.');
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
return isTaskReadyFunction ? await isTaskReadyFunction() : await this.isTaskReadyFunction();
|
|
524
|
+
},
|
|
525
|
+
isFinishedFunction: async () => {
|
|
526
|
+
if (isMaxPagesExceeded()) {
|
|
527
|
+
this.log.info(`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${this.#maxRequestsPerCrawl} requests ` +
|
|
528
|
+
'and all requests that were in progress at that time have now finished. ' +
|
|
529
|
+
`In total, the crawler processed ${this.handledRequestsCount} requests and will shut down.`);
|
|
530
|
+
return true;
|
|
531
|
+
}
|
|
532
|
+
if (this.#unexpectedStop) {
|
|
533
|
+
this.log.info('The crawler has finished all the remaining ongoing requests and will shut down now.');
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
// `maybeFinish()` calls this only once nothing is in flight (`autoscaled_pool.ts`) - the point
|
|
537
|
+
// where a crawl that cannot progress becomes distinguishable from one that is merely waiting,
|
|
538
|
+
// and the only place where throwing does not abandon requests mid-processing.
|
|
539
|
+
const state = await this.requestManager?.checkReadiness();
|
|
540
|
+
// Under `keepAlive`, outliving a domain that will not let us through is the whole point.
|
|
541
|
+
if (state?.status === 'stalled' && !keepAlive) {
|
|
542
|
+
throw new PersistentRateLimitError(`Giving up: ${state.reason}`);
|
|
543
|
+
}
|
|
544
|
+
const isFinished = isFinishedFunction
|
|
545
|
+
? await isFinishedFunction()
|
|
546
|
+
: state === undefined || state.status === 'finished';
|
|
547
|
+
if (isFinished) {
|
|
548
|
+
const reason = isFinishedFunction
|
|
549
|
+
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
|
|
550
|
+
: 'All requests from the queue have been processed, the crawler will shut down.';
|
|
551
|
+
this.log.info(reason);
|
|
552
|
+
}
|
|
553
|
+
return isFinished;
|
|
554
|
+
},
|
|
555
|
+
log: this.log,
|
|
556
|
+
};
|
|
557
|
+
this.#taskLoopOptions = { ...taskLoopOptions, ...crawlerOwnedTaskLoopConfiguration };
|
|
558
|
+
this.#resolveConcurrencySystem = () => OwnedOrInjected.resolve(concurrencySystem, () => this.createDefaultConcurrencySystem({
|
|
559
|
+
minConcurrency,
|
|
560
|
+
maxConcurrency,
|
|
561
|
+
maxTasksPerMinute: maxRequestsPerMinute,
|
|
562
|
+
// Spread conditionally - an explicit `undefined` would clobber a subclass default, see
|
|
563
|
+
// `HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS`.
|
|
564
|
+
...(initialConcurrency !== undefined && { desiredConcurrency: initialConcurrency }),
|
|
565
|
+
log: this.log,
|
|
566
|
+
}));
|
|
254
567
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
this.requestQueue = requestQueue;
|
|
258
|
-
}
|
|
259
|
-
this.httpClient = httpClient ?? new GotScrapingHttpClient();
|
|
260
|
-
this.proxyConfiguration = proxyConfiguration;
|
|
261
|
-
this.log = log;
|
|
262
|
-
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
|
|
263
|
-
this.statusMessageCallback = statusMessageCallback;
|
|
264
|
-
this.events = config.getEventManager();
|
|
265
|
-
this.domainAccessedTime = new Map();
|
|
266
|
-
this.experiments = experiments;
|
|
267
|
-
this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });
|
|
268
|
-
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
|
|
269
|
-
this.requestHandler = requestHandler ?? this.router;
|
|
270
|
-
this.failedRequestHandler = failedRequestHandler;
|
|
271
|
-
this.errorHandler = errorHandler;
|
|
272
|
-
if (requestHandlerTimeoutSecs) {
|
|
273
|
-
this.requestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
568
|
+
finally {
|
|
569
|
+
serviceLocatorScope.exitScope();
|
|
274
570
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
|
|
574
|
+
* `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
575
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
|
|
576
|
+
*
|
|
577
|
+
* Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
|
|
578
|
+
* concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.
|
|
579
|
+
*/
|
|
580
|
+
createDefaultConcurrencySystem(options) {
|
|
581
|
+
return new ConcurrencySystem(options);
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Determines if the given HTTP status code is an error status code given
|
|
585
|
+
* the default behaviour and user-set preferences.
|
|
586
|
+
* @param status
|
|
587
|
+
* @returns `true` if the status code is considered an error, `false` otherwise
|
|
588
|
+
*/
|
|
589
|
+
isErrorStatusCode(status) {
|
|
590
|
+
const excludeError = this.#ignoreHttpErrorStatusCodes.has(status);
|
|
591
|
+
const includeError = this.additionalHttpErrorStatusCodes.has(status);
|
|
592
|
+
return (status >= 500 && !excludeError) || includeError;
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
596
|
+
* This handles base context creation, session resolution, and context helpers.
|
|
597
|
+
*/
|
|
598
|
+
buildBasicContextPipeline() {
|
|
599
|
+
return ContextPipeline.create()
|
|
600
|
+
.compose({ action: this.checkRobotsTxt.bind(this) })
|
|
601
|
+
.compose({ action: (context) => this.createBaseContext(context) })
|
|
602
|
+
.compose({ action: this.resolveSession.bind(this) })
|
|
603
|
+
.compose({ action: this.createContextHelpers.bind(this) });
|
|
604
|
+
}
|
|
605
|
+
async checkRobotsTxt({ request }) {
|
|
606
|
+
if (!(await this.isAllowedBasedOnRobotsTxtFile(request.url))) {
|
|
607
|
+
this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`);
|
|
608
|
+
request.state = RequestState.SKIPPED;
|
|
609
|
+
request.noRetry = true;
|
|
610
|
+
await this.#handleSkippedRequest({
|
|
611
|
+
request,
|
|
612
|
+
reason: 'robotsTxt',
|
|
613
|
+
});
|
|
614
|
+
throw new ContextPipelineInterruptedError(`Skipping request ${request.url} as disallowed by robots.txt`);
|
|
311
615
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
maxTasksPerMinute: maxRequestsPerMinute ?? autoscaledPoolOptions?.maxTasksPerMinute,
|
|
332
|
-
runTaskFunction: this._runTaskFunction.bind(this),
|
|
333
|
-
isTaskReadyFunction: async () => {
|
|
334
|
-
if (isMaxPagesExceeded()) {
|
|
335
|
-
if (this.shouldLogMaxProcessedRequestsExceeded) {
|
|
336
|
-
log.info('Crawler reached the maxRequestsPerCrawl limit of ' +
|
|
337
|
-
`${this.maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`);
|
|
338
|
-
this.shouldLogMaxProcessedRequestsExceeded = false;
|
|
339
|
-
}
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
return isTaskReadyFunction ? await isTaskReadyFunction() : await this._isTaskReadyFunction();
|
|
616
|
+
return {};
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
620
|
+
* Subclasses should override this to add their own pipeline stages.
|
|
621
|
+
*/
|
|
622
|
+
buildContextPipeline() {
|
|
623
|
+
return ContextPipeline.create();
|
|
624
|
+
}
|
|
625
|
+
createBaseContext(context) {
|
|
626
|
+
const deferredCleanup = [];
|
|
627
|
+
return {
|
|
628
|
+
id: cryptoRandomObjectId(10),
|
|
629
|
+
log: this.log,
|
|
630
|
+
pushData: this.pushData.bind(this),
|
|
631
|
+
useState: this.useState.bind(this),
|
|
632
|
+
getKeyValueStore: async (identifier) => KeyValueStore.open(identifier),
|
|
633
|
+
registerDeferredCleanup: (cleanup) => {
|
|
634
|
+
deferredCleanup.push(cleanup);
|
|
343
635
|
},
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
636
|
+
extendTimeout: (secs) => {
|
|
637
|
+
const extraMillis = secs * 1000;
|
|
638
|
+
// the current `addTimeoutToPromise` window (the request handler, or a navigation hook)...
|
|
639
|
+
extendTimeout(extraMillis);
|
|
640
|
+
// ...the internal timeout around the whole request, which is not an `addTimeoutToPromise` frame...
|
|
641
|
+
context[extendTimeoutKey]?.(extraMillis);
|
|
642
|
+
// ...and, when called from within the navigation phase, its shared window, so extending a hook
|
|
643
|
+
// extends the whole navigation budget rather than just that hook's step.
|
|
644
|
+
if (context[navigationDeadlineKey] !== undefined) {
|
|
645
|
+
context[navigationDeadlineKey] += extraMillis;
|
|
350
646
|
}
|
|
351
|
-
const isFinished = isFinishedFunction
|
|
352
|
-
? await isFinishedFunction()
|
|
353
|
-
: await this._defaultIsFinishedFunction();
|
|
354
|
-
if (isFinished) {
|
|
355
|
-
const reason = isFinishedFunction
|
|
356
|
-
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
|
|
357
|
-
: 'All requests from the queue have been processed, the crawler will shut down.';
|
|
358
|
-
log.info(reason);
|
|
359
|
-
}
|
|
360
|
-
return isFinished;
|
|
361
647
|
},
|
|
362
|
-
|
|
648
|
+
[deferredCleanupKey]: deferredCleanup,
|
|
363
649
|
};
|
|
364
|
-
|
|
650
|
+
}
|
|
651
|
+
async resolveRequest() {
|
|
652
|
+
const request = await this.timeoutAndRetry(this.fetchNextRequest.bind(this), this.internalTimeoutMillis, `Fetching next request timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
653
|
+
// Reset loadedUrl so an old one is not carried over to retries.
|
|
654
|
+
if (request) {
|
|
655
|
+
request.loadedUrl = undefined;
|
|
656
|
+
}
|
|
657
|
+
return request;
|
|
658
|
+
}
|
|
659
|
+
async resolveSession({ request }) {
|
|
660
|
+
const session = await this.timeoutAndRetry(async () => {
|
|
661
|
+
const existingSession = await this.sessionPool.getSession(request.sessionId);
|
|
662
|
+
if (!existingSession) {
|
|
663
|
+
throw new ContextPipelineInitializationError(new MissingSessionError(request.sessionId));
|
|
664
|
+
}
|
|
665
|
+
return existingSession;
|
|
666
|
+
}, this.internalTimeoutMillis, `Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
667
|
+
return { session, proxyInfo: session?.proxyInfo };
|
|
668
|
+
}
|
|
669
|
+
async createContextHelpers({ request, session }) {
|
|
670
|
+
const addRequests = async (requests, options = {}) => {
|
|
671
|
+
const newCrawlDepth = request.crawlDepth + 1;
|
|
672
|
+
const requestsGenerator = this.addCrawlDepthRequestGenerator(requests, newCrawlDepth);
|
|
673
|
+
return await this.addRequests(requestsGenerator, options);
|
|
674
|
+
};
|
|
675
|
+
const sendRequest = createSendRequest(this.httpClient, request, session);
|
|
676
|
+
return { addRequests, sendRequest };
|
|
677
|
+
}
|
|
678
|
+
buildFinalContextPipeline() {
|
|
679
|
+
const subclassPipeline = (this.#contextPipelineOptions.contextPipelineBuilder?.() ??
|
|
680
|
+
this.buildContextPipeline());
|
|
681
|
+
// `extendContext` runs *before* the subclass navigation pipeline (which includes the
|
|
682
|
+
// pre/post-navigation hooks). This makes the extension visible to those hooks and to the
|
|
683
|
+
// request handler alike. The trade-off is that `extendContext` cannot access
|
|
684
|
+
// navigation-dependent context members (e.g. `page`, `response`, `$`, `body`), as those
|
|
685
|
+
// don't exist yet at this point in the pipeline.
|
|
686
|
+
// The `extendContext` output (`ContextExtension`) is carried through the subclass pipeline at
|
|
687
|
+
// runtime (the pipeline copies each middleware's returned members onto the shared context), but
|
|
688
|
+
// TypeScript cannot express that `Context` transitively includes `ContextExtension` here. The
|
|
689
|
+
// casts below are sound because `buildFinalContextPipeline` is declared to return the fully
|
|
690
|
+
// resolved `ExtendedContext` (= `Context & ContextExtension`).
|
|
691
|
+
const { extendContext } = this.#contextPipelineOptions;
|
|
692
|
+
let contextPipeline;
|
|
693
|
+
if (extendContext !== undefined) {
|
|
694
|
+
contextPipeline = ContextPipeline.create()
|
|
695
|
+
.compose({ action: async (context) => await extendContext(context) })
|
|
696
|
+
.chain(subclassPipeline);
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
contextPipeline = subclassPipeline;
|
|
700
|
+
}
|
|
701
|
+
contextPipeline = contextPipeline.compose({
|
|
702
|
+
action: async (context) => {
|
|
703
|
+
const { request } = context;
|
|
704
|
+
if (request && !this.requestMatchesEnqueueStrategy(request)) {
|
|
705
|
+
// eslint-disable-next-line dot-notation
|
|
706
|
+
const message = `Skipping request ${request.id} (starting url: ${request.url} -> loaded url: ${request.loadedUrl}) because it does not match the enqueue strategy (${request['enqueueStrategy']}).`;
|
|
707
|
+
this.log.debug(message);
|
|
708
|
+
request.noRetry = true;
|
|
709
|
+
request.state = RequestState.SKIPPED;
|
|
710
|
+
await this.#handleSkippedRequest({ request, reason: 'redirect' });
|
|
711
|
+
throw new ContextPipelineInterruptedError(message);
|
|
712
|
+
}
|
|
713
|
+
return context;
|
|
714
|
+
},
|
|
715
|
+
});
|
|
716
|
+
return contextPipeline;
|
|
365
717
|
}
|
|
366
718
|
/**
|
|
367
719
|
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
|
|
@@ -370,59 +722,71 @@ export class BasicCrawler {
|
|
|
370
722
|
* @param error The error to check.
|
|
371
723
|
*/
|
|
372
724
|
isProxyError(error) {
|
|
373
|
-
return ROTATE_PROXY_ERRORS.some((x) => this.
|
|
725
|
+
return ROTATE_PROXY_ERRORS.some((x) => this.getMessageFromError(error)?.includes(x));
|
|
374
726
|
}
|
|
375
727
|
/**
|
|
728
|
+
* Sets the status message for the current crawler run.
|
|
729
|
+
*
|
|
376
730
|
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
|
|
731
|
+
*
|
|
732
|
+
* The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
|
|
733
|
+
* event. Integrations such as the Apify SDK subscribe to that event and forward the message to
|
|
734
|
+
* their status-reporting backend (e.g. the Apify platform).
|
|
377
735
|
*/
|
|
378
|
-
|
|
736
|
+
setStatusMessage(message, options = {}) {
|
|
379
737
|
const data = options.isStatusMessageTerminal != null ? { terminal: options.isStatusMessageTerminal } : undefined;
|
|
380
|
-
this.log.
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
738
|
+
this.log.logWithLevel(LogLevel[options.level ?? 'DEBUG'], message, data);
|
|
739
|
+
// Broadcast the status message through the event system. Consumers (e.g. the Apify SDK) can
|
|
740
|
+
// subscribe to `EventType.STATUS_MESSAGE` and propagate it to their status-reporting backend.
|
|
741
|
+
// Setting the status message is not a storage concern, so we intentionally don't route it
|
|
742
|
+
// through the storage client anymore.
|
|
743
|
+
serviceLocator.getEventManager().emit(EventType.STATUS_MESSAGE, {
|
|
744
|
+
crawlerId: this.#identity.id,
|
|
745
|
+
message,
|
|
746
|
+
isStatusMessageTerminal: options.isStatusMessageTerminal,
|
|
747
|
+
level: options.level,
|
|
748
|
+
});
|
|
387
749
|
}
|
|
388
750
|
getPeriodicLogger() {
|
|
389
|
-
let previousState = { ...this.
|
|
751
|
+
let previousState = { ...this.statistics.state };
|
|
390
752
|
const getOperationMode = () => {
|
|
391
|
-
const { requestsFailed } = this.
|
|
753
|
+
const { requestsFailed } = this.statistics.state;
|
|
392
754
|
const { requestsFailed: previousRequestsFailed } = previousState;
|
|
393
|
-
previousState = { ...this.
|
|
394
|
-
|
|
395
|
-
|
|
755
|
+
previousState = { ...this.statistics.state };
|
|
756
|
+
const failedDelta = requestsFailed - previousRequestsFailed;
|
|
757
|
+
if (failedDelta > 0) {
|
|
758
|
+
return { mode: 'ERROR', failedDelta };
|
|
396
759
|
}
|
|
397
|
-
return 'REGULAR';
|
|
760
|
+
return { mode: 'REGULAR', failedDelta: 0 };
|
|
398
761
|
};
|
|
399
762
|
const log = async () => {
|
|
400
|
-
const operationMode = getOperationMode();
|
|
763
|
+
const { mode: operationMode, failedDelta } = getOperationMode();
|
|
401
764
|
let message;
|
|
402
765
|
if (operationMode === 'ERROR') {
|
|
403
|
-
message = `Experiencing problems, ${
|
|
766
|
+
message = `Experiencing problems, ${failedDelta} failed requests in the past ${this.#statusMessageLoggingInterval} seconds.`;
|
|
404
767
|
}
|
|
405
768
|
else {
|
|
406
|
-
const total = this.requestManager?.getTotalCount();
|
|
407
|
-
message = `Crawled ${this.
|
|
769
|
+
const total = await this.requestManager?.getTotalCount();
|
|
770
|
+
message = `Crawled ${this.statistics.state.requestsFinished}${total ? `/${total}` : ''} pages, ${this.statistics.state.requestsFailed} failed requests, desired concurrency ${this.concurrencySystem?.desiredConcurrency ?? 0}.`;
|
|
408
771
|
}
|
|
409
|
-
if (this
|
|
410
|
-
await this
|
|
772
|
+
if (this.#statusMessageCallback) {
|
|
773
|
+
await this.#statusMessageCallback({
|
|
411
774
|
crawler: this,
|
|
412
|
-
state: this.
|
|
775
|
+
state: this.statistics.state,
|
|
413
776
|
previousState,
|
|
414
777
|
message,
|
|
415
778
|
});
|
|
416
779
|
return;
|
|
417
780
|
}
|
|
418
|
-
|
|
781
|
+
this.setStatusMessage(message);
|
|
419
782
|
};
|
|
420
|
-
const interval = setInterval(log, this
|
|
783
|
+
const interval = setInterval(log, this.#statusMessageLoggingInterval * 1e3);
|
|
421
784
|
return { log, stop: () => clearInterval(interval) };
|
|
422
785
|
}
|
|
423
786
|
/**
|
|
424
|
-
* Runs the crawler. Returns a promise that resolves once
|
|
425
|
-
*
|
|
787
|
+
* Runs the crawler. Returns a promise that resolves once every request has been processed and the crawler's
|
|
788
|
+
* finished-check ({@link BasicCrawlerOptions.taskLoopOptions|`taskLoopOptions.isFinishedFunction`}, or the
|
|
789
|
+
* default "the request manager is empty") reports that the crawl is over.
|
|
426
790
|
*
|
|
427
791
|
* We can use the `requests` parameter to enqueue the initial requests — it is a shortcut for
|
|
428
792
|
* running {@link BasicCrawler.addRequests|`crawler.addRequests()`} before {@link BasicCrawler.run|`crawler.run()`}.
|
|
@@ -434,76 +798,96 @@ export class BasicCrawler {
|
|
|
434
798
|
if (this.running) {
|
|
435
799
|
throw new Error('This crawler instance is already running, you can add more requests to it via `crawler.addRequests()`.');
|
|
436
800
|
}
|
|
437
|
-
const { purgeRequestQueue
|
|
801
|
+
const { purgeRequestQueue, ...addRequestsOptions } = options ?? {};
|
|
438
802
|
if (this.hasFinishedBefore) {
|
|
439
803
|
// When executing the run method for the second time explicitly,
|
|
440
|
-
// we need to purge the
|
|
804
|
+
// we need to purge the RQ to allow processing the same requests again — this is important so users can
|
|
441
805
|
// pass in failed requests back to the `crawler.run()`, otherwise they would be considered as handled and
|
|
442
|
-
// ignored
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
806
|
+
// ignored — as a failed request is still handled.
|
|
807
|
+
// `purgeRequestQueue` unset purges only storage the crawler opened itself (see `#purgeableExtent`);
|
|
808
|
+
// `true` also purges a caller-supplied manager, `false` purges nothing.
|
|
809
|
+
if (purgeRequestQueue === undefined && this.#purgeableExtent === 'ambiguous') {
|
|
810
|
+
throw new Error('Cannot decide what to purge before running again: `sameDomainDelaySecs` paces the request ' +
|
|
811
|
+
'manager you supplied, so the per-domain queues that have to be emptied are the ' +
|
|
812
|
+
"crawler's while the manager underneath them is yours. Say which you want: " +
|
|
813
|
+
'`run(requests, { purgeRequestQueue: true })` empties both, `false` empties neither.');
|
|
449
814
|
}
|
|
450
|
-
this
|
|
451
|
-
|
|
452
|
-
|
|
815
|
+
if (purgeRequestQueue !== false && (this.#purgeableExtent === 'all' || purgeRequestQueue === true)) {
|
|
816
|
+
// One call from the outside in reaches everything the manager wraps, a pacer's per-domain queues
|
|
817
|
+
// included.
|
|
818
|
+
await this.requestManager?.purge?.();
|
|
819
|
+
}
|
|
820
|
+
// A supplied statistics instance keeps whatever state it was handed - only wipe a default we built.
|
|
821
|
+
await this.#statisticsDep.ifOwned(async (stats) => {
|
|
822
|
+
stats.reset();
|
|
823
|
+
await stats.resetStore();
|
|
824
|
+
});
|
|
825
|
+
await this.#sessionPoolDep.ifOwned((pool) => pool.resetStore());
|
|
453
826
|
}
|
|
827
|
+
this.#unexpectedStop = false;
|
|
454
828
|
this.running = true;
|
|
455
|
-
this.
|
|
456
|
-
this.shouldLogMaxEnqueuedRequestsExceeded = true;
|
|
829
|
+
this.#loggedPerRun.clear();
|
|
457
830
|
await purgeDefaultStorages({
|
|
458
831
|
onlyPurgeOnce: true,
|
|
459
|
-
|
|
460
|
-
|
|
832
|
+
storageBackend: serviceLocator.getStorageBackend(),
|
|
833
|
+
configuration: serviceLocator.getConfiguration(),
|
|
461
834
|
});
|
|
462
835
|
if (requests) {
|
|
463
836
|
await this.addRequests(requests, addRequestsOptions);
|
|
464
837
|
}
|
|
465
|
-
|
|
466
|
-
|
|
838
|
+
try {
|
|
839
|
+
await this.init();
|
|
840
|
+
await this.statistics.startCapturing();
|
|
841
|
+
}
|
|
842
|
+
catch (error) {
|
|
843
|
+
// Clean up here before propagating, otherwise a failed startup would leave the process hanging.
|
|
844
|
+
await this.teardown().catch((teardownError) => {
|
|
845
|
+
this.log.exception(teardownError, 'Cleaning up after a failed crawler startup failed.');
|
|
846
|
+
});
|
|
847
|
+
// The run never began, so let the instance be run again instead of leaving it wedged as `running`.
|
|
848
|
+
this.running = false;
|
|
849
|
+
throw error;
|
|
850
|
+
}
|
|
467
851
|
const periodicLogger = this.getPeriodicLogger();
|
|
468
|
-
|
|
469
|
-
void this.setStatusMessage('Starting the crawler.', { level: 'INFO' });
|
|
852
|
+
this.setStatusMessage('Starting the crawler.', { level: 'INFO' });
|
|
470
853
|
const sigintHandler = async () => {
|
|
471
854
|
this.log.warning('Pausing... Press CTRL+C again to force exit. To resume, do: CRAWLEE_PURGE_ON_START=0 npm start');
|
|
472
|
-
await this.
|
|
473
|
-
await this
|
|
855
|
+
await this.pauseOnMigration();
|
|
856
|
+
await this.#autoscaledPool.abort();
|
|
474
857
|
};
|
|
475
858
|
// Attach a listener to handle migration and aborting events gracefully.
|
|
476
|
-
const boundPauseOnMigration = this.
|
|
859
|
+
const boundPauseOnMigration = this.pauseOnMigration.bind(this);
|
|
477
860
|
process.once('SIGINT', sigintHandler);
|
|
478
|
-
|
|
479
|
-
|
|
861
|
+
const eventManager = serviceLocator.getEventManager();
|
|
862
|
+
eventManager.on(EventType.MIGRATING, boundPauseOnMigration);
|
|
863
|
+
eventManager.on(EventType.ABORTING, boundPauseOnMigration);
|
|
480
864
|
let stats = {};
|
|
481
865
|
try {
|
|
482
|
-
await this
|
|
866
|
+
await this.#autoscaledPool.run();
|
|
483
867
|
}
|
|
484
868
|
finally {
|
|
869
|
+
await this.statistics.stopCapturing();
|
|
485
870
|
await this.teardown();
|
|
486
|
-
await this.stats.stopCapturing();
|
|
487
871
|
process.off('SIGINT', sigintHandler);
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
const finalStats = this.
|
|
872
|
+
eventManager.off(EventType.MIGRATING, boundPauseOnMigration);
|
|
873
|
+
eventManager.off(EventType.ABORTING, boundPauseOnMigration);
|
|
874
|
+
const finalStats = this.statistics.calculate();
|
|
491
875
|
stats = {
|
|
492
|
-
requestsFinished: this.
|
|
493
|
-
requestsFailed: this.
|
|
494
|
-
retryHistogram: this.
|
|
876
|
+
requestsFinished: this.statistics.state.requestsFinished,
|
|
877
|
+
requestsFailed: this.statistics.state.requestsFailed,
|
|
878
|
+
retryHistogram: this.statistics.requestRetryHistogram,
|
|
495
879
|
...finalStats,
|
|
496
880
|
};
|
|
497
881
|
this.log.info('Final request statistics:', stats);
|
|
498
|
-
if (this.
|
|
882
|
+
if (this.statistics.errorTracker.total !== 0) {
|
|
499
883
|
const prettify = ([count, info]) => `${count}x: ${info.at(-1).trim()} (${info[0]})`;
|
|
500
884
|
this.log.info(`Error analysis:`, {
|
|
501
|
-
totalErrors: this.
|
|
502
|
-
uniqueErrors: this.
|
|
503
|
-
mostCommonErrors: this.
|
|
885
|
+
totalErrors: this.statistics.errorTracker.total,
|
|
886
|
+
uniqueErrors: this.statistics.errorTracker.getUniqueErrorCount(),
|
|
887
|
+
mostCommonErrors: this.statistics.errorTracker.getMostPopularErrors(3).map(prettify),
|
|
504
888
|
});
|
|
505
889
|
}
|
|
506
|
-
const client =
|
|
890
|
+
const client = serviceLocator.getStorageBackend();
|
|
507
891
|
if (client.teardown) {
|
|
508
892
|
let finished = false;
|
|
509
893
|
setTimeout(() => {
|
|
@@ -515,8 +899,7 @@ export class BasicCrawler {
|
|
|
515
899
|
finished = true;
|
|
516
900
|
}
|
|
517
901
|
periodicLogger.stop();
|
|
518
|
-
|
|
519
|
-
void this.setStatusMessage(`Finished! Total ${this.stats.state.requestsFinished + this.stats.state.requestsFailed} requests: ${this.stats.state.requestsFinished} succeeded, ${this.stats.state.requestsFailed} failed.`, { isStatusMessageTerminal: true, level: 'INFO' });
|
|
902
|
+
this.setStatusMessage(`Finished! Total ${this.statistics.state.requestsFinished + this.statistics.state.requestsFailed} requests: ${this.statistics.state.requestsFinished} succeeded, ${this.statistics.state.requestsFailed} failed.`, { isStatusMessageTerminal: true, level: 'INFO' });
|
|
520
903
|
this.running = false;
|
|
521
904
|
this.hasFinishedBefore = true;
|
|
522
905
|
}
|
|
@@ -529,60 +912,160 @@ export class BasicCrawler {
|
|
|
529
912
|
*
|
|
530
913
|
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
531
914
|
*/
|
|
532
|
-
stop(
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
.then(() => this.log.info(message))
|
|
539
|
-
.catch((err) => {
|
|
540
|
-
this.log.error('An error occurred when stopping the crawler:', err);
|
|
541
|
-
});
|
|
915
|
+
stop(reason = 'The crawler has been gracefully stopped.') {
|
|
916
|
+
if (this.#unexpectedStop) {
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
this.log.info(reason);
|
|
920
|
+
this.#unexpectedStop = true;
|
|
542
921
|
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
922
|
+
/**
|
|
923
|
+
* Stops dispatching new requests, letting the in-progress ones finish. Resolves once they have settled, or rejects
|
|
924
|
+
* after `timeoutSecs` if they take too long. Unlike {@link BasicCrawler.stop|`stop()`}, this does not end the
|
|
925
|
+
* run — {@link BasicCrawler.run|`run()`} stays pending until {@link BasicCrawler.resume|`resume()`}.
|
|
926
|
+
*
|
|
927
|
+
* > *NOTE:* The {@link BasicCrawler.concurrencySystem|concurrency system} keeps monitoring and autoscaling
|
|
928
|
+
* throughout, since a shared one may still be serving other crawlers.
|
|
929
|
+
*/
|
|
930
|
+
async pause(timeoutSecs) {
|
|
931
|
+
if (!this.#autoscaledPool) {
|
|
932
|
+
this.log.warning('Cannot pause a crawler that is not running.');
|
|
933
|
+
return;
|
|
546
934
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
935
|
+
await this.#autoscaledPool.pause(timeoutSecs);
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Resumes a run suspended with {@link BasicCrawler.pause|`pause()`}, letting the crawler dispatch requests
|
|
939
|
+
* again. A no-op on a crawler that is not paused.
|
|
940
|
+
*/
|
|
941
|
+
resume() {
|
|
942
|
+
if (!this.#autoscaledPool) {
|
|
943
|
+
this.log.warning('Cannot resume a crawler that is not running.');
|
|
944
|
+
return;
|
|
550
945
|
}
|
|
946
|
+
this.#autoscaledPool.resume();
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
|
|
950
|
+
* if none has been configured or opened yet.
|
|
951
|
+
*/
|
|
952
|
+
async getRequestManager() {
|
|
551
953
|
if (!this.requestManager) {
|
|
552
|
-
this.requestManager =
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
954
|
+
this.requestManager = await this.openOwnedRequestQueue();
|
|
955
|
+
}
|
|
956
|
+
// Apply the processing-time hint here (an async lifecycle point) rather than in the constructor,
|
|
957
|
+
// now that `setExpectedRequestProcessingTimeSecs` is async. The hint is raise-only and idempotent,
|
|
958
|
+
// but guard so we do not re-issue it on every call.
|
|
959
|
+
if (!this.#requestManagerTimeoutsApplied) {
|
|
960
|
+
this.#requestManagerTimeoutsApplied = true;
|
|
961
|
+
await this.applyRequestManagerTimeouts(this.requestManager);
|
|
962
|
+
}
|
|
963
|
+
return this.requestManager;
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
|
|
967
|
+
* crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
|
|
968
|
+
*/
|
|
969
|
+
async getRequestQueue() {
|
|
970
|
+
return this.getRequestManager();
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Opens the default {@link RequestQueue} — the crawler's own, read from when the caller supplied nothing.
|
|
974
|
+
* @private
|
|
975
|
+
*/
|
|
976
|
+
async openOwnedRequestQueue() {
|
|
977
|
+
// The first crawler instance uses the default queue (null identifier);
|
|
978
|
+
// subsequent instances get their own queue via a unique alias so they don't collide.
|
|
979
|
+
const identifier = this.#identity.instanceIndex === 0 ? null : { alias: `__default_${this.#identity.id}__` };
|
|
980
|
+
return RequestQueue.open(identifier, { configuration: serviceLocator.getConfiguration() });
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Tells a request manager how long we expect to hold a fetched request, so that one backed by a
|
|
984
|
+
* locking storage backend keeps it reserved for slightly longer than the request handler timeout
|
|
985
|
+
* (with some padding for overhead), but never for less than a minute. This prevents a long-running
|
|
986
|
+
* request from being handed out a second time while it is still being processed — and it works
|
|
987
|
+
* regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
|
|
988
|
+
*/
|
|
989
|
+
async applyRequestManagerTimeouts(requestManager) {
|
|
990
|
+
// A router route may hold a request for longer than the crawler's own timeout, and we cannot know
|
|
991
|
+
// which routes a run will hit, so reserve for the longest one any route asked for. The hint is
|
|
992
|
+
// raise-only, so erring high here is safe.
|
|
993
|
+
const maxRouteTimeoutSecs = this.requestHandler.getMaxTimeoutSecs?.() ?? 0;
|
|
994
|
+
const handlerTimeoutSecs = Math.max(this.#requestHandlerTimeoutMillis / 1000, maxRouteTimeoutSecs);
|
|
995
|
+
await requestManager.setExpectedRequestProcessingTimeSecs?.(Math.max(handlerTimeoutSecs + 5, 60));
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
|
|
999
|
+
* for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
|
|
1000
|
+
* mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
|
|
1001
|
+
* the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
|
|
1002
|
+
* `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
|
|
1003
|
+
*/
|
|
1004
|
+
async validateRequestUserData(source) {
|
|
1005
|
+
if (typeof source === 'string') {
|
|
1006
|
+
return;
|
|
556
1007
|
}
|
|
557
|
-
|
|
1008
|
+
const getSchema = this.requestHandler.getSchema;
|
|
1009
|
+
if (typeof getSchema !== 'function') {
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
// Resolve the label via its public accessors only — the top-level `label` of a `RequestOptions` or the
|
|
1013
|
+
// `Request.label` getter — rather than reaching into `userData`, where the request happens to store it.
|
|
1014
|
+
const target = source;
|
|
1015
|
+
const schema = getSchema(target.label);
|
|
1016
|
+
if (!schema) {
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
// Store the parsed value rather than the raw input, so the queue holds the same coerced `userData` the
|
|
1020
|
+
// handler will see. Assigning through a `Request` instance's setter keeps its internal `__crawlee` meta.
|
|
1021
|
+
target.userData = await validateUserData(target.label, schema, target.userData ?? {});
|
|
558
1022
|
}
|
|
559
1023
|
async useState(defaultValue = {}) {
|
|
560
|
-
const kvs = await KeyValueStore.open(null, {
|
|
561
|
-
|
|
1024
|
+
const kvs = await KeyValueStore.open(null, { configuration: serviceLocator.getConfiguration() });
|
|
1025
|
+
if (this.#identity.hasExplicitId) {
|
|
1026
|
+
const stateKey = `${BasicCrawler.#CRAWLEE_STATE_KEY}_${this.#identity.id}`;
|
|
1027
|
+
return kvs.getAutoSavedValue(stateKey, defaultValue);
|
|
1028
|
+
}
|
|
1029
|
+
BasicCrawler.#useStateAnonymousIndices.add(this.#identity.instanceIndex);
|
|
1030
|
+
if (BasicCrawler.#useStateAnonymousIndices.size > 1) {
|
|
1031
|
+
serviceLocator
|
|
1032
|
+
.getLogger()
|
|
1033
|
+
.warningOnce('Multiple crawler instances are calling useState() without an explicit `id` option. \n' +
|
|
1034
|
+
'This means they will share the same state object, which is likely unintended. \n' +
|
|
1035
|
+
'To fix this, provide a unique `id` option to each crawler instance. \n' +
|
|
1036
|
+
'Example: new BasicCrawler({ id: "my-crawler-1", ... })');
|
|
1037
|
+
}
|
|
1038
|
+
return kvs.getAutoSavedValue(BasicCrawler.#CRAWLEE_STATE_KEY, defaultValue);
|
|
562
1039
|
}
|
|
563
|
-
|
|
564
|
-
return this.requestManager?.getPendingCount() ?? 0;
|
|
1040
|
+
async #getPendingRequestCountApproximation() {
|
|
1041
|
+
return (await this.requestManager?.getPendingCount()) ?? 0;
|
|
565
1042
|
}
|
|
566
|
-
calculateEnqueuedRequestLimit(explicitLimit) {
|
|
567
|
-
if (this
|
|
1043
|
+
async #calculateEnqueuedRequestLimit(explicitLimit) {
|
|
1044
|
+
if (this.#maxRequestsPerCrawl === undefined) {
|
|
568
1045
|
return explicitLimit;
|
|
569
1046
|
}
|
|
570
|
-
const limit = Math.max(0, this
|
|
1047
|
+
const limit = Math.max(0, this.#maxRequestsPerCrawl - this.handledRequestsCount - (await this.#getPendingRequestCountApproximation()));
|
|
571
1048
|
return Math.min(limit, explicitLimit ?? Infinity);
|
|
572
1049
|
}
|
|
573
|
-
async handleSkippedRequest(options) {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
const enqueuedRequestLimit = this.calculateEnqueuedRequestLimit();
|
|
581
|
-
if (enqueuedRequestLimit === undefined || enqueuedRequestLimit !== 0) {
|
|
582
|
-
this.log.info('The number of requests enqueued by the crawler reached the enqueueLinks limit.');
|
|
1050
|
+
async #handleSkippedRequest(options) {
|
|
1051
|
+
// A skipped request is a *successful* outcome, but the interrupt still unwinds through the
|
|
1052
|
+
// transaction scope, which rolls back - so the skip bookkeeping must write directly.
|
|
1053
|
+
await withDirectStorageAccess(async () => {
|
|
1054
|
+
if (options.reason === 'limit') {
|
|
1055
|
+
this.logOncePerRun('maxRequestsPerCrawl', 'The number of requests enqueued by the crawler reached the maxRequestsPerCrawl limit of ' +
|
|
1056
|
+
`${this.#maxRequestsPerCrawl} requests and no further requests will be added.`);
|
|
583
1057
|
}
|
|
1058
|
+
if (options.reason === 'depth') {
|
|
1059
|
+
this.logOncePerRun('maxCrawlDepth', `The crawler reached the maxCrawlDepth limit of ${this.#maxCrawlDepth} and no further requests will be enqueued.`);
|
|
1060
|
+
}
|
|
1061
|
+
await this.#onSkippedRequest?.(options);
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
logOncePerRun(key, message, level = 'info') {
|
|
1065
|
+
if (!this.#loggedPerRun.has(key)) {
|
|
1066
|
+
this.log[level](message);
|
|
1067
|
+
this.#loggedPerRun.add(key);
|
|
584
1068
|
}
|
|
585
|
-
await this.onSkippedRequest?.(options);
|
|
586
1069
|
}
|
|
587
1070
|
/**
|
|
588
1071
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
@@ -590,76 +1073,134 @@ export class BasicCrawler {
|
|
|
590
1073
|
* the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
|
|
591
1074
|
* the `waitForAllRequestsToBeAdded` promise you get in the response object.
|
|
592
1075
|
*
|
|
1076
|
+
* Optionally, the requests can be filtered using `include`/`exclude` glob or regexp patterns and an
|
|
1077
|
+
* enqueue `strategy` (both AND-ed together, same as {@link CrawlingContext.enqueueLinks|`enqueueLinks`}),
|
|
1078
|
+
* relative to `baseUrl`. Unlike `enqueueLinks`, there is no implicit "current page" to anchor the strategy
|
|
1079
|
+
* to, so `strategy` defaults to {@link EnqueueStrategy.All|`all`} here.
|
|
1080
|
+
*
|
|
593
1081
|
* This is an alias for calling `addRequestsBatched()` on the implicit `RequestQueue` for this crawler instance.
|
|
594
1082
|
*
|
|
595
1083
|
* @param requests The requests to add
|
|
596
1084
|
* @param options Options for the request queue
|
|
597
1085
|
*/
|
|
598
1086
|
async addRequests(requests, options = {}) {
|
|
599
|
-
await this.
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
1087
|
+
await this.getRequestManager();
|
|
1088
|
+
if (!isIterable(requests) && !isAsyncIterable(requests)) {
|
|
1089
|
+
throw new Error(`Expected an iterable or async iterable, got ${getObjectType(requests)}`);
|
|
1090
|
+
}
|
|
1091
|
+
parseArgument(options, addRequestsOptionsSchema, 'EnqueueUrlsOptions');
|
|
1092
|
+
// `label`/`userData` apply to every request this call produces, so a single upfront validation
|
|
1093
|
+
// against the label's schema covers them all and fails the whole call fast, rather than failing
|
|
1094
|
+
// lazily once the generator below is drained. Skipped when neither is set - each item still gets
|
|
1095
|
+
// its own per-item validation below, and validating an absent label/userData here would spuriously
|
|
1096
|
+
// check them against a registered default-route schema.
|
|
1097
|
+
if (options.label !== undefined || options.userData !== undefined) {
|
|
1098
|
+
await this.validateRequestUserData({ label: options.label, userData: options.userData });
|
|
1099
|
+
}
|
|
1100
|
+
const requestLimit = await this.#calculateEnqueuedRequestLimit(options.limit);
|
|
1101
|
+
const strategy = options.strategy ?? EnqueueStrategy.All;
|
|
1102
|
+
const urlExcludePatternObjects = options.exclude?.length
|
|
1103
|
+
? constructUrlPatternObjects(options.exclude)
|
|
1104
|
+
: [];
|
|
1105
|
+
const urlPatternObjects = options.include?.length
|
|
1106
|
+
? constructUrlPatternObjects(options.include)
|
|
1107
|
+
: [];
|
|
1108
|
+
// The strategy always applies, even when `include` patterns are provided - the two are AND-ed together
|
|
1109
|
+
// (a URL must match an `include` pattern *and* satisfy the strategy). This mirrors crawlee-python.
|
|
1110
|
+
const enqueueStrategyPatterns = options.baseUrl
|
|
1111
|
+
? buildEnqueueStrategyPatterns(options.baseUrl, strategy)
|
|
1112
|
+
: [];
|
|
604
1113
|
const isAllowedBasedOnRobotsTxtFile = this.isAllowedBasedOnRobotsTxtFile.bind(this);
|
|
605
|
-
const maxCrawlDepth = this
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
1114
|
+
const maxCrawlDepth = this.#maxCrawlDepth;
|
|
1115
|
+
const validateRequestUserData = this.validateRequestUserData.bind(this);
|
|
1116
|
+
const allSkipped = [];
|
|
1117
|
+
// A skipped source (which can carry arbitrary userData) is only retained if something reads it -
|
|
1118
|
+
// otherwise the URL alone is enough to build the callback argument and to log with.
|
|
1119
|
+
const hasSkippedRequestCallback = this.#onSkippedRequest !== undefined || options.onSkippedRequest !== undefined;
|
|
1120
|
+
const keepSkippedSource = (source) => (hasSkippedRequestCallback ? source : source.url);
|
|
609
1121
|
async function* filteredRequests() {
|
|
610
|
-
let yieldedRequestCount = 0;
|
|
611
1122
|
for await (const request of requests) {
|
|
612
|
-
const
|
|
613
|
-
if (
|
|
614
|
-
|
|
1123
|
+
const [requestOptions] = createRequestOptions([typeof request === 'string' ? request : request], { ...options, strategy });
|
|
1124
|
+
if (!requestOptions) {
|
|
1125
|
+
continue; // invalid URL, silently dropped (matches `createRequestOptions`'s own filtering)
|
|
1126
|
+
}
|
|
1127
|
+
if (maxCrawlDepth !== undefined && requestOptions.crawlDepth > maxCrawlDepth) {
|
|
1128
|
+
allSkipped.push({ source: keepSkippedSource(requestOptions), reason: 'depth' });
|
|
615
1129
|
continue;
|
|
616
1130
|
}
|
|
617
|
-
if (
|
|
618
|
-
|
|
1131
|
+
if (!(await isAllowedBasedOnRobotsTxtFile(requestOptions.url))) {
|
|
1132
|
+
allSkipped.push({ source: keepSkippedSource(requestOptions), reason: 'robotsTxt' });
|
|
619
1133
|
continue;
|
|
620
1134
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
1135
|
+
const onSkippedByFilter = (opts) => allSkipped.push({ source: keepSkippedSource(opts), reason: 'filters' });
|
|
1136
|
+
// Filter by user patterns first (with exclude)...
|
|
1137
|
+
let filtered = filterRequestOptionsByPatterns([requestOptions], urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, strategy, onSkippedByFilter);
|
|
1138
|
+
// ...then filter by the enqueue strategy (making this an AND check)
|
|
1139
|
+
filtered = filterRequestOptionsByPatterns(filtered, enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined, [], strategy, onSkippedByFilter);
|
|
1140
|
+
if (filtered.length === 0) {
|
|
1141
|
+
continue;
|
|
624
1142
|
}
|
|
625
|
-
|
|
626
|
-
|
|
1143
|
+
let [finalOptions] = filtered;
|
|
1144
|
+
if (options.transformRequestFunction) {
|
|
1145
|
+
const transformed = applyRequestTransform([finalOptions], options.transformRequestFunction, (r) => allSkipped.push({ source: keepSkippedSource(r), reason: r.skippedReason ?? 'transform' }));
|
|
1146
|
+
if (transformed.length === 0) {
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
[finalOptions] = transformed;
|
|
627
1150
|
}
|
|
1151
|
+
await validateRequestUserData(finalOptions);
|
|
1152
|
+
yield new Request(finalOptions);
|
|
628
1153
|
}
|
|
629
1154
|
}
|
|
630
|
-
const result = await this.requestManager.addRequestsBatched(filteredRequests(),
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
1155
|
+
const result = await this.requestManager.addRequestsBatched(filteredRequests(), {
|
|
1156
|
+
forefront: options.forefront,
|
|
1157
|
+
waitForAllRequestsToBeAdded: options.waitForAllRequestsToBeAdded,
|
|
1158
|
+
batchSize: options.batchSize,
|
|
1159
|
+
waitBetweenBatchesMillis: options.waitBetweenBatchesMillis,
|
|
1160
|
+
maxNewRequests: requestLimit,
|
|
1161
|
+
});
|
|
1162
|
+
// Report requests skipped due to the maxNewRequests budget (i.e. maxRequestsPerCrawl limit, or an
|
|
1163
|
+
// explicit `limit` option)
|
|
1164
|
+
for (const request of result.requestsOverLimit ?? []) {
|
|
1165
|
+
allSkipped.push({ source: request, reason: 'limit' });
|
|
1166
|
+
}
|
|
1167
|
+
if (allSkipped.length > 0) {
|
|
1168
|
+
const skippedRobotsUrls = allSkipped
|
|
1169
|
+
.filter((s) => s.reason === 'robotsTxt')
|
|
1170
|
+
.map(({ source }) => (typeof source === 'string' ? source : source.url));
|
|
1171
|
+
if (skippedRobotsUrls.length > 0) {
|
|
1172
|
+
this.log.warning(`Some requests were skipped because they were disallowed based on the robots.txt file`, { skipped: skippedRobotsUrls });
|
|
1173
|
+
}
|
|
1174
|
+
// Only log the limit message when an explicit `limit` was passed (not the internal
|
|
1175
|
+
// `maxRequestsPerCrawl`-derived one), and only once per call.
|
|
1176
|
+
if (options.limit !== undefined && allSkipped.some((s) => s.reason === 'limit')) {
|
|
1177
|
+
this.log.info(requestLimit === options.limit
|
|
1178
|
+
? `Skipping requests in this call due to the enqueueLinks limit of ${options.limit}.`
|
|
1179
|
+
: `Skipping requests in this call due to the remaining maxRequestsPerCrawl budget of ${requestLimit}, which is lower than the enqueueLinks limit of ${options.limit}.`);
|
|
1180
|
+
}
|
|
1181
|
+
await Promise.all(allSkipped.map(async ({ source, reason }) => {
|
|
1182
|
+
const args = createSkippedRequestArgs(source, reason);
|
|
1183
|
+
await this.#handleSkippedRequest(args);
|
|
1184
|
+
await options.onSkippedRequest?.(args);
|
|
1185
|
+
}));
|
|
648
1186
|
}
|
|
649
1187
|
return result;
|
|
650
1188
|
}
|
|
651
1189
|
/**
|
|
652
1190
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
653
1191
|
*/
|
|
654
|
-
async pushData(data,
|
|
655
|
-
|
|
1192
|
+
async pushData(data, datasetIdentifier) {
|
|
1193
|
+
tryCancel();
|
|
1194
|
+
const dataset = await this.getDataset(datasetIdentifier);
|
|
656
1195
|
return dataset.pushData(data);
|
|
657
1196
|
}
|
|
658
1197
|
/**
|
|
659
1198
|
* Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
|
|
660
1199
|
*/
|
|
661
|
-
async getDataset(
|
|
662
|
-
return Dataset.open(
|
|
1200
|
+
async getDataset(identifier) {
|
|
1201
|
+
return Dataset.open(identifier, {
|
|
1202
|
+
configuration: serviceLocator.getConfiguration(),
|
|
1203
|
+
});
|
|
663
1204
|
}
|
|
664
1205
|
/**
|
|
665
1206
|
* Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
|
|
@@ -674,8 +1215,9 @@ export class BasicCrawler {
|
|
|
674
1215
|
*/
|
|
675
1216
|
async exportData(path, format, options) {
|
|
676
1217
|
const supportedFormats = ['json', 'csv'];
|
|
677
|
-
|
|
678
|
-
|
|
1218
|
+
const formatMatch = /\.(json|csv)$/i.exec(path);
|
|
1219
|
+
if (!format && formatMatch) {
|
|
1220
|
+
format = formatMatch[1].toLowerCase();
|
|
679
1221
|
}
|
|
680
1222
|
if (!format) {
|
|
681
1223
|
throw new Error(`Failed to infer format from the path: '${path}'. Supported formats: ${supportedFormats.join(', ')}`);
|
|
@@ -694,6 +1236,7 @@ export class BasicCrawler {
|
|
|
694
1236
|
const keys = options?.collectAllKeys
|
|
695
1237
|
? Array.from(new Set(items.flatMap(Object.keys)))
|
|
696
1238
|
: Object.keys(items[0]);
|
|
1239
|
+
const { stringify } = await import('csv-stringify/sync');
|
|
697
1240
|
value = stringify([
|
|
698
1241
|
keys,
|
|
699
1242
|
...items.map((item) => {
|
|
@@ -701,13 +1244,13 @@ export class BasicCrawler {
|
|
|
701
1244
|
}),
|
|
702
1245
|
]);
|
|
703
1246
|
}
|
|
704
|
-
await
|
|
1247
|
+
await mkdir(dirname(path), { recursive: true });
|
|
705
1248
|
await writeFile(path, value);
|
|
706
1249
|
this.log.info(`Export to ${path} finished!`);
|
|
707
1250
|
}
|
|
708
1251
|
if (format === 'json') {
|
|
709
|
-
await
|
|
710
|
-
await
|
|
1252
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1253
|
+
await writeFile(path, `${JSON.stringify(items, null, 4)}\n`);
|
|
711
1254
|
this.log.info(`Export to ${path} finished!`);
|
|
712
1255
|
}
|
|
713
1256
|
return items;
|
|
@@ -715,57 +1258,190 @@ export class BasicCrawler {
|
|
|
715
1258
|
/**
|
|
716
1259
|
* Initializes the crawler.
|
|
717
1260
|
*/
|
|
718
|
-
async
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
//
|
|
725
|
-
//
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
this.
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
1261
|
+
async init() {
|
|
1262
|
+
const eventManager = serviceLocator.getEventManager();
|
|
1263
|
+
if (!eventManager.isInitialized()) {
|
|
1264
|
+
await eventManager.init();
|
|
1265
|
+
this.#closeEvents = true;
|
|
1266
|
+
}
|
|
1267
|
+
// Warn once at startup if the internal timeout is shorter than the phases it is meant to outlast. It is
|
|
1268
|
+
// floored per request so it will not actually cut them short, but the configured value is then effectively
|
|
1269
|
+
// ignored, which is worth flagging. Checked here (not in the constructor) because a subclass sets its
|
|
1270
|
+
// navigation timeout only after `super()`.
|
|
1271
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.resolveRequestHandlerTimeoutMillis(undefined);
|
|
1272
|
+
if (this.internalTimeoutMillis < phasesMillis) {
|
|
1273
|
+
this.log.warning(`CRAWLEE_INTERNAL_TIMEOUT (${this.internalTimeoutMillis / 1000}s) is shorter than the navigation ` +
|
|
1274
|
+
`and request handler timeouts combined (${phasesMillis / 1000}s); it will be raised per request ` +
|
|
1275
|
+
`so it does not cut them short.`);
|
|
1276
|
+
}
|
|
1277
|
+
// An owned governor is rebuilt (and started) for every run, so it always starts from a clean slate — stale
|
|
1278
|
+
// resource snapshots or a previous run's scaled desired concurrency would otherwise distort this run's
|
|
1279
|
+
// scaling. An injected one is long-lived and its lifecycle belongs to the caller.
|
|
1280
|
+
this.#concurrencySystemDep = this.#resolveConcurrencySystem();
|
|
1281
|
+
await this.#concurrencySystemDep.ifOwned((system) => system.start());
|
|
1282
|
+
this.#autoscaledPool = new AutoscaledPool({
|
|
1283
|
+
...this.#taskLoopOptions,
|
|
1284
|
+
concurrencySystem: this.#concurrencySystemDep.value,
|
|
1285
|
+
consumer: this.#identity,
|
|
1286
|
+
});
|
|
1287
|
+
await this.getRequestManager();
|
|
1288
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* The navigation timeout (pre-navigation hooks, navigation, and post-navigation hooks) in milliseconds, used
|
|
1291
|
+
* to size the internal request timeout. `BasicCrawler` has no navigation phase, so this is 0; the HTTP and
|
|
1292
|
+
* browser crawlers override it with their `navigationTimeoutSecs`.
|
|
1293
|
+
*/
|
|
1294
|
+
getNavigationTimeoutMillis() {
|
|
1295
|
+
return 0;
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Races the request against the internal timeout (see {@link raceWithTimeout}), sized to outlast the phases
|
|
1299
|
+
* that have their own timeout - the navigation, its hooks, and the request handler - so a legitimately slow
|
|
1300
|
+
* request, a per-route override, or a low `CRAWLEE_INTERNAL_TIMEOUT` is not cut short mid-phase. It takes
|
|
1301
|
+
* whichever is larger: the configured internal timeout, or this request's combined phase budget.
|
|
1302
|
+
*/
|
|
1303
|
+
async withRequestTimeout(crawlingContext, work) {
|
|
1304
|
+
const { request } = crawlingContext;
|
|
1305
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.resolveRequestHandlerTimeoutMillis(request.label);
|
|
1306
|
+
const timeoutMillis = Math.max(this.internalTimeoutMillis, phasesMillis);
|
|
1307
|
+
await raceWithTimeout(crawlingContext, work, { timeoutMillis, requestId: request.id });
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* The request handler timeout for a request with the given route label. A router route may override the
|
|
1311
|
+
* crawler's own `requestHandlerTimeoutSecs`; anything else falls back to `fallbackMillis`.
|
|
1312
|
+
*
|
|
1313
|
+
* @param label The request's route label, or `undefined` for the default route / no specific request.
|
|
1314
|
+
* @param fallbackMillis Timeout to use when no route overrides it.
|
|
1315
|
+
*/
|
|
1316
|
+
resolveRequestHandlerTimeoutMillis(label, fallbackMillis = this.#requestHandlerTimeoutMillis) {
|
|
1317
|
+
return this.getRouteTimeoutMillis(label) ?? fallbackMillis;
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* The timeout the router route with the given label asked for, or `undefined` when it did not override one
|
|
1321
|
+
* (or the request handler is not a router at all).
|
|
1322
|
+
*/
|
|
1323
|
+
getRouteTimeoutMillis(label) {
|
|
1324
|
+
const getTimeoutSecs = this.requestHandler.getTimeoutSecs;
|
|
1325
|
+
if (typeof getTimeoutSecs !== 'function') {
|
|
1326
|
+
return undefined;
|
|
1327
|
+
}
|
|
1328
|
+
const timeoutSecs = getTimeoutSecs(label);
|
|
1329
|
+
return timeoutSecs === undefined ? undefined : timeoutSecs * 1000;
|
|
734
1330
|
}
|
|
735
1331
|
async runRequestHandler(crawlingContext) {
|
|
736
|
-
|
|
737
|
-
|
|
1332
|
+
const timeoutMillis = this.resolveRequestHandlerTimeoutMillis(crawlingContext.request.label);
|
|
1333
|
+
await addTimeoutToPromise(async () => this.requestHandler(crawlingContext), timeoutMillis, `requestHandler timed out after ${timeoutMillis / 1000} seconds (${crawlingContext.request.id}).`);
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Runs `callback` inside a {@link StorageTransaction}, unless transactional storage is disabled.
|
|
1337
|
+
* Deliberately does **not** commit on return - `handleRequest` swallows request handler failures, so
|
|
1338
|
+
* a normal return says nothing about success. `handleRequest` owns the outcome.
|
|
1339
|
+
*/
|
|
1340
|
+
async runInStorageTransaction(callback) {
|
|
1341
|
+
if (!this.#transactionalStorageEnabled) {
|
|
1342
|
+
return callback();
|
|
1343
|
+
}
|
|
1344
|
+
const transaction = createStorageTransaction({
|
|
1345
|
+
policy: this.#storageWritePolicy,
|
|
1346
|
+
commitTimeoutMillis: this.internalTimeoutMillis,
|
|
738
1347
|
});
|
|
1348
|
+
let threw = true;
|
|
1349
|
+
try {
|
|
1350
|
+
const result = await transaction.run(callback);
|
|
1351
|
+
threw = false;
|
|
1352
|
+
return result;
|
|
1353
|
+
}
|
|
1354
|
+
finally {
|
|
1355
|
+
if (transaction.state === 'open') {
|
|
1356
|
+
// `handleRequest` commits or rolls back on every normal path, so an open transaction on
|
|
1357
|
+
// a normal return is a wiring bug; on a propagating throw (a pipeline-level failure) it is
|
|
1358
|
+
// expected. Either way, discard the unvalidated writes; only the former is worth flagging.
|
|
1359
|
+
if (!threw) {
|
|
1360
|
+
this.log.error('Internal error: a storage transaction was still open after the request pipeline ' +
|
|
1361
|
+
'returned normally. Its writes are being discarded. Please report this.');
|
|
1362
|
+
}
|
|
1363
|
+
transaction.rollback();
|
|
1364
|
+
}
|
|
1365
|
+
// Unconditional: `failed` is a terminal state that the branch above never reaches.
|
|
1366
|
+
transaction.dispose();
|
|
1367
|
+
}
|
|
739
1368
|
}
|
|
740
1369
|
/**
|
|
741
1370
|
* Handles blocked request
|
|
742
1371
|
*/
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
1372
|
+
throwOnBlockedRequest(statusCode) {
|
|
1373
|
+
if (this.retryOnBlocked)
|
|
1374
|
+
return;
|
|
1375
|
+
if (this.blockedStatusCodes.has(statusCode)) {
|
|
1376
|
+
throw new SessionError(`Request blocked - received ${statusCode} status code.`);
|
|
747
1377
|
}
|
|
748
1378
|
}
|
|
749
1379
|
async isAllowedBasedOnRobotsTxtFile(url) {
|
|
750
|
-
if (!this
|
|
1380
|
+
if (!this.#respectRobotsTxtFile) {
|
|
751
1381
|
return true;
|
|
752
1382
|
}
|
|
753
1383
|
const robotsTxtFile = await this.getRobotsTxtFileForUrl(url);
|
|
754
|
-
const userAgent = typeof this
|
|
1384
|
+
const userAgent = typeof this.#respectRobotsTxtFile === 'object' ? this.#respectRobotsTxtFile?.userAgent : '*';
|
|
1385
|
+
if (robotsTxtFile) {
|
|
1386
|
+
const crawlDelay = robotsTxtFile.getCrawlDelay(userAgent);
|
|
1387
|
+
if (crawlDelay !== undefined) {
|
|
1388
|
+
this.applyCrawlDelay(url, crawlDelay);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
755
1391
|
return !robotsTxtFile || robotsTxtFile.isAllowed(url, userAgent);
|
|
756
1392
|
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Records an HTTP 429 against the URL's domain so the request manager can hold the retry back.
|
|
1395
|
+
*
|
|
1396
|
+
* @param retryAfterHeader The raw `Retry-After` response header, if the server sent one.
|
|
1397
|
+
* @returns `true` if the manager took responsibility for the delay, in which case the caller should throw
|
|
1398
|
+
* {@link RequestThrottledError} rather than treating the response as a blocked session.
|
|
1399
|
+
*/
|
|
1400
|
+
recordDomainRateLimit(url, retryAfterHeader) {
|
|
1401
|
+
if (this.requestManager?.recordPacingSignal({
|
|
1402
|
+
reason: 'rateLimited',
|
|
1403
|
+
url,
|
|
1404
|
+
waitMs: parseRetryAfterHeader(retryAfterHeader) ?? undefined,
|
|
1405
|
+
})) {
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
const domain = hostnameOrUrl(url);
|
|
1409
|
+
this.logOncePerRun(`rateLimitNotThrottled:${domain}`, `"${domain}" responded with HTTP 429 (Too Many Requests), but the crawler's request manager does not ` +
|
|
1410
|
+
'pace that domain, so the response is handled like any other, with no per-domain delay. Set ' +
|
|
1411
|
+
`\`sameDomainDelaySecs\`, or pass a \`ThrottlingRequestManager\` covering "${domain}" as ` +
|
|
1412
|
+
'`requestManager`, to honour `Retry-After` and apply exponential backoff instead.', 'warning');
|
|
1413
|
+
return false;
|
|
1414
|
+
}
|
|
1415
|
+
/** Hands a robots.txt `Crawl-delay` to the request manager, warning if it will not be honoured. */
|
|
1416
|
+
applyCrawlDelay(url, delaySeconds) {
|
|
1417
|
+
// robots.txt is per-origin; `hostname` is the closest pacing scope and errs wide (http and https to one
|
|
1418
|
+
// host share a clock).
|
|
1419
|
+
if (this.requestManager?.recordPacingSignal({
|
|
1420
|
+
reason: 'minInterval',
|
|
1421
|
+
url,
|
|
1422
|
+
intervalMs: delaySeconds * 1000,
|
|
1423
|
+
scope: 'hostname',
|
|
1424
|
+
})) {
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
const domain = hostnameOrUrl(url);
|
|
1428
|
+
this.logOncePerRun(`crawlDelayIgnored:${domain}`, `robots.txt for "${domain}" defines a crawl-delay of ${delaySeconds}s, but the crawler's request ` +
|
|
1429
|
+
'manager does not pace that domain, so its requests will not be paced. Set ' +
|
|
1430
|
+
`\`sameDomainDelaySecs\`, or pass a \`ThrottlingRequestManager\` covering "${domain}" as ` +
|
|
1431
|
+
'`requestManager`.', 'warning');
|
|
1432
|
+
}
|
|
757
1433
|
async getRobotsTxtFileForUrl(url) {
|
|
758
|
-
if (!this
|
|
1434
|
+
if (!this.#respectRobotsTxtFile) {
|
|
759
1435
|
return undefined;
|
|
760
1436
|
}
|
|
761
1437
|
try {
|
|
762
1438
|
const origin = new URL(url).origin;
|
|
763
|
-
const cachedRobotsTxtFile = this
|
|
1439
|
+
const cachedRobotsTxtFile = this.#robotsTxtFileCache.get(origin);
|
|
764
1440
|
if (cachedRobotsTxtFile) {
|
|
765
1441
|
return cachedRobotsTxtFile;
|
|
766
1442
|
}
|
|
767
|
-
const robotsTxtFile = await RobotsTxtFile.find(url);
|
|
768
|
-
this
|
|
1443
|
+
const robotsTxtFile = await RobotsTxtFile.find(url, { logger: this.log });
|
|
1444
|
+
this.#robotsTxtFileCache.add(origin, robotsTxtFile);
|
|
769
1445
|
return robotsTxtFile;
|
|
770
1446
|
}
|
|
771
1447
|
catch (e) {
|
|
@@ -773,10 +1449,10 @@ export class BasicCrawler {
|
|
|
773
1449
|
return undefined;
|
|
774
1450
|
}
|
|
775
1451
|
}
|
|
776
|
-
async
|
|
777
|
-
if (this
|
|
1452
|
+
async pauseOnMigration() {
|
|
1453
|
+
if (this.#autoscaledPool) {
|
|
778
1454
|
// if run wasn't called, this is going to crash
|
|
779
|
-
await this
|
|
1455
|
+
await this.#autoscaledPool.pause(SAFE_MIGRATION_WAIT_MILLIS).catch((err) => {
|
|
780
1456
|
if (err.message.includes('running tasks did not finish')) {
|
|
781
1457
|
this.log.error('The crawler was paused due to migration to another host, ' +
|
|
782
1458
|
"but some requests did not finish in time. Those requests' results may be duplicated.");
|
|
@@ -786,14 +1462,16 @@ export class BasicCrawler {
|
|
|
786
1462
|
}
|
|
787
1463
|
});
|
|
788
1464
|
}
|
|
789
|
-
const
|
|
790
|
-
if
|
|
791
|
-
|
|
1465
|
+
const requestManagerPersistPromise = (async () => {
|
|
1466
|
+
// The request manager persists its read-only loader's state, if it has one that supports
|
|
1467
|
+
// persistence (e.g. a tandem wrapping a `RequestList`). For a plain `RequestQueue`, this is a no-op.
|
|
1468
|
+
if (this.requestManager?.persistState) {
|
|
1469
|
+
if ((await this.requestManager.checkReadiness()).status === 'finished')
|
|
792
1470
|
return;
|
|
793
|
-
await this.
|
|
1471
|
+
await this.requestManager.persistState().catch((err) => {
|
|
794
1472
|
if (err.message.includes('Cannot persist state.')) {
|
|
795
1473
|
this.log.error("The crawler attempted to persist its request list's state and failed due to missing or " +
|
|
796
|
-
'invalid
|
|
1474
|
+
'invalid configuration. Make sure to use either RequestList.open() or the "stateKeyPrefix" option of RequestList ' +
|
|
797
1475
|
'constructor to ensure your crawling state is persisted through host migrations and restarts.');
|
|
798
1476
|
}
|
|
799
1477
|
else {
|
|
@@ -803,153 +1481,52 @@ export class BasicCrawler {
|
|
|
803
1481
|
});
|
|
804
1482
|
}
|
|
805
1483
|
})();
|
|
806
|
-
await Promise.all([
|
|
807
|
-
}
|
|
808
|
-
/**
|
|
809
|
-
* Initializes the RequestManager based on the configured requestList and requestQueue.
|
|
810
|
-
*/
|
|
811
|
-
async initializeRequestManager() {
|
|
812
|
-
if (this.requestManager !== undefined) {
|
|
813
|
-
return;
|
|
814
|
-
}
|
|
815
|
-
if (this.requestList && this.requestQueue) {
|
|
816
|
-
// Create a RequestManagerTandem if both RequestList and RequestQueue are provided
|
|
817
|
-
this.requestManager = new RequestManagerTandem(this.requestList, this.requestQueue);
|
|
818
|
-
}
|
|
819
|
-
else if (this.requestQueue) {
|
|
820
|
-
// Use RequestQueue directly if only it is provided
|
|
821
|
-
this.requestManager = this.requestQueue;
|
|
822
|
-
}
|
|
823
|
-
else if (this.requestList) {
|
|
824
|
-
// Use RequestList directly if only it is provided
|
|
825
|
-
// Make it compatible with the IRequestManager interface
|
|
826
|
-
this.requestManager = new RequestListAdapter(this.requestList);
|
|
827
|
-
}
|
|
828
|
-
// If neither RequestList nor RequestQueue is provided, leave the requestManager uninitialized until `getRequestQueue` is called
|
|
1484
|
+
await Promise.all([requestManagerPersistPromise, this.statistics.persistState?.()]);
|
|
829
1485
|
}
|
|
830
1486
|
/**
|
|
831
1487
|
* Fetches the next request to process from the underlying request provider.
|
|
832
1488
|
*/
|
|
833
|
-
async
|
|
1489
|
+
async fetchNextRequest() {
|
|
834
1490
|
if (this.requestManager === undefined) {
|
|
835
|
-
throw new Error(`
|
|
1491
|
+
throw new Error(`fetchNextRequest called on an uninitialized crawler`);
|
|
836
1492
|
}
|
|
837
1493
|
return this.requestManager.fetchNextRequest();
|
|
838
1494
|
}
|
|
839
|
-
/**
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
const domain = getDomain(request.url);
|
|
846
|
-
if (!domain || !request) {
|
|
847
|
-
return false;
|
|
848
|
-
}
|
|
849
|
-
const now = Date.now();
|
|
850
|
-
const lastAccessTime = this.domainAccessedTime.get(domain);
|
|
851
|
-
if (!lastAccessTime || now - lastAccessTime >= this.sameDomainDelayMillis) {
|
|
852
|
-
this.domainAccessedTime.set(domain, now);
|
|
853
|
-
return false;
|
|
854
|
-
}
|
|
855
|
-
if (source instanceof RequestQueueV1) {
|
|
856
|
-
// eslint-disable-next-line dot-notation
|
|
857
|
-
source['inProgress']?.delete(request.id);
|
|
858
|
-
}
|
|
859
|
-
const delay = lastAccessTime + this.sameDomainDelayMillis - now;
|
|
860
|
-
this.log.debug(`Request ${request.url} (${request.id}) will be reclaimed after ${delay} milliseconds due to same domain delay`);
|
|
861
|
-
setTimeout(async () => {
|
|
862
|
-
this.log.debug(`Adding request ${request.url} (${request.id}) back to the queue`);
|
|
863
|
-
if (source instanceof RequestQueueV1) {
|
|
864
|
-
// eslint-disable-next-line dot-notation
|
|
865
|
-
source['inProgress'].add(request.id);
|
|
866
|
-
}
|
|
867
|
-
await source.reclaimRequest(request, { forefront: request.userData?.__crawlee?.forefront });
|
|
868
|
-
}, delay);
|
|
869
|
-
return true;
|
|
870
|
-
}
|
|
871
|
-
/**
|
|
872
|
-
* Wrapper around requestHandler that fetches requests from RequestList/RequestQueue
|
|
873
|
-
* then retries them in a case of an error, etc.
|
|
874
|
-
*/
|
|
875
|
-
async _runTaskFunction() {
|
|
876
|
-
const source = this.requestManager;
|
|
877
|
-
if (!source)
|
|
878
|
-
throw new Error('Request provider is not initialized!');
|
|
879
|
-
const request = await this._timeoutAndRetry(this._fetchNextRequest.bind(this), this.internalTimeoutMillis, `Fetching next request timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
880
|
-
tryCancel();
|
|
881
|
-
const session = this.useSessionPool
|
|
882
|
-
? await this._timeoutAndRetry(async () => {
|
|
883
|
-
return await this.sessionPool.newSession({
|
|
884
|
-
proxyInfo: await this.proxyConfiguration?.newProxyInfo({
|
|
885
|
-
request: request ?? undefined,
|
|
886
|
-
}),
|
|
887
|
-
maxUsageCount: 1,
|
|
888
|
-
});
|
|
889
|
-
}, this.internalTimeoutMillis, `Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`)
|
|
890
|
-
: undefined;
|
|
891
|
-
tryCancel();
|
|
892
|
-
if (!request || this.delayRequest(request, source)) {
|
|
893
|
-
return;
|
|
894
|
-
}
|
|
895
|
-
if (!(await this.isAllowedBasedOnRobotsTxtFile(request.url))) {
|
|
896
|
-
this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`);
|
|
897
|
-
request.state = RequestState.SKIPPED;
|
|
898
|
-
request.noRetry = true;
|
|
899
|
-
await source.markRequestHandled(request);
|
|
900
|
-
await this.handleSkippedRequest({
|
|
901
|
-
url: request.url,
|
|
902
|
-
reason: 'robotsTxt',
|
|
903
|
-
});
|
|
1495
|
+
/** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
|
|
1496
|
+
async handleRequest(crawlingContext, requestSource, request) {
|
|
1497
|
+
// An earlier phase we cannot cancel (e.g. a slow `extendContext`) may have run past the internal timeout,
|
|
1498
|
+
// which already failed the request in `runTaskFunction`. Bail before running the handler so it does not
|
|
1499
|
+
// execute (and re-report) on top of a request the crawler has already moved past.
|
|
1500
|
+
if (crawlingContext[timeoutExpiredKey]?.()) {
|
|
904
1501
|
return;
|
|
905
1502
|
}
|
|
906
|
-
// Reset loadedUrl so an old one is not carried over to retries.
|
|
907
|
-
request.loadedUrl = undefined;
|
|
908
1503
|
const statisticsId = request.id || request.uniqueKey;
|
|
909
|
-
|
|
910
|
-
const
|
|
911
|
-
const crawlingContext = {
|
|
912
|
-
id: cryptoRandomObjectId(10),
|
|
913
|
-
log: this.log,
|
|
914
|
-
request,
|
|
915
|
-
session,
|
|
916
|
-
proxyInfo: session?.proxyInfo,
|
|
917
|
-
enqueueLinks: async (options) => {
|
|
918
|
-
const requestQueue = await this.getRequestQueue();
|
|
919
|
-
return await this.enqueueLinksWithCrawlDepth(options, request, requestQueue);
|
|
920
|
-
},
|
|
921
|
-
addRequests: async (requests, options = {}) => {
|
|
922
|
-
const newCrawlDepth = request.crawlDepth + 1;
|
|
923
|
-
const requestsGenerator = this.addCrawlDepthRequestGenerator(requests, newCrawlDepth);
|
|
924
|
-
await this.addRequests(requestsGenerator, options);
|
|
925
|
-
},
|
|
926
|
-
pushData: this.pushData.bind(this),
|
|
927
|
-
useState: this.useState.bind(this),
|
|
928
|
-
sendRequest: createSendRequest(this.httpClient, request, session),
|
|
929
|
-
getKeyValueStore: async (idOrName) => KeyValueStore.open(idOrName, { config: this.config }),
|
|
930
|
-
registerDeferredCleanup: (cleanup) => {
|
|
931
|
-
deferredCleanup.push(cleanup);
|
|
932
|
-
},
|
|
933
|
-
};
|
|
1504
|
+
// Opened by `runInStorageTransaction`; absent when disabled or when the subclass opens its own.
|
|
1505
|
+
const transaction = currentStorageTransaction();
|
|
934
1506
|
let isRequestLocked = true;
|
|
935
1507
|
try {
|
|
936
1508
|
request.state = RequestState.REQUEST_HANDLER;
|
|
937
1509
|
await this.runRequestHandler(crawlingContext);
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this.
|
|
1510
|
+
// Commit *before* marking the request as handled, so a commit failure fails the request and
|
|
1511
|
+
// it is retried. This also closes the transaction, so everything below passes through.
|
|
1512
|
+
await transaction?.commit();
|
|
1513
|
+
await this.timeoutAndRetry(async () => requestSource.markRequestAsHandled(request), this.internalTimeoutMillis, `Marking request ${request.url} (${request.id}) as handled timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1514
|
+
isRequestLocked = false; // markRequestAsHandled succeeded and unlocked the request
|
|
1515
|
+
this.statistics.finishJob(statisticsId, request.retryCount);
|
|
942
1516
|
// reclaim session if request finishes successfully
|
|
943
1517
|
request.state = RequestState.DONE;
|
|
944
|
-
crawlingContext.session
|
|
1518
|
+
crawlingContext.session.markGood();
|
|
945
1519
|
}
|
|
946
1520
|
catch (rawError) {
|
|
1521
|
+
// Roll back *before* any error handler runs - error handlers write to real storage precisely
|
|
1522
|
+
// because the transaction is already closed. A no-op when the commit above succeeded.
|
|
1523
|
+
transaction?.rollback();
|
|
947
1524
|
const err = this.unwrapError(rawError);
|
|
948
1525
|
try {
|
|
949
1526
|
request.state = RequestState.ERROR_HANDLER;
|
|
950
|
-
await addTimeoutToPromise(async () => this.
|
|
1527
|
+
await addTimeoutToPromise(async () => this.requestFunctionErrorHandler(err, crawlingContext, request, requestSource), this.internalTimeoutMillis, `Handling request failure of ${request.url} (${request.id}) timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
951
1528
|
if (!(err instanceof CriticalError)) {
|
|
952
|
-
isRequestLocked = false; //
|
|
1529
|
+
isRequestLocked = false; // requestFunctionErrorHandler calls either markRequestAsHandled or reclaimRequest
|
|
953
1530
|
}
|
|
954
1531
|
request.state = RequestState.DONE;
|
|
955
1532
|
}
|
|
@@ -967,49 +1544,26 @@ export class BasicCrawler {
|
|
|
967
1544
|
request.state = RequestState.ERROR;
|
|
968
1545
|
throw unwrappedSecondaryError;
|
|
969
1546
|
}
|
|
970
|
-
// decrease the session score if the request fails (but the error handler did not throw)
|
|
971
|
-
|
|
1547
|
+
// decrease the session score if the request fails (but the error handler did not throw);
|
|
1548
|
+
// skip when the error is a SessionError, which already retired the session
|
|
1549
|
+
if (!this.errorAbsolvesSession(err)) {
|
|
1550
|
+
crawlingContext.session.markBad();
|
|
1551
|
+
}
|
|
972
1552
|
}
|
|
973
1553
|
finally {
|
|
974
|
-
|
|
975
|
-
//
|
|
976
|
-
|
|
1554
|
+
// Safety net - return the request to the queue if nobody managed to mark it as handled
|
|
1555
|
+
// or reclaim it before (e.g. after a CriticalError). Reclaiming a request that is no longer
|
|
1556
|
+
// in progress is a harmless no-op on the storage backend.
|
|
1557
|
+
if (isRequestLocked && requestSource instanceof RequestQueue) {
|
|
977
1558
|
try {
|
|
978
|
-
await
|
|
1559
|
+
await requestSource.reclaimRequest(request);
|
|
979
1560
|
}
|
|
980
1561
|
catch {
|
|
981
|
-
//
|
|
1562
|
+
// The request was never in progress, or could not be reclaimed. Either way it's fine.
|
|
982
1563
|
}
|
|
983
1564
|
}
|
|
984
1565
|
}
|
|
985
1566
|
}
|
|
986
|
-
/**
|
|
987
|
-
* Wrapper around the crawling context's `enqueueLinks` method:
|
|
988
|
-
* - Injects `crawlDepth` to each request being added based on the crawling context request.
|
|
989
|
-
* - Provides defaults for the `enqueueLinks` options based on the crawler configuration.
|
|
990
|
-
* - These options can be overridden by the user.
|
|
991
|
-
* @internal
|
|
992
|
-
*/
|
|
993
|
-
async enqueueLinksWithCrawlDepth(options, request, requestQueue) {
|
|
994
|
-
const transformRequestFunctionWrapper = (newRequest) => {
|
|
995
|
-
newRequest.crawlDepth = request.crawlDepth + 1;
|
|
996
|
-
if (this.maxCrawlDepth !== undefined && newRequest.crawlDepth > this.maxCrawlDepth) {
|
|
997
|
-
newRequest.skippedReason = 'depth';
|
|
998
|
-
return false;
|
|
999
|
-
}
|
|
1000
|
-
// After injecting the crawlDepth, we call the user-provided transform function, if there is one.
|
|
1001
|
-
return options.transformRequestFunction?.(newRequest) ?? newRequest;
|
|
1002
|
-
};
|
|
1003
|
-
return await enqueueLinks({
|
|
1004
|
-
requestQueue,
|
|
1005
|
-
robotsTxtFile: await this.getRobotsTxtFileForUrl(request.url),
|
|
1006
|
-
onSkippedRequest: this.handleSkippedRequest,
|
|
1007
|
-
limit: this.calculateEnqueuedRequestLimit(options.limit),
|
|
1008
|
-
// Allow user options to override defaults set above ⤴
|
|
1009
|
-
...options,
|
|
1010
|
-
transformRequestFunction: transformRequestFunctionWrapper,
|
|
1011
|
-
});
|
|
1012
|
-
}
|
|
1013
1567
|
/**
|
|
1014
1568
|
* Generator function that yields requests injected with the given crawl depth.
|
|
1015
1569
|
* @internal
|
|
@@ -1029,7 +1583,7 @@ export class BasicCrawler {
|
|
|
1029
1583
|
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
1030
1584
|
* @ignore
|
|
1031
1585
|
*/
|
|
1032
|
-
async
|
|
1586
|
+
async timeoutAndRetry(handler, timeout, error, maxRetries = 3, retried = 1) {
|
|
1033
1587
|
try {
|
|
1034
1588
|
return await addTimeoutToPromise(handler, timeout, error);
|
|
1035
1589
|
}
|
|
@@ -1037,28 +1591,50 @@ export class BasicCrawler {
|
|
|
1037
1591
|
if (retried <= maxRetries) {
|
|
1038
1592
|
// we retry on any error, not just timeout
|
|
1039
1593
|
this.log.warning(`${e.message} (retrying ${retried}/${maxRetries})`);
|
|
1040
|
-
return this.
|
|
1594
|
+
return this.timeoutAndRetry(handler, timeout, error, maxRetries, retried + 1);
|
|
1041
1595
|
}
|
|
1042
1596
|
throw e;
|
|
1043
1597
|
}
|
|
1044
1598
|
}
|
|
1045
1599
|
/**
|
|
1046
|
-
*
|
|
1600
|
+
* Whether the request manager has a request ready for processing. A manager that is only `waiting` also gets a
|
|
1601
|
+
* wake-up scheduled, so a paced crawl resumes on its clock rather than on the task loop's polling interval.
|
|
1047
1602
|
*/
|
|
1048
|
-
async
|
|
1049
|
-
|
|
1603
|
+
async isTaskReadyFunction() {
|
|
1604
|
+
if (this.requestManager === undefined) {
|
|
1605
|
+
return false;
|
|
1606
|
+
}
|
|
1607
|
+
const state = await this.requestManager.checkReadiness();
|
|
1608
|
+
if (state.status === 'waiting' && state.readyAt !== undefined) {
|
|
1609
|
+
this.#scheduleTaskLoopWake(state.readyAt);
|
|
1610
|
+
}
|
|
1611
|
+
return state.status === 'ready';
|
|
1050
1612
|
}
|
|
1051
1613
|
/**
|
|
1052
|
-
*
|
|
1614
|
+
* Nudges the task loop at `readyAt`, on a single timer that only an earlier one replaces. The pool polls anyway
|
|
1615
|
+
* every `maybeRunIntervalSecs` (0.5s by default), so this only shortens the wait - hence one timer rather than
|
|
1616
|
+
* one per probe, and `unref`'d so it never keeps the process alive.
|
|
1053
1617
|
*/
|
|
1054
|
-
|
|
1055
|
-
|
|
1618
|
+
#scheduleTaskLoopWake(readyAt) {
|
|
1619
|
+
if (this.#taskLoopWakeTimer !== undefined) {
|
|
1620
|
+
if (this.#taskLoopWakeAt <= readyAt) {
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
clearTimeout(this.#taskLoopWakeTimer);
|
|
1624
|
+
}
|
|
1625
|
+
this.#taskLoopWakeAt = readyAt;
|
|
1626
|
+
this.#taskLoopWakeTimer = setTimeout(() => {
|
|
1627
|
+
this.#taskLoopWakeTimer = undefined;
|
|
1628
|
+
void this.#autoscaledPool?.notify();
|
|
1629
|
+
}, Math.max(0, readyAt - Date.now()));
|
|
1630
|
+
this.#taskLoopWakeTimer.unref();
|
|
1056
1631
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1632
|
+
/** Drops a pending task-loop wake-up, so a finished run leaves no timer behind. */
|
|
1633
|
+
#clearTaskLoopWake() {
|
|
1634
|
+
if (this.#taskLoopWakeTimer !== undefined) {
|
|
1635
|
+
clearTimeout(this.#taskLoopWakeTimer);
|
|
1636
|
+
this.#taskLoopWakeTimer = undefined;
|
|
1637
|
+
}
|
|
1062
1638
|
}
|
|
1063
1639
|
/**
|
|
1064
1640
|
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
@@ -1074,27 +1650,38 @@ export class BasicCrawler {
|
|
|
1074
1650
|
}
|
|
1075
1651
|
/**
|
|
1076
1652
|
* Handles errors thrown by user provided requestHandler()
|
|
1653
|
+
*
|
|
1654
|
+
* @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
|
|
1077
1655
|
*/
|
|
1078
|
-
async
|
|
1079
|
-
|
|
1656
|
+
async requestFunctionErrorHandler(error, crawlingContext, request, source) {
|
|
1657
|
+
if (error instanceof RequestThrottledError) {
|
|
1658
|
+
// The domain told us to come back later, so the request was never really attempted. Put it back
|
|
1659
|
+
// without recording a failure - it costs neither a retry nor session reputation.
|
|
1660
|
+
this.log.debug(`Deferring request because its domain is rate-limiting us. ${error.message}`, {
|
|
1661
|
+
id: request.id,
|
|
1662
|
+
url: request.url,
|
|
1663
|
+
});
|
|
1664
|
+
await source.reclaimRequest(request, { forefront: request.userData?.__crawlee?.forefront });
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1080
1667
|
request.pushErrorMessage(error);
|
|
1081
1668
|
if (error instanceof CriticalError) {
|
|
1082
1669
|
throw error;
|
|
1083
1670
|
}
|
|
1084
|
-
const shouldRetryRequest = this.
|
|
1671
|
+
const shouldRetryRequest = this.canRequestBeRetried(request, error);
|
|
1085
1672
|
if (shouldRetryRequest) {
|
|
1086
|
-
await this.
|
|
1087
|
-
await this
|
|
1673
|
+
await this.statistics.errorTrackerRetry.addAsync(error, crawlingContext);
|
|
1674
|
+
await this.#errorHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1088
1675
|
error);
|
|
1089
1676
|
if (error instanceof SessionError) {
|
|
1090
|
-
|
|
1677
|
+
crawlingContext.session?.retire();
|
|
1091
1678
|
}
|
|
1092
1679
|
if (!request.noRetry) {
|
|
1093
1680
|
request.retryCount++;
|
|
1094
1681
|
const { url, retryCount, id } = request;
|
|
1095
1682
|
// We don't want to see the stack trace in the logs by default, when we are going to retry the request.
|
|
1096
1683
|
// Thus, we print the full stack trace only when CRAWLEE_VERBOSE_LOG environment variable is set to true.
|
|
1097
|
-
const message = this.
|
|
1684
|
+
const message = this.getMessageFromError(error);
|
|
1098
1685
|
this.log.warning(`Reclaiming failed request back to the list or queue. ${message}`, {
|
|
1099
1686
|
id,
|
|
1100
1687
|
url,
|
|
@@ -1104,40 +1691,33 @@ export class BasicCrawler {
|
|
|
1104
1691
|
return;
|
|
1105
1692
|
}
|
|
1106
1693
|
}
|
|
1694
|
+
if (error instanceof SessionError) {
|
|
1695
|
+
crawlingContext.session?.retire();
|
|
1696
|
+
}
|
|
1107
1697
|
// If the request is non-retryable, the error and snapshot aren't saved in the errorTrackerRetry object.
|
|
1108
1698
|
// Therefore, we pass the crawlingContext to the errorTracker.add method, enabling snapshot capture.
|
|
1109
1699
|
// This is to make sure the error snapshot is not duplicated in the errorTrackerRetry and errorTracker objects.
|
|
1110
1700
|
const { noRetry, maxRetries } = request;
|
|
1111
1701
|
if (noRetry || !maxRetries) {
|
|
1112
|
-
await this.
|
|
1702
|
+
await this.statistics.errorTracker.addAsync(error, crawlingContext);
|
|
1113
1703
|
}
|
|
1114
1704
|
else {
|
|
1115
|
-
this.
|
|
1705
|
+
this.statistics.errorTracker.add(error);
|
|
1116
1706
|
}
|
|
1117
1707
|
// If we get here, the request is either not retryable
|
|
1118
1708
|
// or failed more than retryCount times and will not be retried anymore.
|
|
1119
1709
|
// Mark the request as failed and do not retry.
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
this.
|
|
1123
|
-
await this._handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
|
|
1124
|
-
}
|
|
1125
|
-
async _tagUserHandlerError(cb) {
|
|
1126
|
-
try {
|
|
1127
|
-
return (await cb());
|
|
1128
|
-
}
|
|
1129
|
-
catch (e) {
|
|
1130
|
-
Object.defineProperty(e, 'triggeredFromUserHandler', { value: true });
|
|
1131
|
-
throw e;
|
|
1132
|
-
}
|
|
1710
|
+
await source.markRequestAsHandled(request);
|
|
1711
|
+
this.statistics.failJob(request.id || request.uniqueKey, request.retryCount);
|
|
1712
|
+
await this.handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
|
|
1133
1713
|
}
|
|
1134
|
-
async
|
|
1714
|
+
async handleFailedRequestHandler(crawlingContext, error) {
|
|
1135
1715
|
// Always log the last error regardless if the user provided a failedRequestHandler
|
|
1136
1716
|
const { id, url, method, uniqueKey } = crawlingContext.request;
|
|
1137
|
-
const message = this.
|
|
1717
|
+
const message = this.getMessageFromError(error, true);
|
|
1138
1718
|
this.log.error(`Request failed and reached maximum retries. ${message}`, { id, url, method, uniqueKey });
|
|
1139
|
-
if (this
|
|
1140
|
-
await this
|
|
1719
|
+
if (this.#failedRequestHandler) {
|
|
1720
|
+
await this.#failedRequestHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1141
1721
|
error);
|
|
1142
1722
|
}
|
|
1143
1723
|
}
|
|
@@ -1146,7 +1726,7 @@ export class BasicCrawler {
|
|
|
1146
1726
|
* @param error The error received
|
|
1147
1727
|
* @returns The message to be logged
|
|
1148
1728
|
*/
|
|
1149
|
-
|
|
1729
|
+
getMessageFromError(error, forceStack = false) {
|
|
1150
1730
|
if ([TypeError, SyntaxError, ReferenceError].some((type) => error instanceof type)) {
|
|
1151
1731
|
forceStack = true;
|
|
1152
1732
|
}
|
|
@@ -1160,11 +1740,16 @@ export class BasicCrawler {
|
|
|
1160
1740
|
? (error.stack ?? [error.message || error, ...stackLines].join('\n'))
|
|
1161
1741
|
: [error.message || error, userLine].join('\n');
|
|
1162
1742
|
}
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1743
|
+
/**
|
|
1744
|
+
* Whether the session should be spared for this error - either because it was already retired, or because the
|
|
1745
|
+
* failure says nothing about the session (a rate limit is a property of the domain).
|
|
1746
|
+
*/
|
|
1747
|
+
errorAbsolvesSession(error) {
|
|
1748
|
+
return error instanceof SessionError || error instanceof RequestThrottledError;
|
|
1749
|
+
}
|
|
1750
|
+
canRequestBeRetried(request, error) {
|
|
1751
|
+
// Request should never be retried, or the error encountered makes it not able to be retried.
|
|
1752
|
+
if (request.noRetry || error instanceof NonRetryableError) {
|
|
1168
1753
|
return false;
|
|
1169
1754
|
}
|
|
1170
1755
|
// User requested retry (we ignore retry count here as its explicitly told by the user to retry)
|
|
@@ -1172,24 +1757,9 @@ export class BasicCrawler {
|
|
|
1172
1757
|
return true;
|
|
1173
1758
|
}
|
|
1174
1759
|
// Ensure there are more retries available for the request
|
|
1175
|
-
const maxRequestRetries = request.maxRetries ?? this
|
|
1760
|
+
const maxRequestRetries = request.maxRetries ?? this.#maxRequestRetries;
|
|
1176
1761
|
return request.retryCount < maxRequestRetries;
|
|
1177
1762
|
}
|
|
1178
|
-
/**
|
|
1179
|
-
* Updates handledRequestsCount from possibly stored counts, usually after worker migration.
|
|
1180
|
-
*/
|
|
1181
|
-
async _loadHandledRequestCount() {
|
|
1182
|
-
if (this.requestManager) {
|
|
1183
|
-
this.handledRequestsCount = await this.requestManager.handledCount();
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
async _executeHooks(hooks, ...args) {
|
|
1187
|
-
if (Array.isArray(hooks) && hooks.length) {
|
|
1188
|
-
for (const hook of hooks) {
|
|
1189
|
-
await hook(...args);
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
1763
|
/**
|
|
1194
1764
|
* Stops the crawler immediately.
|
|
1195
1765
|
*
|
|
@@ -1198,32 +1768,39 @@ export class BasicCrawler {
|
|
|
1198
1768
|
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
1199
1769
|
*/
|
|
1200
1770
|
async teardown() {
|
|
1201
|
-
this
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1771
|
+
// When this crawler initialized the event manager, its close() call emits
|
|
1772
|
+
// the final persistence event after the crawler-specific state has been
|
|
1773
|
+
// saved. External event managers still need an explicit event here.
|
|
1774
|
+
if (!this.#closeEvents) {
|
|
1775
|
+
serviceLocator.getEventManager().emit(EventType.PERSIST_STATE, { isMigrating: false });
|
|
1776
|
+
}
|
|
1777
|
+
await this.#sessionPoolDep.ifOwned(async (pool) => pool.teardown({ persistState: this.#closeEvents ?? false }));
|
|
1778
|
+
if (this.#closeEvents) {
|
|
1779
|
+
await serviceLocator.getEventManager().close();
|
|
1780
|
+
}
|
|
1781
|
+
this.#clearTaskLoopWake();
|
|
1782
|
+
await this.#autoscaledPool?.abort();
|
|
1783
|
+
await this.#concurrencySystemDep?.ifOwned((system) => system.stop());
|
|
1207
1784
|
}
|
|
1208
|
-
|
|
1785
|
+
getCookieHeaderFromRequest(request) {
|
|
1209
1786
|
if (request.headers?.Cookie && request.headers?.cookie) {
|
|
1210
1787
|
this.log.warning(`Encountered mixed casing for the cookie headers for request ${request.url} (${request.id}). Their values will be merged.`);
|
|
1211
1788
|
return mergeCookies(request.url, [request.headers.cookie, request.headers.Cookie]);
|
|
1212
1789
|
}
|
|
1213
1790
|
return request.headers?.Cookie || request.headers?.cookie || '';
|
|
1214
1791
|
}
|
|
1215
|
-
|
|
1216
|
-
//
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1792
|
+
requestMatchesEnqueueStrategy(request) {
|
|
1793
|
+
// If `skipNavigation` was used, just return `true`
|
|
1794
|
+
try {
|
|
1795
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
|
1796
|
+
request.loadedUrl;
|
|
1797
|
+
}
|
|
1798
|
+
catch (err) {
|
|
1799
|
+
if (err instanceof NavigationSkippedError) {
|
|
1800
|
+
return true;
|
|
1221
1801
|
}
|
|
1222
|
-
|
|
1802
|
+
throw err;
|
|
1223
1803
|
}
|
|
1224
|
-
return RequestQueue.open(null, { config: this.config });
|
|
1225
|
-
}
|
|
1226
|
-
requestMatchesEnqueueStrategy(request) {
|
|
1227
1804
|
const { url, loadedUrl } = request;
|
|
1228
1805
|
// eslint-disable-next-line dot-notation -- private access
|
|
1229
1806
|
const strategy = request['enqueueStrategy'];
|
|
@@ -1261,31 +1838,10 @@ export class BasicCrawler {
|
|
|
1261
1838
|
}
|
|
1262
1839
|
}
|
|
1263
1840
|
}
|
|
1264
|
-
/**
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
*
|
|
1269
|
-
* > Serves as a shortcut for using `Router.create<BasicCrawlingContext>()`.
|
|
1270
|
-
*
|
|
1271
|
-
* ```ts
|
|
1272
|
-
* import { BasicCrawler, createBasicRouter } from 'crawlee';
|
|
1273
|
-
*
|
|
1274
|
-
* const router = createBasicRouter();
|
|
1275
|
-
* router.addHandler('label-a', async (ctx) => {
|
|
1276
|
-
* ctx.log.info('...');
|
|
1277
|
-
* });
|
|
1278
|
-
* router.addDefaultHandler(async (ctx) => {
|
|
1279
|
-
* ctx.log.info('...');
|
|
1280
|
-
* });
|
|
1281
|
-
*
|
|
1282
|
-
* const crawler = new BasicCrawler({
|
|
1283
|
-
* requestHandler: router,
|
|
1284
|
-
* });
|
|
1285
|
-
* await crawler.run();
|
|
1286
|
-
* ```
|
|
1287
|
-
*/
|
|
1841
|
+
/** The hostname of `url`, falling back to the whole string when it is not parseable - for log messages only. */
|
|
1842
|
+
function hostnameOrUrl(url) {
|
|
1843
|
+
return URL.canParse(url) ? new URL(url).hostname : url;
|
|
1844
|
+
}
|
|
1288
1845
|
export function createBasicRouter(routes) {
|
|
1289
1846
|
return Router.create(routes);
|
|
1290
1847
|
}
|
|
1291
|
-
//# sourceMappingURL=basic-crawler.js.map
|