@crawlee/basic 4.0.0-beta.10 → 4.0.0-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -13
- package/index.d.ts +1 -2
- package/index.js +0 -2
- package/internals/basic-crawler.d.ts +536 -226
- package/internals/basic-crawler.js +1050 -553
- package/internals/request-timeout.d.ts +48 -0
- package/internals/request-timeout.js +73 -0
- package/internals/send-request.d.ts +3 -6
- package/internals/send-request.js +21 -26
- package/package.json +12 -9
- 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/constants.d.ts +0 -7
- package/internals/constants.d.ts.map +0 -1
- package/internals/constants.js +0 -7
- package/internals/constants.js.map +0 -1
- package/internals/send-request.d.ts.map +0 -1
- package/internals/send-request.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
import { writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
|
-
import { AutoscaledPool,
|
|
4
|
-
import {
|
|
3
|
+
import { AutoscaledPool, bindMethodsToServiceLocator, BLOCKED_STATUS_CODES, ConcurrencySystem, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, CriticalError, Dataset, enqueueLinks, EnqueueStrategy, getObjectType, KeyValueStore, log, LogLevel, mergeCookies, MissingSessionError, NavigationSkippedError, NonRetryableError, OwnedOrInjected, purgeDefaultStorages, RequestHandlerError, RequestManagerTandem, RequestQueue, RequestState, RetryRequestError, Router, ServiceLocator, serviceLocator, Session, SessionError, SessionPool, Statistics, validateUserData, validators, } from '@crawlee/core';
|
|
4
|
+
import { FetchHttpClient } from '@crawlee/http-client';
|
|
5
|
+
import { isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS } from '@crawlee/utils';
|
|
5
6
|
import { stringify } from 'csv-stringify/sync';
|
|
6
7
|
import { ensureDir, writeJSON } from 'fs-extra/esm';
|
|
7
|
-
import ow from 'ow';
|
|
8
|
+
import ow, { ArgumentError } from 'ow';
|
|
8
9
|
import { getDomain } from 'tldts';
|
|
9
10
|
import { LruCache } from '@apify/datastructures';
|
|
10
|
-
import
|
|
11
|
-
import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
|
|
11
|
+
import { addTimeoutToPromise, extendTimeout, TimeoutError } from '@apify/timeout';
|
|
12
12
|
import { cryptoRandomObjectId } from '@apify/utilities';
|
|
13
|
+
import { extendTimeoutKey, navigationDeadlineKey, raceWithTimeout, timeoutExpiredKey, } from './request-timeout.js';
|
|
13
14
|
import { createSendRequest } from './send-request.js';
|
|
15
|
+
class LazyDefaultHttpClient {
|
|
16
|
+
_delegatePromise;
|
|
17
|
+
constructor(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
|
+
async sendRequest(...args) {
|
|
27
|
+
return (await this._delegatePromise).sendRequest(...args);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
14
30
|
/**
|
|
15
31
|
* Since there's no set number of seconds before the container is terminated after
|
|
16
32
|
* a migration event, we need some reasonable number to use for RequestList persistence.
|
|
@@ -21,135 +37,160 @@ import { createSendRequest } from './send-request.js';
|
|
|
21
37
|
* @ignore
|
|
22
38
|
*/
|
|
23
39
|
const SAFE_MIGRATION_WAIT_MILLIS = 20000;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
* or from a dynamic queue of URLs enabling recursive crawling of websites.
|
|
28
|
-
*
|
|
29
|
-
* `BasicCrawler` is a low-level tool that requires the user to implement the page
|
|
30
|
-
* download and data extraction functionality themselves.
|
|
31
|
-
* If we want a crawler that already facilitates this functionality,
|
|
32
|
-
* we should consider using {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler}.
|
|
33
|
-
*
|
|
34
|
-
* `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.requestHandler|`requestHandler`}
|
|
35
|
-
* for each {@link Request} object, which represents a single URL to crawl.
|
|
36
|
-
* The {@link Request} objects are fed from the {@link RequestList} or {@link RequestQueue}
|
|
37
|
-
* instances provided by the {@link BasicCrawlerOptions.requestList|`requestList`} or {@link BasicCrawlerOptions.requestQueue|`requestQueue`}
|
|
38
|
-
* constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
|
|
39
|
-
* the crawler will open the default request queue either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
|
|
40
|
-
* or if `requests` parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
|
|
41
|
-
*
|
|
42
|
-
* If both {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
|
|
43
|
-
* the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
|
|
44
|
-
* to the {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
|
|
45
|
-
*
|
|
46
|
-
* The crawler finishes if there are no more {@link Request} objects to crawl.
|
|
47
|
-
*
|
|
48
|
-
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
49
|
-
* using the functionality provided by the {@link AutoscaledPool} class.
|
|
50
|
-
* All {@link AutoscaledPool} configuration options can be passed to the {@link BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
|
|
51
|
-
* parameter of the `BasicCrawler` constructor.
|
|
52
|
-
* For user convenience, the {@link AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
|
|
53
|
-
* {@link AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
|
|
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
|
-
*/
|
|
40
|
+
const deferredCleanupKey = Symbol('deferredCleanup');
|
|
41
|
+
// The request timeout plumbing (the window helper, the context symbols, and the race) lives in its own module.
|
|
42
|
+
export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
|
|
88
43
|
export class BasicCrawler {
|
|
89
|
-
config;
|
|
90
44
|
static CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
|
|
45
|
+
/**
|
|
46
|
+
* Tracks the number of crawler instances created. The first crawler uses the default
|
|
47
|
+
* request queue; subsequent ones get their own queue via a unique alias so they don't
|
|
48
|
+
* collide.
|
|
49
|
+
*/
|
|
50
|
+
static instanceCount = 0;
|
|
51
|
+
/**
|
|
52
|
+
* Tracks crawler instances that accessed shared state without having an explicit id.
|
|
53
|
+
* Used to detect and warn about multiple crawlers sharing the same state.
|
|
54
|
+
*/
|
|
55
|
+
static useStateAnonymousIndices = new Set();
|
|
91
56
|
/**
|
|
92
57
|
* A reference to the underlying {@link Statistics} class that collects and logs run statistics for requests.
|
|
93
58
|
*/
|
|
94
59
|
stats;
|
|
95
60
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
61
|
+
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
|
|
62
|
+
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
|
|
63
|
+
* via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
|
|
98
64
|
*/
|
|
99
|
-
|
|
65
|
+
requestManager;
|
|
66
|
+
/** Backs the {@link BasicCrawler.sessionPool|`sessionPool`} getter. */
|
|
67
|
+
sessionPoolDep;
|
|
100
68
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* Only available if used by the crawler.
|
|
69
|
+
* A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
|
|
70
|
+
* {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
|
|
104
71
|
*/
|
|
105
|
-
|
|
72
|
+
get sessionPool() {
|
|
73
|
+
return this.sessionPoolDep.value;
|
|
74
|
+
}
|
|
106
75
|
/**
|
|
107
|
-
*
|
|
108
|
-
*
|
|
76
|
+
* Tracks **only** the queue the crawler opens for itself — not the {@link RequestManagerTandem} that may wrap it
|
|
77
|
+
* around a user-supplied `requestList` — so the owned-only purge between repeated `run()` calls never reaches
|
|
78
|
+
* through to a borrowed loader. Filled lazily in {@link BasicCrawler.openOwnedRequestQueue|`openOwnedRequestQueue()`}.
|
|
109
79
|
*/
|
|
110
|
-
|
|
80
|
+
ownedRequestQueue = OwnedOrInjected.resolve();
|
|
111
81
|
/**
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
|
|
116
|
-
|
|
82
|
+
* Whether the request-processing-time hint has already been forwarded to the request manager. The hint
|
|
83
|
+
* derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
|
|
84
|
+
* so it only needs to be applied once, at the first async access of the manager.
|
|
85
|
+
*/
|
|
86
|
+
requestManagerTimeoutsApplied = false;
|
|
87
|
+
/**
|
|
88
|
+
* Resolves the governor for one run: either the injected
|
|
89
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} (borrowed) or a freshly built default with
|
|
90
|
+
* the concurrency shortcuts folded in (owned, so the crawler starts and stops it).
|
|
91
|
+
*/
|
|
92
|
+
resolveConcurrencySystem;
|
|
93
|
+
/** As resolved by `_init()`. Absent until the first run, so a `teardown()` before it is a no-op. */
|
|
94
|
+
concurrencySystemDep;
|
|
95
|
+
/**
|
|
96
|
+
* The concurrency governor this run is booking its requests against — either the
|
|
97
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
|
|
98
|
+
* crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
|
|
99
|
+
*
|
|
100
|
+
* > *NOTE:* `undefined` until {@link BasicCrawler.run|`crawler.run()`} has resolved it. A crawler-owned default
|
|
101
|
+
* is also rebuilt for every run, so the instance is not stable across runs.
|
|
102
|
+
*
|
|
103
|
+
* {@link IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
|
|
104
|
+
* owning the instance: build a {@link ConcurrencySystem} yourself and inject it, then set
|
|
105
|
+
* `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
|
|
106
|
+
*/
|
|
107
|
+
get concurrencySystem() {
|
|
108
|
+
return this.concurrencySystemDep?.maybeValue;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The task loop that dispatches this run's requests. Private on purpose — it is a bare parallel task runner with
|
|
112
|
+
* no configuration left of its own (see {@link ConcurrencySystem}), and everything a caller legitimately did
|
|
113
|
+
* with it now has a crawler-level counterpart: {@link BasicCrawler.pause|`pause()`},
|
|
114
|
+
* {@link BasicCrawler.resume|`resume()`}, {@link BasicCrawler.teardown|`teardown()`} and
|
|
115
|
+
* {@link BasicCrawler.concurrencySystem|`concurrencySystem`}.
|
|
117
116
|
*/
|
|
118
117
|
autoscaledPool;
|
|
118
|
+
/**
|
|
119
|
+
* A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
|
|
120
|
+
* Only available if used by the crawler.
|
|
121
|
+
*/
|
|
122
|
+
proxyConfiguration;
|
|
119
123
|
/**
|
|
120
124
|
* Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
|
|
121
125
|
* See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
|
|
122
126
|
*/
|
|
123
127
|
router = Router.create();
|
|
128
|
+
_basicContextPipeline;
|
|
129
|
+
/**
|
|
130
|
+
* The basic part of the context pipeline. Unlike the subclass pipeline, this
|
|
131
|
+
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
|
|
132
|
+
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
133
|
+
*
|
|
134
|
+
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
135
|
+
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
136
|
+
*/
|
|
137
|
+
get basicContextPipeline() {
|
|
138
|
+
if (this._basicContextPipeline === undefined) {
|
|
139
|
+
this._basicContextPipeline = this.buildBasicContextPipeline();
|
|
140
|
+
}
|
|
141
|
+
return this._basicContextPipeline;
|
|
142
|
+
}
|
|
143
|
+
_contextPipeline;
|
|
144
|
+
get contextPipeline() {
|
|
145
|
+
if (this._contextPipeline === undefined) {
|
|
146
|
+
this._contextPipeline = this.buildFinalContextPipeline();
|
|
147
|
+
}
|
|
148
|
+
return this._contextPipeline;
|
|
149
|
+
}
|
|
124
150
|
running = false;
|
|
125
151
|
hasFinishedBefore = false;
|
|
126
|
-
|
|
152
|
+
unexpectedStop = false;
|
|
153
|
+
#log;
|
|
154
|
+
get log() {
|
|
155
|
+
return this.#log;
|
|
156
|
+
}
|
|
127
157
|
requestHandler;
|
|
128
158
|
errorHandler;
|
|
129
159
|
failedRequestHandler;
|
|
130
160
|
requestHandlerTimeoutMillis;
|
|
131
161
|
internalTimeoutMillis;
|
|
132
162
|
maxRequestRetries;
|
|
163
|
+
maxCrawlDepth;
|
|
133
164
|
sameDomainDelayMillis;
|
|
134
165
|
domainAccessedTime;
|
|
135
|
-
|
|
136
|
-
handledRequestsCount
|
|
166
|
+
maxRequestsPerCrawl;
|
|
167
|
+
get handledRequestsCount() {
|
|
168
|
+
return this.stats.state.requestsFinished + this.stats.state.requestsFailed;
|
|
169
|
+
}
|
|
137
170
|
statusMessageLoggingInterval;
|
|
138
171
|
statusMessageCallback;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
172
|
+
blockedStatusCodes = new Set();
|
|
173
|
+
additionalHttpErrorStatusCodes;
|
|
174
|
+
ignoreHttpErrorStatusCodes;
|
|
175
|
+
/**
|
|
176
|
+
* The resolved options for the crawler's own task loop — the crawler-owned `runTaskFunction`, the (possibly
|
|
177
|
+
* user-overridden) ready/finished predicates and cadence/logging. Concurrency configuration lives on the
|
|
178
|
+
* {@link ConcurrencySystem} instead, and the loop's `consumer` identity is the crawler's own, so neither is
|
|
179
|
+
* settable here.
|
|
180
|
+
*/
|
|
181
|
+
taskLoopOptions;
|
|
144
182
|
httpClient;
|
|
145
183
|
retryOnBlocked;
|
|
146
184
|
respectRobotsTxtFile;
|
|
147
185
|
onSkippedRequest;
|
|
148
186
|
_closeEvents;
|
|
149
|
-
|
|
187
|
+
loggedPerRun = new Set();
|
|
150
188
|
robotsTxtFileCache;
|
|
151
|
-
|
|
189
|
+
identity;
|
|
190
|
+
contextPipelineOptions;
|
|
152
191
|
static optionsShape = {
|
|
192
|
+
contextPipelineBuilder: ow.optional.object,
|
|
193
|
+
extendContext: ow.optional.function,
|
|
153
194
|
requestList: ow.optional.object.validate(validators.requestList),
|
|
154
195
|
requestQueue: ow.optional.object.validate(validators.requestQueue),
|
|
155
196
|
// Subclasses override this function instead of passing it
|
|
@@ -161,145 +202,414 @@ export class BasicCrawler {
|
|
|
161
202
|
failedRequestHandler: ow.optional.function,
|
|
162
203
|
maxRequestRetries: ow.optional.number,
|
|
163
204
|
sameDomainDelaySecs: ow.optional.number,
|
|
164
|
-
maxSessionRotations: ow.optional.number,
|
|
165
205
|
maxRequestsPerCrawl: ow.optional.number,
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
206
|
+
maxCrawlDepth: ow.optional.number,
|
|
207
|
+
taskLoopOptions: ow.optional.object,
|
|
208
|
+
concurrencySystem: ow.optional.object,
|
|
209
|
+
sessionPool: ow.optional.object.validate(validators.sessionPool),
|
|
210
|
+
proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
|
|
169
211
|
statusMessageLoggingInterval: ow.optional.number,
|
|
170
212
|
statusMessageCallback: ow.optional.function,
|
|
213
|
+
additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
|
|
214
|
+
ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
|
|
215
|
+
blockedStatusCodes: ow.optional.array.ofType(ow.number),
|
|
171
216
|
retryOnBlocked: ow.optional.boolean,
|
|
172
|
-
respectRobotsTxtFile: ow.optional.boolean,
|
|
217
|
+
respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object),
|
|
173
218
|
onSkippedRequest: ow.optional.function,
|
|
174
219
|
httpClient: ow.optional.object,
|
|
220
|
+
configuration: ow.optional.object,
|
|
221
|
+
storageBackend: ow.optional.object,
|
|
222
|
+
eventManager: ow.optional.object,
|
|
223
|
+
logger: ow.optional.object,
|
|
175
224
|
// AutoscaledPool shorthands
|
|
176
225
|
minConcurrency: ow.optional.number,
|
|
177
226
|
maxConcurrency: ow.optional.number,
|
|
178
227
|
maxRequestsPerMinute: ow.optional.number.integerOrInfinite.positive.greaterThanOrEqual(1),
|
|
179
228
|
keepAlive: ow.optional.boolean,
|
|
180
|
-
// internal
|
|
181
|
-
log: ow.optional.object,
|
|
182
|
-
experiments: ow.optional.object,
|
|
183
229
|
statisticsOptions: ow.optional.object,
|
|
230
|
+
id: ow.optional.string,
|
|
184
231
|
};
|
|
185
232
|
/**
|
|
186
233
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
187
234
|
*/
|
|
188
|
-
constructor(options = {}
|
|
189
|
-
this.config = config;
|
|
235
|
+
constructor(options = {}) {
|
|
190
236
|
ow(options, 'BasicCrawlerOptions', ow.object.exactShape(BasicCrawler.optionsShape));
|
|
191
|
-
const {
|
|
237
|
+
const {
|
|
238
|
+
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
|
|
239
|
+
requestList,
|
|
240
|
+
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
|
|
241
|
+
requestQueue, requestManager, maxRequestRetries = 3, sameDomainDelaySecs = 0, maxRequestsPerCrawl, maxCrawlDepth, taskLoopOptions = {}, concurrencySystem, keepAlive, sessionPool, proxyConfiguration, additionalHttpErrorStatusCodes = [], ignoreHttpErrorStatusCodes = [],
|
|
242
|
+
// Service locator options
|
|
243
|
+
configuration, storageBackend, eventManager, logger,
|
|
192
244
|
// AutoscaledPool shorthands
|
|
193
|
-
minConcurrency, maxConcurrency, maxRequestsPerMinute, retryOnBlocked = false, respectRobotsTxtFile = false, onSkippedRequest, requestHandler, requestHandlerTimeoutSecs, errorHandler, failedRequestHandler, statusMessageLoggingInterval = 10, statusMessageCallback, statisticsOptions, httpClient,
|
|
194
|
-
//
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
if (
|
|
210
|
-
|
|
245
|
+
minConcurrency, maxConcurrency, maxRequestsPerMinute, blockedStatusCodes: blockedStatusCodesInput, retryOnBlocked = false, respectRobotsTxtFile = false, onSkippedRequest, requestHandler, requestHandlerTimeoutSecs, errorHandler, failedRequestHandler, statusMessageLoggingInterval = 10, statusMessageCallback, statisticsOptions, httpClient, id, } = options;
|
|
246
|
+
// All concurrency configuration lives on the `ConcurrencySystem`, so the shortcuts have nowhere to go once
|
|
247
|
+
// one is supplied - and silently dropping a `maxConcurrency` the user asked for is how crawls end up
|
|
248
|
+
// hammering a site.
|
|
249
|
+
if (concurrencySystem !== undefined &&
|
|
250
|
+
(minConcurrency !== undefined || maxConcurrency !== undefined || maxRequestsPerMinute !== undefined)) {
|
|
251
|
+
throw new ArgumentError('The `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts cannot be combined with ' +
|
|
252
|
+
'`concurrencySystem` - they configure the default `ConcurrencySystem` that a supplied one ' +
|
|
253
|
+
'replaces. Pass them to the `ConcurrencySystem` constructor instead.', this.constructor);
|
|
254
|
+
}
|
|
255
|
+
// Create per-crawler service locator if custom services were provided.
|
|
256
|
+
// This wraps every method on the crawler instance so that calls to the global `serviceLocator`
|
|
257
|
+
// (via AsyncLocalStorage) resolve to this scoped instance instead.
|
|
258
|
+
// We also enter the scope for the rest of the constructor body, so that any code below
|
|
259
|
+
// that accesses `serviceLocator` will see the correct (scoped) instance.
|
|
260
|
+
let serviceLocatorScope = { enterScope: () => { }, exitScope: () => { } };
|
|
261
|
+
if (storageBackend ||
|
|
262
|
+
eventManager ||
|
|
263
|
+
logger ||
|
|
264
|
+
(configuration !== undefined && configuration !== serviceLocator.getConfiguration())) {
|
|
265
|
+
const scopedServiceLocator = new ServiceLocator(configuration, eventManager, storageBackend, logger);
|
|
266
|
+
serviceLocatorScope = bindMethodsToServiceLocator(scopedServiceLocator, this);
|
|
211
267
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
this.maxRequestRetries = maxRequestRetries;
|
|
230
|
-
this.sameDomainDelayMillis = sameDomainDelaySecs * 1000;
|
|
231
|
-
this.maxSessionRotations = maxSessionRotations;
|
|
232
|
-
this.handledRequestsCount = 0;
|
|
233
|
-
this.stats = new Statistics({
|
|
234
|
-
logMessage: `${log.getOptions().prefix} request statistics:`,
|
|
235
|
-
log,
|
|
236
|
-
config,
|
|
237
|
-
...statisticsOptions,
|
|
238
|
-
});
|
|
239
|
-
this.sessionPoolOptions = {
|
|
240
|
-
...sessionPoolOptions,
|
|
241
|
-
log,
|
|
242
|
-
};
|
|
243
|
-
if (this.retryOnBlocked) {
|
|
244
|
-
this.sessionPoolOptions.blockedStatusCodes = sessionPoolOptions.blockedStatusCodes ?? [];
|
|
245
|
-
if (this.sessionPoolOptions.blockedStatusCodes.length !== 0) {
|
|
246
|
-
log.warning(`Both 'blockedStatusCodes' and 'retryOnBlocked' are set. Please note that the 'retryOnBlocked' feature might not work as expected.`);
|
|
268
|
+
try {
|
|
269
|
+
serviceLocatorScope.enterScope();
|
|
270
|
+
this.contextPipelineOptions = {
|
|
271
|
+
contextPipelineBuilder: options.contextPipelineBuilder,
|
|
272
|
+
extendContext: options.extendContext,
|
|
273
|
+
};
|
|
274
|
+
this.#log = serviceLocator.getLogger().child({ prefix: this.constructor.name });
|
|
275
|
+
// Initialize the Configuration instance to avoid lazy loading in the components
|
|
276
|
+
serviceLocator.getConfiguration();
|
|
277
|
+
const instanceIndex = BasicCrawler.instanceCount++;
|
|
278
|
+
this.identity = { instanceIndex, hasExplicitId: id !== undefined, id: id ?? String(instanceIndex) };
|
|
279
|
+
if (requestManager !== undefined) {
|
|
280
|
+
if (requestList !== undefined || requestQueue !== undefined) {
|
|
281
|
+
throw new Error('The `requestManager` option cannot be used in conjunction with `requestList` and/or `requestQueue`');
|
|
282
|
+
}
|
|
283
|
+
this.requestManager = requestManager;
|
|
247
284
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
285
|
+
else if (requestList !== undefined && requestQueue !== undefined) {
|
|
286
|
+
// Combine the read-only list with the writable queue into a tandem.
|
|
287
|
+
this.requestManager = new RequestManagerTandem(requestList, requestQueue);
|
|
288
|
+
}
|
|
289
|
+
else if (requestQueue !== undefined) {
|
|
290
|
+
// A RequestQueue is itself a request manager.
|
|
291
|
+
this.requestManager = requestQueue;
|
|
292
|
+
}
|
|
293
|
+
else if (requestList !== undefined) {
|
|
294
|
+
// A lone read-only `requestList` (deprecated option) is combined with a lazily-opened default queue
|
|
295
|
+
// into a tandem, so that its requests are read first and new ones can still be enqueued during the
|
|
296
|
+
// crawl. The queue is opened on first use; the tandem also forwards `persistState()` to the loader.
|
|
297
|
+
this.requestManager = new RequestManagerTandem(requestList, () => this.openOwnedRequestQueue());
|
|
298
|
+
}
|
|
299
|
+
this.httpClient = httpClient ?? new LazyDefaultHttpClient({ logger: this.log });
|
|
300
|
+
this.proxyConfiguration = proxyConfiguration;
|
|
301
|
+
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
|
|
302
|
+
this.statusMessageCallback = statusMessageCallback;
|
|
303
|
+
this.domainAccessedTime = new Map();
|
|
304
|
+
this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });
|
|
305
|
+
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
|
|
306
|
+
this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);
|
|
307
|
+
this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);
|
|
308
|
+
this.requestHandler = requestHandler ?? this.router;
|
|
309
|
+
this.failedRequestHandler = failedRequestHandler;
|
|
310
|
+
this.errorHandler = errorHandler;
|
|
311
|
+
if (requestHandlerTimeoutSecs) {
|
|
312
|
+
this.requestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
this.requestHandlerTimeoutMillis = 60_000;
|
|
316
|
+
}
|
|
317
|
+
this.retryOnBlocked = retryOnBlocked;
|
|
318
|
+
this.respectRobotsTxtFile = respectRobotsTxtFile;
|
|
319
|
+
this.onSkippedRequest = onSkippedRequest;
|
|
320
|
+
// allow at least 5min for internal timeouts
|
|
321
|
+
this.internalTimeoutMillis =
|
|
322
|
+
serviceLocator.getConfiguration().internalTimeoutMillis ??
|
|
323
|
+
Math.max(this.requestHandlerTimeoutMillis * 2, 300e3);
|
|
324
|
+
this.maxRequestRetries = maxRequestRetries;
|
|
325
|
+
this.maxCrawlDepth = maxCrawlDepth;
|
|
326
|
+
this.sameDomainDelayMillis = sameDomainDelaySecs * 1000;
|
|
327
|
+
this.stats = new Statistics({
|
|
328
|
+
logMessage: `${this.constructor.name} request statistics:`,
|
|
329
|
+
log: this.log,
|
|
330
|
+
id: this.identity.id,
|
|
331
|
+
...statisticsOptions,
|
|
332
|
+
});
|
|
333
|
+
if (sessionPool && proxyConfiguration) {
|
|
334
|
+
this.log.warning('Both `sessionPool` and `proxyConfiguration` were provided to the crawler. ' +
|
|
335
|
+
'The `proxyConfiguration` is ignored - sessions from the supplied pool keep whatever ' +
|
|
336
|
+
'`proxyInfo` they were created with. Configure proxies on the pool instead, ' +
|
|
337
|
+
'e.g. via `addSession({ proxyInfo })` or a custom `createSessionFunction`.');
|
|
338
|
+
}
|
|
339
|
+
this.sessionPoolDep = OwnedOrInjected.resolve(sessionPool, () => new SessionPool({
|
|
340
|
+
createSessionFunction: async (opts) => new Session({
|
|
341
|
+
...opts?.sessionOptions,
|
|
342
|
+
proxyInfo: opts?.sessionOptions?.proxyInfo ?? (await this.proxyConfiguration?.newProxyInfo()),
|
|
343
|
+
}),
|
|
344
|
+
}));
|
|
345
|
+
this.blockedStatusCodes = new Set(blockedStatusCodesInput ?? BLOCKED_STATUS_CODES);
|
|
346
|
+
const maxSignedInteger = 2 ** 31 - 1;
|
|
347
|
+
if (this.requestHandlerTimeoutMillis > maxSignedInteger) {
|
|
348
|
+
this.log.warning(`requestHandlerTimeoutMillis ${this.requestHandlerTimeoutMillis}` +
|
|
349
|
+
` does not fit a signed 32-bit integer. Limiting the value to ${maxSignedInteger}`);
|
|
350
|
+
this.requestHandlerTimeoutMillis = maxSignedInteger;
|
|
351
|
+
}
|
|
352
|
+
this.internalTimeoutMillis = Math.min(this.internalTimeoutMillis, maxSignedInteger);
|
|
353
|
+
this.maxRequestsPerCrawl = maxRequestsPerCrawl;
|
|
354
|
+
const isMaxPagesExceeded = () => this.maxRequestsPerCrawl && this.maxRequestsPerCrawl <= this.handledRequestsCount;
|
|
355
|
+
// eslint-disable-next-line prefer-const
|
|
356
|
+
let { isFinishedFunction, isTaskReadyFunction } = taskLoopOptions;
|
|
357
|
+
// override even if `isFinishedFunction` provided by user - `keepAlive` has higher priority
|
|
358
|
+
if (keepAlive) {
|
|
359
|
+
isFinishedFunction = async () => false;
|
|
360
|
+
}
|
|
361
|
+
const crawlerOwnedTaskLoopConfiguration = {
|
|
362
|
+
runTaskFunction: async () => {
|
|
363
|
+
const source = this.requestManager;
|
|
364
|
+
if (!source)
|
|
365
|
+
throw new Error('Request provider is not initialized!');
|
|
366
|
+
const request = await this.resolveRequest();
|
|
367
|
+
if (!request || this.delayRequest(request, source)) {
|
|
368
|
+
return;
|
|
277
369
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
370
|
+
// Started here, rather than in `handleRequest`, so that a failure during context pipeline
|
|
371
|
+
// initialization (e.g. a browser page timing out before the request handler ever runs) is
|
|
372
|
+
// still accounted for by `failJob` below - which is a no-op without a matching `startJob`.
|
|
373
|
+
this.stats.startJob(request.id || request.uniqueKey);
|
|
374
|
+
const crawlingContext = { request };
|
|
375
|
+
try {
|
|
376
|
+
// Navigation, the navigation hooks and the request handler are timed individually, but the
|
|
377
|
+
// phases between them are not, so a request could still get stuck indefinitely. This is the
|
|
378
|
+
// catch-all for that - see `raceWithTimeout` for why it is a bare timer, not a timeout frame.
|
|
379
|
+
await this.withRequestTimeout(crawlingContext, this.basicContextPipeline
|
|
380
|
+
.chain(this.contextPipeline)
|
|
381
|
+
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request)));
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
// ContextPipelineInterruptedError means the request was intentionally skipped
|
|
385
|
+
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
|
|
386
|
+
if (error instanceof ContextPipelineInterruptedError) {
|
|
387
|
+
this.stats.discardJob(request.id || request.uniqueKey);
|
|
388
|
+
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.`);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
|
|
392
|
+
// i.e. not in user's requestHandler), handle it through the normal error flow. A bare `TimeoutError`
|
|
393
|
+
// here is the internal timeout above firing - anything else thrown inside the pipeline arrives wrapped.
|
|
394
|
+
const isPipelineError = error instanceof ContextPipelineInitializationError ||
|
|
395
|
+
error instanceof SessionError ||
|
|
396
|
+
error instanceof TimeoutError;
|
|
397
|
+
if (isPipelineError) {
|
|
398
|
+
const unwrappedError = this.unwrapError(error);
|
|
399
|
+
await this.requestFunctionErrorHandler(unwrappedError, crawlingContext, request, this.requestManager);
|
|
400
|
+
// SessionError already retired the session in `requestFunctionErrorHandler`;
|
|
401
|
+
// skip `markBad` to avoid double-counting usage/error score.
|
|
402
|
+
if (!(unwrappedError instanceof SessionError)) {
|
|
403
|
+
crawlingContext.session?.markBad();
|
|
404
|
+
}
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
throw this.unwrapError(error);
|
|
408
|
+
}
|
|
409
|
+
finally {
|
|
410
|
+
// Run request-scoped deferred cleanups only after the whole request lifecycle - including the user's error handler - has finished.
|
|
411
|
+
const deferredCleanup = crawlingContext[deferredCleanupKey] ?? [];
|
|
412
|
+
await Promise.all(deferredCleanup.map((fn) => fn().catch((cleanupError) => this.log.debug('Error in deferred cleanup', { error: cleanupError }))));
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
isTaskReadyFunction: async () => {
|
|
416
|
+
if (isMaxPagesExceeded()) {
|
|
417
|
+
this.logOncePerRun('shuttingDown', 'Crawler reached the maxRequestsPerCrawl limit of ' +
|
|
418
|
+
`${this.maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`);
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
if (this.unexpectedStop) {
|
|
422
|
+
this.logOncePerRun('shuttingDown', 'No new requests are allowed because the `stop()` method has been called. ' +
|
|
423
|
+
'Ongoing requests will be allowed to complete.');
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
return isTaskReadyFunction ? await isTaskReadyFunction() : await this.isTaskReadyFunction();
|
|
427
|
+
},
|
|
428
|
+
isFinishedFunction: async () => {
|
|
429
|
+
if (isMaxPagesExceeded()) {
|
|
430
|
+
this.log.info(`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${this.maxRequestsPerCrawl} requests ` +
|
|
431
|
+
'and all requests that were in progress at that time have now finished. ' +
|
|
432
|
+
`In total, the crawler processed ${this.handledRequestsCount} requests and will shut down.`);
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
if (this.unexpectedStop) {
|
|
436
|
+
this.log.info('The crawler has finished all the remaining ongoing requests and will shut down now.');
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
const isFinished = isFinishedFunction
|
|
440
|
+
? await isFinishedFunction()
|
|
441
|
+
: await this.defaultIsFinishedFunction();
|
|
442
|
+
if (isFinished) {
|
|
443
|
+
const reason = isFinishedFunction
|
|
444
|
+
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
|
|
445
|
+
: 'All requests from the queue have been processed, the crawler will shut down.';
|
|
446
|
+
this.log.info(reason);
|
|
447
|
+
}
|
|
448
|
+
return isFinished;
|
|
449
|
+
},
|
|
450
|
+
log: this.log,
|
|
451
|
+
};
|
|
452
|
+
this.taskLoopOptions = { ...taskLoopOptions, ...crawlerOwnedTaskLoopConfiguration };
|
|
453
|
+
this.resolveConcurrencySystem = () => OwnedOrInjected.resolve(concurrencySystem, () => this.createDefaultConcurrencySystem({
|
|
454
|
+
minConcurrency,
|
|
455
|
+
maxConcurrency,
|
|
456
|
+
maxTasksPerMinute: maxRequestsPerMinute,
|
|
457
|
+
log: this.log,
|
|
458
|
+
}));
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
serviceLocatorScope.exitScope();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
|
|
466
|
+
* `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
467
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
|
|
468
|
+
*
|
|
469
|
+
* Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
|
|
470
|
+
* concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.
|
|
471
|
+
*/
|
|
472
|
+
createDefaultConcurrencySystem(options) {
|
|
473
|
+
return new ConcurrencySystem(options);
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Determines if the given HTTP status code is an error status code given
|
|
477
|
+
* the default behaviour and user-set preferences.
|
|
478
|
+
* @param status
|
|
479
|
+
* @returns `true` if the status code is considered an error, `false` otherwise
|
|
480
|
+
*/
|
|
481
|
+
isErrorStatusCode(status) {
|
|
482
|
+
const excludeError = this.ignoreHttpErrorStatusCodes.has(status);
|
|
483
|
+
const includeError = this.additionalHttpErrorStatusCodes.has(status);
|
|
484
|
+
return (status >= 500 && !excludeError) || includeError;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
488
|
+
* This handles base context creation, session resolution, and context helpers.
|
|
489
|
+
*/
|
|
490
|
+
buildBasicContextPipeline() {
|
|
491
|
+
return ContextPipeline.create()
|
|
492
|
+
.compose({ action: this.checkRobotsTxt.bind(this) })
|
|
493
|
+
.compose({ action: (context) => this.createBaseContext(context) })
|
|
494
|
+
.compose({ action: this.resolveSession.bind(this) })
|
|
495
|
+
.compose({ action: this.createContextHelpers.bind(this) });
|
|
496
|
+
}
|
|
497
|
+
async checkRobotsTxt({ request }) {
|
|
498
|
+
if (!(await this.isAllowedBasedOnRobotsTxtFile(request.url))) {
|
|
499
|
+
this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`);
|
|
500
|
+
request.state = RequestState.SKIPPED;
|
|
501
|
+
request.noRetry = true;
|
|
502
|
+
await this.handleSkippedRequest({
|
|
503
|
+
url: request.url,
|
|
504
|
+
reason: 'robotsTxt',
|
|
505
|
+
});
|
|
506
|
+
throw new ContextPipelineInterruptedError(`Skipping request ${request.url} as disallowed by robots.txt`);
|
|
507
|
+
}
|
|
508
|
+
return {};
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
512
|
+
* Subclasses should override this to add their own pipeline stages.
|
|
513
|
+
*/
|
|
514
|
+
buildContextPipeline() {
|
|
515
|
+
return ContextPipeline.create();
|
|
516
|
+
}
|
|
517
|
+
createBaseContext(context) {
|
|
518
|
+
const deferredCleanup = [];
|
|
519
|
+
return {
|
|
520
|
+
id: cryptoRandomObjectId(10),
|
|
521
|
+
log: this.log,
|
|
522
|
+
pushData: this.pushData.bind(this),
|
|
523
|
+
useState: this.useState.bind(this),
|
|
524
|
+
getKeyValueStore: async (identifier) => KeyValueStore.open(identifier),
|
|
525
|
+
registerDeferredCleanup: (cleanup) => {
|
|
526
|
+
deferredCleanup.push(cleanup);
|
|
281
527
|
},
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
if (isFinished) {
|
|
293
|
-
const reason = isFinishedFunction
|
|
294
|
-
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
|
|
295
|
-
: 'All requests from the queue have been processed, the crawler will shut down.';
|
|
296
|
-
log.info(reason);
|
|
528
|
+
extendTimeout: (secs) => {
|
|
529
|
+
const extraMillis = secs * 1000;
|
|
530
|
+
// the current `addTimeoutToPromise` window (the request handler, or a navigation hook)...
|
|
531
|
+
extendTimeout(extraMillis);
|
|
532
|
+
// ...the internal timeout around the whole request, which is not an `addTimeoutToPromise` frame...
|
|
533
|
+
context[extendTimeoutKey]?.(extraMillis);
|
|
534
|
+
// ...and, when called from within the navigation phase, its shared window, so extending a hook
|
|
535
|
+
// extends the whole navigation budget rather than just that hook's step.
|
|
536
|
+
if (context[navigationDeadlineKey] !== undefined) {
|
|
537
|
+
context[navigationDeadlineKey] += extraMillis;
|
|
297
538
|
}
|
|
298
|
-
return isFinished;
|
|
299
539
|
},
|
|
300
|
-
|
|
540
|
+
[deferredCleanupKey]: deferredCleanup,
|
|
301
541
|
};
|
|
302
|
-
|
|
542
|
+
}
|
|
543
|
+
async resolveRequest() {
|
|
544
|
+
const request = await this.timeoutAndRetry(this.fetchNextRequest.bind(this), this.internalTimeoutMillis, `Fetching next request timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
545
|
+
// Reset loadedUrl so an old one is not carried over to retries.
|
|
546
|
+
if (request) {
|
|
547
|
+
request.loadedUrl = undefined;
|
|
548
|
+
}
|
|
549
|
+
return request;
|
|
550
|
+
}
|
|
551
|
+
async resolveSession({ request }) {
|
|
552
|
+
const session = await this.timeoutAndRetry(async () => {
|
|
553
|
+
const existingSession = await this.sessionPool.getSession(request.sessionId);
|
|
554
|
+
if (!existingSession) {
|
|
555
|
+
throw new ContextPipelineInitializationError(new MissingSessionError(request.sessionId));
|
|
556
|
+
}
|
|
557
|
+
return existingSession;
|
|
558
|
+
}, this.internalTimeoutMillis, `Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
559
|
+
return { session, proxyInfo: session?.proxyInfo };
|
|
560
|
+
}
|
|
561
|
+
async createContextHelpers({ request, session }) {
|
|
562
|
+
const enqueueLinksWrapper = async (options) => {
|
|
563
|
+
const requestManager = await this.getRequestManager();
|
|
564
|
+
return await this.enqueueLinksWithCrawlDepth(options, request, requestManager);
|
|
565
|
+
};
|
|
566
|
+
const addRequests = async (requests, options = {}) => {
|
|
567
|
+
const newCrawlDepth = request.crawlDepth + 1;
|
|
568
|
+
const requestsGenerator = this.addCrawlDepthRequestGenerator(requests, newCrawlDepth);
|
|
569
|
+
await this.addRequests(requestsGenerator, options);
|
|
570
|
+
};
|
|
571
|
+
const sendRequest = createSendRequest(this.httpClient, request, session);
|
|
572
|
+
return { enqueueLinks: enqueueLinksWrapper, addRequests, sendRequest };
|
|
573
|
+
}
|
|
574
|
+
buildFinalContextPipeline() {
|
|
575
|
+
const subclassPipeline = (this.contextPipelineOptions.contextPipelineBuilder?.() ??
|
|
576
|
+
this.buildContextPipeline());
|
|
577
|
+
// `extendContext` runs *before* the subclass navigation pipeline (which includes the
|
|
578
|
+
// pre/post-navigation hooks). This makes the extension visible to those hooks and to the
|
|
579
|
+
// request handler alike. The trade-off is that `extendContext` cannot access
|
|
580
|
+
// navigation-dependent context members (e.g. `page`, `response`, `$`, `body`), as those
|
|
581
|
+
// don't exist yet at this point in the pipeline.
|
|
582
|
+
// The `extendContext` output (`ContextExtension`) is carried through the subclass pipeline at
|
|
583
|
+
// runtime (the pipeline copies each middleware's returned members onto the shared context), but
|
|
584
|
+
// TypeScript cannot express that `Context` transitively includes `ContextExtension` here. The
|
|
585
|
+
// casts below are sound because `buildFinalContextPipeline` is declared to return the fully
|
|
586
|
+
// resolved `ExtendedContext` (= `Context & ContextExtension`).
|
|
587
|
+
const { extendContext } = this.contextPipelineOptions;
|
|
588
|
+
let contextPipeline;
|
|
589
|
+
if (extendContext !== undefined) {
|
|
590
|
+
contextPipeline = ContextPipeline.create()
|
|
591
|
+
.compose({ action: async (context) => await extendContext(context) })
|
|
592
|
+
.chain(subclassPipeline);
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
contextPipeline = subclassPipeline;
|
|
596
|
+
}
|
|
597
|
+
contextPipeline = contextPipeline.compose({
|
|
598
|
+
action: async (context) => {
|
|
599
|
+
const { request } = context;
|
|
600
|
+
if (request && !this.requestMatchesEnqueueStrategy(request)) {
|
|
601
|
+
// eslint-disable-next-line dot-notation
|
|
602
|
+
const message = `Skipping request ${request.id} (starting url: ${request.url} -> loaded url: ${request.loadedUrl}) because it does not match the enqueue strategy (${request['enqueueStrategy']}).`;
|
|
603
|
+
this.log.debug(message);
|
|
604
|
+
request.noRetry = true;
|
|
605
|
+
request.state = RequestState.SKIPPED;
|
|
606
|
+
await this.handleSkippedRequest({ url: request.url, reason: 'redirect' });
|
|
607
|
+
throw new ContextPipelineInterruptedError(message);
|
|
608
|
+
}
|
|
609
|
+
return context;
|
|
610
|
+
},
|
|
611
|
+
});
|
|
612
|
+
return contextPipeline;
|
|
303
613
|
}
|
|
304
614
|
/**
|
|
305
615
|
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
|
|
@@ -311,25 +621,27 @@ export class BasicCrawler {
|
|
|
311
621
|
return ROTATE_PROXY_ERRORS.some((x) => this._getMessageFromError(error)?.includes(x));
|
|
312
622
|
}
|
|
313
623
|
/**
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
* @param _crawlingContext The crawling context to check.
|
|
317
|
-
*/
|
|
318
|
-
async isRequestBlocked(_crawlingContext) {
|
|
319
|
-
throw new Error('the "isRequestBlocked" method is not implemented in this crawler.');
|
|
320
|
-
}
|
|
321
|
-
/**
|
|
624
|
+
* Sets the status message for the current crawler run.
|
|
625
|
+
*
|
|
322
626
|
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
|
|
627
|
+
*
|
|
628
|
+
* The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
|
|
629
|
+
* event. Integrations such as the Apify SDK subscribe to that event and forward the message to
|
|
630
|
+
* their status-reporting backend (e.g. the Apify platform).
|
|
323
631
|
*/
|
|
324
|
-
|
|
632
|
+
setStatusMessage(message, options = {}) {
|
|
325
633
|
const data = options.isStatusMessageTerminal != null ? { terminal: options.isStatusMessageTerminal } : undefined;
|
|
326
|
-
this.log.
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
634
|
+
this.log.logWithLevel(LogLevel[options.level ?? 'DEBUG'], message, data);
|
|
635
|
+
// Broadcast the status message through the event system. Consumers (e.g. the Apify SDK) can
|
|
636
|
+
// subscribe to `EventType.STATUS_MESSAGE` and propagate it to their status-reporting backend.
|
|
637
|
+
// Setting the status message is not a storage concern, so we intentionally don't route it
|
|
638
|
+
// through the storage client anymore.
|
|
639
|
+
serviceLocator.getEventManager().emit("statusMessage" /* EventType.STATUS_MESSAGE */, {
|
|
640
|
+
crawlerId: this.identity.id,
|
|
641
|
+
message,
|
|
642
|
+
isStatusMessageTerminal: options.isStatusMessageTerminal,
|
|
643
|
+
level: options.level,
|
|
644
|
+
});
|
|
333
645
|
}
|
|
334
646
|
getPeriodicLogger() {
|
|
335
647
|
let previousState = { ...this.stats.state };
|
|
@@ -337,20 +649,21 @@ export class BasicCrawler {
|
|
|
337
649
|
const { requestsFailed } = this.stats.state;
|
|
338
650
|
const { requestsFailed: previousRequestsFailed } = previousState;
|
|
339
651
|
previousState = { ...this.stats.state };
|
|
340
|
-
|
|
341
|
-
|
|
652
|
+
const failedDelta = requestsFailed - previousRequestsFailed;
|
|
653
|
+
if (failedDelta > 0) {
|
|
654
|
+
return { mode: 'ERROR', failedDelta };
|
|
342
655
|
}
|
|
343
|
-
return 'REGULAR';
|
|
656
|
+
return { mode: 'REGULAR', failedDelta: 0 };
|
|
344
657
|
};
|
|
345
658
|
const log = async () => {
|
|
346
|
-
const operationMode = getOperationMode();
|
|
659
|
+
const { mode: operationMode, failedDelta } = getOperationMode();
|
|
347
660
|
let message;
|
|
348
661
|
if (operationMode === 'ERROR') {
|
|
349
|
-
message = `Experiencing problems, ${
|
|
662
|
+
message = `Experiencing problems, ${failedDelta} failed requests in the past ${this.statusMessageLoggingInterval} seconds.`;
|
|
350
663
|
}
|
|
351
664
|
else {
|
|
352
|
-
const total = this.
|
|
353
|
-
message = `Crawled ${this.stats.state.requestsFinished}${total ? `/${total}` : ''} pages, ${this.stats.state.requestsFailed} failed requests, desired concurrency ${this.
|
|
665
|
+
const total = await this.requestManager?.getTotalCount();
|
|
666
|
+
message = `Crawled ${this.stats.state.requestsFinished}${total ? `/${total}` : ''} pages, ${this.stats.state.requestsFailed} failed requests, desired concurrency ${this.concurrencySystem?.desiredConcurrency ?? 0}.`;
|
|
354
667
|
}
|
|
355
668
|
if (this.statusMessageCallback) {
|
|
356
669
|
await this.statusMessageCallback({
|
|
@@ -361,14 +674,15 @@ export class BasicCrawler {
|
|
|
361
674
|
});
|
|
362
675
|
return;
|
|
363
676
|
}
|
|
364
|
-
|
|
677
|
+
this.setStatusMessage(message);
|
|
365
678
|
};
|
|
366
679
|
const interval = setInterval(log, this.statusMessageLoggingInterval * 1e3);
|
|
367
680
|
return { log, stop: () => clearInterval(interval) };
|
|
368
681
|
}
|
|
369
682
|
/**
|
|
370
|
-
* Runs the crawler. Returns a promise that resolves once
|
|
371
|
-
*
|
|
683
|
+
* Runs the crawler. Returns a promise that resolves once every request has been processed and the crawler's
|
|
684
|
+
* finished-check ({@link BasicCrawlerOptions.taskLoopOptions|`taskLoopOptions.isFinishedFunction`}, or the
|
|
685
|
+
* default "the request manager is empty") reports that the crawl is over.
|
|
372
686
|
*
|
|
373
687
|
* We can use the `requests` parameter to enqueue the initial requests — it is a shortcut for
|
|
374
688
|
* running {@link BasicCrawler.addRequests|`crawler.addRequests()`} before {@link BasicCrawler.run|`crawler.run()`}.
|
|
@@ -380,39 +694,61 @@ export class BasicCrawler {
|
|
|
380
694
|
if (this.running) {
|
|
381
695
|
throw new Error('This crawler instance is already running, you can add more requests to it via `crawler.addRequests()`.');
|
|
382
696
|
}
|
|
383
|
-
const { purgeRequestQueue
|
|
697
|
+
const { purgeRequestQueue, ...addRequestsOptions } = options ?? {};
|
|
384
698
|
if (this.hasFinishedBefore) {
|
|
385
699
|
// When executing the run method for the second time explicitly,
|
|
386
|
-
// we need to purge the
|
|
700
|
+
// we need to purge the RQ to allow processing the same requests again — this is important so users can
|
|
387
701
|
// pass in failed requests back to the `crawler.run()`, otherwise they would be considered as handled and
|
|
388
|
-
// ignored
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
702
|
+
// ignored — as a failed request is still handled.
|
|
703
|
+
// By default (`purgeRequestQueue` unset), only the queue we opened ourselves is purged.
|
|
704
|
+
// When `purgeRequestQueue` is explicitly `true`, we also purge a user-supplied manager.
|
|
705
|
+
// When `purgeRequestQueue` is explicitly `false`, nothing is purged.
|
|
706
|
+
const shouldPurge = purgeRequestQueue !== false;
|
|
707
|
+
const managerToPurge = this.ownedRequestQueue.maybeValue ?? (purgeRequestQueue === true ? this.requestManager : undefined);
|
|
708
|
+
if (managerToPurge?.purge && shouldPurge) {
|
|
709
|
+
await managerToPurge.purge();
|
|
392
710
|
}
|
|
393
711
|
this.stats.reset();
|
|
394
712
|
await this.stats.resetStore();
|
|
395
|
-
await this.
|
|
713
|
+
await this.sessionPoolDep.ifOwned((pool) => pool.resetStore());
|
|
396
714
|
}
|
|
715
|
+
this.unexpectedStop = false;
|
|
397
716
|
this.running = true;
|
|
398
|
-
|
|
717
|
+
this.loggedPerRun.clear();
|
|
718
|
+
await purgeDefaultStorages({
|
|
719
|
+
onlyPurgeOnce: true,
|
|
720
|
+
storageBackend: serviceLocator.getStorageBackend(),
|
|
721
|
+
configuration: serviceLocator.getConfiguration(),
|
|
722
|
+
});
|
|
399
723
|
if (requests) {
|
|
400
724
|
await this.addRequests(requests, addRequestsOptions);
|
|
401
725
|
}
|
|
402
|
-
|
|
403
|
-
|
|
726
|
+
try {
|
|
727
|
+
await this._init();
|
|
728
|
+
await this.stats.startCapturing();
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
// Clean up here before propagating, otherwise a failed startup would leave the process hanging.
|
|
732
|
+
await this.teardown().catch((teardownError) => {
|
|
733
|
+
this.log.exception(teardownError, 'Cleaning up after a failed crawler startup failed.');
|
|
734
|
+
});
|
|
735
|
+
// The run never began, so let the instance be run again instead of leaving it wedged as `running`.
|
|
736
|
+
this.running = false;
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
404
739
|
const periodicLogger = this.getPeriodicLogger();
|
|
405
|
-
|
|
740
|
+
this.setStatusMessage('Starting the crawler.', { level: 'INFO' });
|
|
406
741
|
const sigintHandler = async () => {
|
|
407
742
|
this.log.warning('Pausing... Press CTRL+C again to force exit. To resume, do: CRAWLEE_PURGE_ON_START=0 npm start');
|
|
408
|
-
await this.
|
|
743
|
+
await this.pauseOnMigration();
|
|
409
744
|
await this.autoscaledPool.abort();
|
|
410
745
|
};
|
|
411
746
|
// Attach a listener to handle migration and aborting events gracefully.
|
|
412
|
-
const boundPauseOnMigration = this.
|
|
747
|
+
const boundPauseOnMigration = this.pauseOnMigration.bind(this);
|
|
413
748
|
process.once('SIGINT', sigintHandler);
|
|
414
|
-
|
|
415
|
-
|
|
749
|
+
const eventManager = serviceLocator.getEventManager();
|
|
750
|
+
eventManager.on("migrating" /* EventType.MIGRATING */, boundPauseOnMigration);
|
|
751
|
+
eventManager.on("aborting" /* EventType.ABORTING */, boundPauseOnMigration);
|
|
416
752
|
let stats = {};
|
|
417
753
|
try {
|
|
418
754
|
await this.autoscaledPool.run();
|
|
@@ -421,8 +757,8 @@ export class BasicCrawler {
|
|
|
421
757
|
await this.teardown();
|
|
422
758
|
await this.stats.stopCapturing();
|
|
423
759
|
process.off('SIGINT', sigintHandler);
|
|
424
|
-
|
|
425
|
-
|
|
760
|
+
eventManager.off("migrating" /* EventType.MIGRATING */, boundPauseOnMigration);
|
|
761
|
+
eventManager.off("aborting" /* EventType.ABORTING */, boundPauseOnMigration);
|
|
426
762
|
const finalStats = this.stats.calculate();
|
|
427
763
|
stats = {
|
|
428
764
|
requestsFinished: this.stats.state.requestsFinished,
|
|
@@ -439,7 +775,7 @@ export class BasicCrawler {
|
|
|
439
775
|
mostCommonErrors: this.stats.errorTracker.getMostPopularErrors(3).map(prettify),
|
|
440
776
|
});
|
|
441
777
|
}
|
|
442
|
-
const client =
|
|
778
|
+
const client = serviceLocator.getStorageBackend();
|
|
443
779
|
if (client.teardown) {
|
|
444
780
|
let finished = false;
|
|
445
781
|
setTimeout(() => {
|
|
@@ -451,7 +787,7 @@ export class BasicCrawler {
|
|
|
451
787
|
finished = true;
|
|
452
788
|
}
|
|
453
789
|
periodicLogger.stop();
|
|
454
|
-
|
|
790
|
+
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' });
|
|
455
791
|
this.running = false;
|
|
456
792
|
this.hasFinishedBefore = true;
|
|
457
793
|
}
|
|
@@ -461,29 +797,162 @@ export class BasicCrawler {
|
|
|
461
797
|
* Gracefully stops the current run of the crawler.
|
|
462
798
|
*
|
|
463
799
|
* All the tasks active at the time of calling this method will be allowed to finish.
|
|
800
|
+
*
|
|
801
|
+
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
464
802
|
*/
|
|
465
|
-
stop(
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
.then(() => this.log.info(message))
|
|
472
|
-
.catch((err) => {
|
|
473
|
-
this.log.error('An error occurred when stopping the crawler:', err);
|
|
474
|
-
});
|
|
803
|
+
stop(reason = 'The crawler has been gracefully stopped.') {
|
|
804
|
+
if (this.unexpectedStop) {
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
this.log.info(reason);
|
|
808
|
+
this.unexpectedStop = true;
|
|
475
809
|
}
|
|
810
|
+
/**
|
|
811
|
+
* Stops dispatching new requests, letting the in-progress ones finish. Resolves once they have settled, or rejects
|
|
812
|
+
* after `timeoutSecs` if they take too long. Unlike {@link BasicCrawler.stop|`stop()`}, this does not end the
|
|
813
|
+
* run — {@link BasicCrawler.run|`run()`} stays pending until {@link BasicCrawler.resume|`resume()`}.
|
|
814
|
+
*
|
|
815
|
+
* > *NOTE:* The {@link BasicCrawler.concurrencySystem|concurrency system} keeps monitoring and autoscaling
|
|
816
|
+
* throughout, since a shared one may still be serving other crawlers.
|
|
817
|
+
*/
|
|
818
|
+
async pause(timeoutSecs) {
|
|
819
|
+
if (!this.autoscaledPool) {
|
|
820
|
+
this.log.warning('Cannot pause a crawler that is not running.');
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
await this.autoscaledPool.pause(timeoutSecs);
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Resumes a run suspended with {@link BasicCrawler.pause|`pause()`}, letting the crawler dispatch requests
|
|
827
|
+
* again. A no-op on a crawler that is not paused.
|
|
828
|
+
*/
|
|
829
|
+
resume() {
|
|
830
|
+
if (!this.autoscaledPool) {
|
|
831
|
+
this.log.warning('Cannot resume a crawler that is not running.');
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
this.autoscaledPool.resume();
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
|
|
838
|
+
* if none has been configured or opened yet.
|
|
839
|
+
*/
|
|
840
|
+
async getRequestManager() {
|
|
841
|
+
if (!this.requestManager) {
|
|
842
|
+
this.requestManager = await this.openOwnedRequestQueue();
|
|
843
|
+
}
|
|
844
|
+
// Apply the processing-time hint here (an async lifecycle point) rather than in the constructor,
|
|
845
|
+
// now that `setExpectedRequestProcessingTimeSecs` is async. The hint is raise-only and idempotent,
|
|
846
|
+
// but guard so we do not re-issue it on every call.
|
|
847
|
+
if (!this.requestManagerTimeoutsApplied) {
|
|
848
|
+
this.requestManagerTimeoutsApplied = true;
|
|
849
|
+
await this.applyRequestManagerTimeouts(this.requestManager);
|
|
850
|
+
}
|
|
851
|
+
return this.requestManager;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
|
|
855
|
+
* crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
|
|
856
|
+
*/
|
|
476
857
|
async getRequestQueue() {
|
|
477
|
-
|
|
478
|
-
|
|
858
|
+
return this.getRequestManager();
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Opens the default {@link RequestQueue}, applies the crawler's timeouts to it and records it as the
|
|
862
|
+
* crawler-owned queue (so it gets purged between repeated `run()` calls).
|
|
863
|
+
* @private
|
|
864
|
+
*/
|
|
865
|
+
async openOwnedRequestQueue() {
|
|
866
|
+
// The first crawler instance uses the default queue (null identifier);
|
|
867
|
+
// subsequent instances get their own queue via a unique alias so they don't collide.
|
|
868
|
+
const identifier = this.identity.instanceIndex === 0 ? null : { alias: `__default_${this.identity.id}__` };
|
|
869
|
+
const requestQueue = await RequestQueue.open(identifier, { configuration: serviceLocator.getConfiguration() });
|
|
870
|
+
return this.ownedRequestQueue.set(requestQueue);
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Tells a request manager how long we expect to hold a fetched request, so that one backed by a
|
|
874
|
+
* locking storage backend keeps it reserved for slightly longer than the request handler timeout
|
|
875
|
+
* (with some padding for overhead), but never for less than a minute. This prevents a long-running
|
|
876
|
+
* request from being handed out a second time while it is still being processed — and it works
|
|
877
|
+
* regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
|
|
878
|
+
*/
|
|
879
|
+
async applyRequestManagerTimeouts(requestManager) {
|
|
880
|
+
// A router route may hold a request for longer than the crawler's own timeout, and we cannot know
|
|
881
|
+
// which routes a run will hit, so reserve for the longest one any route asked for. The hint is
|
|
882
|
+
// raise-only, so erring high here is safe.
|
|
883
|
+
const maxRouteTimeoutSecs = this.requestHandler.getMaxTimeoutSecs?.() ?? 0;
|
|
884
|
+
const handlerTimeoutSecs = Math.max(this.requestHandlerTimeoutMillis / 1000, maxRouteTimeoutSecs);
|
|
885
|
+
await requestManager.setExpectedRequestProcessingTimeSecs?.(Math.max(handlerTimeoutSecs + 5, 60));
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
|
|
889
|
+
* for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
|
|
890
|
+
* mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
|
|
891
|
+
* the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
|
|
892
|
+
* `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
|
|
893
|
+
*/
|
|
894
|
+
async validateRequestUserData(source) {
|
|
895
|
+
if (typeof source === 'string') {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const getSchema = this.requestHandler.getSchema;
|
|
899
|
+
if (typeof getSchema !== 'function') {
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
// Resolve the label via its public accessors only — the top-level `label` of a `RequestOptions` or the
|
|
903
|
+
// `Request.label` getter — rather than reaching into `userData`, where the request happens to store it.
|
|
904
|
+
const target = source;
|
|
905
|
+
const schema = getSchema(target.label);
|
|
906
|
+
if (!schema) {
|
|
907
|
+
return;
|
|
479
908
|
}
|
|
480
|
-
|
|
481
|
-
|
|
909
|
+
// Store the parsed value rather than the raw input, so the queue holds the same coerced `userData` the
|
|
910
|
+
// handler will see. Assigning through a `Request` instance's setter keeps its internal `__crawlee` meta.
|
|
911
|
+
target.userData = await validateUserData(target.label, schema, target.userData ?? {});
|
|
482
912
|
}
|
|
483
913
|
async useState(defaultValue = {}) {
|
|
484
|
-
const kvs = await KeyValueStore.open(null, {
|
|
914
|
+
const kvs = await KeyValueStore.open(null, { configuration: serviceLocator.getConfiguration() });
|
|
915
|
+
if (this.identity.hasExplicitId) {
|
|
916
|
+
const stateKey = `${BasicCrawler.CRAWLEE_STATE_KEY}_${this.identity.id}`;
|
|
917
|
+
return kvs.getAutoSavedValue(stateKey, defaultValue);
|
|
918
|
+
}
|
|
919
|
+
BasicCrawler.useStateAnonymousIndices.add(this.identity.instanceIndex);
|
|
920
|
+
if (BasicCrawler.useStateAnonymousIndices.size > 1) {
|
|
921
|
+
serviceLocator
|
|
922
|
+
.getLogger()
|
|
923
|
+
.warningOnce('Multiple crawler instances are calling useState() without an explicit `id` option. \n' +
|
|
924
|
+
'This means they will share the same state object, which is likely unintended. \n' +
|
|
925
|
+
'To fix this, provide a unique `id` option to each crawler instance. \n' +
|
|
926
|
+
'Example: new BasicCrawler({ id: "my-crawler-1", ... })');
|
|
927
|
+
}
|
|
485
928
|
return kvs.getAutoSavedValue(BasicCrawler.CRAWLEE_STATE_KEY, defaultValue);
|
|
486
929
|
}
|
|
930
|
+
async getPendingRequestCountApproximation() {
|
|
931
|
+
return (await this.requestManager?.getPendingCount()) ?? 0;
|
|
932
|
+
}
|
|
933
|
+
async calculateEnqueuedRequestLimit(explicitLimit) {
|
|
934
|
+
if (this.maxRequestsPerCrawl === undefined) {
|
|
935
|
+
return explicitLimit;
|
|
936
|
+
}
|
|
937
|
+
const limit = Math.max(0, this.maxRequestsPerCrawl - this.handledRequestsCount - (await this.getPendingRequestCountApproximation()));
|
|
938
|
+
return Math.min(limit, explicitLimit ?? Infinity);
|
|
939
|
+
}
|
|
940
|
+
async handleSkippedRequest(options) {
|
|
941
|
+
if (options.reason === 'limit') {
|
|
942
|
+
this.logOncePerRun('maxRequestsPerCrawl', 'The number of requests enqueued by the crawler reached the maxRequestsPerCrawl limit of ' +
|
|
943
|
+
`${this.maxRequestsPerCrawl} requests and no further requests will be added.`);
|
|
944
|
+
}
|
|
945
|
+
if (options.reason === 'depth') {
|
|
946
|
+
this.logOncePerRun('maxCrawlDepth', `The crawler reached the maxCrawlDepth limit of ${this.maxCrawlDepth} and no further requests will be enqueued.`);
|
|
947
|
+
}
|
|
948
|
+
await this.onSkippedRequest?.(options);
|
|
949
|
+
}
|
|
950
|
+
logOncePerRun(key, message) {
|
|
951
|
+
if (!this.loggedPerRun.has(key)) {
|
|
952
|
+
this.log.info(message);
|
|
953
|
+
this.loggedPerRun.add(key);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
487
956
|
/**
|
|
488
957
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
489
958
|
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
|
|
@@ -496,46 +965,73 @@ export class BasicCrawler {
|
|
|
496
965
|
* @param options Options for the request queue
|
|
497
966
|
*/
|
|
498
967
|
async addRequests(requests, options = {}) {
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
const
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
968
|
+
await this.getRequestManager();
|
|
969
|
+
const requestLimit = await this.calculateEnqueuedRequestLimit();
|
|
970
|
+
const skippedBecauseOfRobots = new Set();
|
|
971
|
+
const skippedBecauseOfMaxCrawlDepth = new Set();
|
|
972
|
+
const isAllowedBasedOnRobotsTxtFile = this.isAllowedBasedOnRobotsTxtFile.bind(this);
|
|
973
|
+
const maxCrawlDepth = this.maxCrawlDepth;
|
|
974
|
+
const validateRequestUserData = this.validateRequestUserData.bind(this);
|
|
975
|
+
ow(requests, ow.object
|
|
976
|
+
.is((value) => isIterable(value) || isAsyncIterable(value))
|
|
977
|
+
.message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`));
|
|
978
|
+
async function* filteredRequests() {
|
|
979
|
+
for await (const request of requests) {
|
|
980
|
+
const url = typeof request === 'string' ? request : request.url;
|
|
981
|
+
if (maxCrawlDepth !== undefined && request.crawlDepth > maxCrawlDepth) {
|
|
982
|
+
skippedBecauseOfMaxCrawlDepth.add(url);
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
if (await isAllowedBasedOnRobotsTxtFile(url)) {
|
|
986
|
+
await validateRequestUserData(request);
|
|
987
|
+
yield request;
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
skippedBecauseOfRobots.add(url);
|
|
991
|
+
}
|
|
513
992
|
}
|
|
514
993
|
}
|
|
515
|
-
|
|
994
|
+
const result = await this.requestManager.addRequestsBatched(filteredRequests(), {
|
|
995
|
+
...options,
|
|
996
|
+
maxNewRequests: requestLimit,
|
|
997
|
+
});
|
|
998
|
+
// Report requests skipped due to the maxNewRequests budget (i.e. maxRequestsPerCrawl limit)
|
|
999
|
+
const skippedBecauseOfLimit = result.requestsOverLimit ?? [];
|
|
1000
|
+
if (skippedBecauseOfRobots.size > 0) {
|
|
516
1001
|
this.log.warning(`Some requests were skipped because they were disallowed based on the robots.txt file`, {
|
|
517
|
-
skipped: [...
|
|
1002
|
+
skipped: [...skippedBecauseOfRobots],
|
|
518
1003
|
});
|
|
519
|
-
if (this.onSkippedRequest) {
|
|
520
|
-
await Promise.all([...skipped].map((url) => {
|
|
521
|
-
return this.onSkippedRequest({ url, reason: 'robotsTxt' });
|
|
522
|
-
}));
|
|
523
|
-
}
|
|
524
1004
|
}
|
|
525
|
-
|
|
1005
|
+
if (skippedBecauseOfRobots.size > 0 ||
|
|
1006
|
+
skippedBecauseOfLimit.length > 0 ||
|
|
1007
|
+
skippedBecauseOfMaxCrawlDepth.size > 0) {
|
|
1008
|
+
await Promise.all([...skippedBecauseOfRobots]
|
|
1009
|
+
.map((url) => {
|
|
1010
|
+
return this.handleSkippedRequest({ url, reason: 'robotsTxt' });
|
|
1011
|
+
})
|
|
1012
|
+
.concat(skippedBecauseOfLimit.map((request) => {
|
|
1013
|
+
const url = typeof request === 'string' ? request : request.url;
|
|
1014
|
+
return this.handleSkippedRequest({ url, reason: 'limit' });
|
|
1015
|
+
}), [...skippedBecauseOfMaxCrawlDepth].map((url) => {
|
|
1016
|
+
return this.handleSkippedRequest({ url, reason: 'depth' });
|
|
1017
|
+
})));
|
|
1018
|
+
}
|
|
1019
|
+
return result;
|
|
526
1020
|
}
|
|
527
1021
|
/**
|
|
528
1022
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
529
1023
|
*/
|
|
530
|
-
async pushData(data,
|
|
531
|
-
const dataset = await this.getDataset(
|
|
1024
|
+
async pushData(data, datasetIdentifier) {
|
|
1025
|
+
const dataset = await this.getDataset(datasetIdentifier);
|
|
532
1026
|
return dataset.pushData(data);
|
|
533
1027
|
}
|
|
534
1028
|
/**
|
|
535
1029
|
* Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
|
|
536
1030
|
*/
|
|
537
|
-
async getDataset(
|
|
538
|
-
return Dataset.open(
|
|
1031
|
+
async getDataset(identifier) {
|
|
1032
|
+
return Dataset.open(identifier, {
|
|
1033
|
+
configuration: serviceLocator.getConfiguration(),
|
|
1034
|
+
});
|
|
539
1035
|
}
|
|
540
1036
|
/**
|
|
541
1037
|
* Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
|
|
@@ -550,8 +1046,9 @@ export class BasicCrawler {
|
|
|
550
1046
|
*/
|
|
551
1047
|
async exportData(path, format, options) {
|
|
552
1048
|
const supportedFormats = ['json', 'csv'];
|
|
553
|
-
|
|
554
|
-
|
|
1049
|
+
const formatMatch = /\.(json|csv)$/i.exec(path);
|
|
1050
|
+
if (!format && formatMatch) {
|
|
1051
|
+
format = formatMatch[1].toLowerCase();
|
|
555
1052
|
}
|
|
556
1053
|
if (!format) {
|
|
557
1054
|
throw new Error(`Failed to infer format from the path: '${path}'. Supported formats: ${supportedFormats.join(', ')}`);
|
|
@@ -562,7 +1059,21 @@ export class BasicCrawler {
|
|
|
562
1059
|
const dataset = await this.getDataset();
|
|
563
1060
|
const items = await dataset.export(options);
|
|
564
1061
|
if (format === 'csv') {
|
|
565
|
-
|
|
1062
|
+
let value;
|
|
1063
|
+
if (items.length === 0) {
|
|
1064
|
+
value = '';
|
|
1065
|
+
}
|
|
1066
|
+
else {
|
|
1067
|
+
const keys = options?.collectAllKeys
|
|
1068
|
+
? Array.from(new Set(items.flatMap(Object.keys)))
|
|
1069
|
+
: Object.keys(items[0]);
|
|
1070
|
+
value = stringify([
|
|
1071
|
+
keys,
|
|
1072
|
+
...items.map((item) => {
|
|
1073
|
+
return keys.map((k) => item[k]);
|
|
1074
|
+
}),
|
|
1075
|
+
]);
|
|
1076
|
+
}
|
|
566
1077
|
await ensureDir(dirname(path));
|
|
567
1078
|
await writeFile(path, value);
|
|
568
1079
|
this.log.info(`Export to ${path} finished!`);
|
|
@@ -574,32 +1085,91 @@ export class BasicCrawler {
|
|
|
574
1085
|
}
|
|
575
1086
|
return items;
|
|
576
1087
|
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Initializes the crawler.
|
|
1090
|
+
*/
|
|
577
1091
|
async _init() {
|
|
578
|
-
|
|
579
|
-
|
|
1092
|
+
const eventManager = serviceLocator.getEventManager();
|
|
1093
|
+
if (!eventManager.isInitialized()) {
|
|
1094
|
+
await eventManager.init();
|
|
580
1095
|
this._closeEvents = true;
|
|
581
1096
|
}
|
|
582
|
-
//
|
|
583
|
-
//
|
|
584
|
-
// (
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
1097
|
+
// Warn once at startup if the internal timeout is shorter than the phases it is meant to outlast. It is
|
|
1098
|
+
// floored per request so it will not actually cut them short, but the configured value is then effectively
|
|
1099
|
+
// ignored, which is worth flagging. Checked here (not in the constructor) because a subclass sets its
|
|
1100
|
+
// navigation timeout only after `super()`.
|
|
1101
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.resolveRequestHandlerTimeoutMillis(undefined);
|
|
1102
|
+
if (this.internalTimeoutMillis < phasesMillis) {
|
|
1103
|
+
this.log.warning(`CRAWLEE_INTERNAL_TIMEOUT (${this.internalTimeoutMillis / 1000}s) is shorter than the navigation ` +
|
|
1104
|
+
`and request handler timeouts combined (${phasesMillis / 1000}s); it will be raised per request ` +
|
|
1105
|
+
`so it does not cut them short.`);
|
|
1106
|
+
}
|
|
1107
|
+
// An owned governor is rebuilt (and started) for every run, so it always starts from a clean slate — stale
|
|
1108
|
+
// resource snapshots or a previous run's scaled desired concurrency would otherwise distort this run's
|
|
1109
|
+
// scaling. An injected one is long-lived and its lifecycle belongs to the caller.
|
|
1110
|
+
this.concurrencySystemDep = this.resolveConcurrencySystem();
|
|
1111
|
+
await this.concurrencySystemDep.ifOwned((system) => system.start());
|
|
1112
|
+
this.autoscaledPool = new AutoscaledPool({
|
|
1113
|
+
...this.taskLoopOptions,
|
|
1114
|
+
concurrencySystem: this.concurrencySystemDep.value,
|
|
1115
|
+
consumer: this.identity,
|
|
1116
|
+
});
|
|
1117
|
+
await this.getRequestManager();
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* The navigation timeout (pre-navigation hooks, navigation, and post-navigation hooks) in milliseconds, used
|
|
1121
|
+
* to size the internal request timeout. `BasicCrawler` has no navigation phase, so this is 0; the HTTP and
|
|
1122
|
+
* browser crawlers override it with their `navigationTimeoutSecs`.
|
|
1123
|
+
*/
|
|
1124
|
+
getNavigationTimeoutMillis() {
|
|
1125
|
+
return 0;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Races the request against the internal timeout (see {@link raceWithTimeout}), sized to outlast the phases
|
|
1129
|
+
* that have their own timeout - the navigation, its hooks, and the request handler - so a legitimately slow
|
|
1130
|
+
* request, a per-route override, or a low `CRAWLEE_INTERNAL_TIMEOUT` is not cut short mid-phase. It takes
|
|
1131
|
+
* whichever is larger: the configured internal timeout, or this request's combined phase budget.
|
|
1132
|
+
*/
|
|
1133
|
+
async withRequestTimeout(crawlingContext, work) {
|
|
1134
|
+
const { request } = crawlingContext;
|
|
1135
|
+
const phasesMillis = this.getNavigationTimeoutMillis() + this.resolveRequestHandlerTimeoutMillis(request.label);
|
|
1136
|
+
const timeoutMillis = Math.max(this.internalTimeoutMillis, phasesMillis);
|
|
1137
|
+
await raceWithTimeout(crawlingContext, work, { timeoutMillis, requestId: request.id });
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* The request handler timeout for a request with the given route label. A router route may override the
|
|
1141
|
+
* crawler's own `requestHandlerTimeoutSecs`; anything else falls back to `fallbackMillis`.
|
|
1142
|
+
*
|
|
1143
|
+
* @param label The request's route label, or `undefined` for the default route / no specific request.
|
|
1144
|
+
* @param fallbackMillis Timeout to use when no route overrides it.
|
|
1145
|
+
*/
|
|
1146
|
+
resolveRequestHandlerTimeoutMillis(label, fallbackMillis = this.requestHandlerTimeoutMillis) {
|
|
1147
|
+
return this.getRouteTimeoutMillis(label) ?? fallbackMillis;
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* The timeout the router route with the given label asked for, or `undefined` when it did not override one
|
|
1151
|
+
* (or the request handler is not a router at all).
|
|
1152
|
+
*/
|
|
1153
|
+
getRouteTimeoutMillis(label) {
|
|
1154
|
+
const getTimeoutSecs = this.requestHandler.getTimeoutSecs;
|
|
1155
|
+
if (typeof getTimeoutSecs !== 'function') {
|
|
1156
|
+
return undefined;
|
|
590
1157
|
}
|
|
591
|
-
|
|
1158
|
+
const timeoutSecs = getTimeoutSecs(label);
|
|
1159
|
+
return timeoutSecs === undefined ? undefined : timeoutSecs * 1000;
|
|
592
1160
|
}
|
|
593
|
-
async
|
|
594
|
-
|
|
1161
|
+
async runRequestHandler(crawlingContext) {
|
|
1162
|
+
const timeoutMillis = this.resolveRequestHandlerTimeoutMillis(crawlingContext.request.label);
|
|
1163
|
+
await addTimeoutToPromise(async () => this.requestHandler(crawlingContext), timeoutMillis, `requestHandler timed out after ${timeoutMillis / 1000} seconds (${crawlingContext.request.id}).`);
|
|
595
1164
|
}
|
|
596
1165
|
/**
|
|
597
1166
|
* Handles blocked request
|
|
598
1167
|
*/
|
|
599
|
-
_throwOnBlockedRequest(
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
1168
|
+
_throwOnBlockedRequest(statusCode) {
|
|
1169
|
+
if (this.retryOnBlocked)
|
|
1170
|
+
return;
|
|
1171
|
+
if (this.blockedStatusCodes.has(statusCode)) {
|
|
1172
|
+
throw new SessionError(`Request blocked - received ${statusCode} status code.`);
|
|
603
1173
|
}
|
|
604
1174
|
}
|
|
605
1175
|
async isAllowedBasedOnRobotsTxtFile(url) {
|
|
@@ -607,7 +1177,8 @@ export class BasicCrawler {
|
|
|
607
1177
|
return true;
|
|
608
1178
|
}
|
|
609
1179
|
const robotsTxtFile = await this.getRobotsTxtFileForUrl(url);
|
|
610
|
-
|
|
1180
|
+
const userAgent = typeof this.respectRobotsTxtFile === 'object' ? this.respectRobotsTxtFile?.userAgent : '*';
|
|
1181
|
+
return !robotsTxtFile || robotsTxtFile.isAllowed(url, userAgent);
|
|
611
1182
|
}
|
|
612
1183
|
async getRobotsTxtFileForUrl(url) {
|
|
613
1184
|
if (!this.respectRobotsTxtFile) {
|
|
@@ -619,7 +1190,7 @@ export class BasicCrawler {
|
|
|
619
1190
|
if (cachedRobotsTxtFile) {
|
|
620
1191
|
return cachedRobotsTxtFile;
|
|
621
1192
|
}
|
|
622
|
-
const robotsTxtFile = await RobotsTxtFile.find(url);
|
|
1193
|
+
const robotsTxtFile = await RobotsTxtFile.find(url, { logger: this.log });
|
|
623
1194
|
this.robotsTxtFileCache.add(origin, robotsTxtFile);
|
|
624
1195
|
return robotsTxtFile;
|
|
625
1196
|
}
|
|
@@ -628,7 +1199,7 @@ export class BasicCrawler {
|
|
|
628
1199
|
return undefined;
|
|
629
1200
|
}
|
|
630
1201
|
}
|
|
631
|
-
async
|
|
1202
|
+
async pauseOnMigration() {
|
|
632
1203
|
if (this.autoscaledPool) {
|
|
633
1204
|
// if run wasn't called, this is going to crash
|
|
634
1205
|
await this.autoscaledPool.pause(SAFE_MIGRATION_WAIT_MILLIS).catch((err) => {
|
|
@@ -641,14 +1212,16 @@ export class BasicCrawler {
|
|
|
641
1212
|
}
|
|
642
1213
|
});
|
|
643
1214
|
}
|
|
644
|
-
const
|
|
645
|
-
if
|
|
646
|
-
|
|
1215
|
+
const requestManagerPersistPromise = (async () => {
|
|
1216
|
+
// The request manager persists its read-only loader's state, if it has one that supports persistence
|
|
1217
|
+
// (e.g. a tandem wrapping a `RequestList`). For a plain `RequestQueue`, this is a no-op.
|
|
1218
|
+
if (this.requestManager?.persistState) {
|
|
1219
|
+
if (await this.requestManager.isFinished())
|
|
647
1220
|
return;
|
|
648
|
-
await this.
|
|
1221
|
+
await this.requestManager.persistState().catch((err) => {
|
|
649
1222
|
if (err.message.includes('Cannot persist state.')) {
|
|
650
1223
|
this.log.error("The crawler attempted to persist its request list's state and failed due to missing or " +
|
|
651
|
-
'invalid
|
|
1224
|
+
'invalid configuration. Make sure to use either RequestList.open() or the "stateKeyPrefix" option of RequestList ' +
|
|
652
1225
|
'constructor to ensure your crawling state is persisted through host migrations and restarts.');
|
|
653
1226
|
}
|
|
654
1227
|
else {
|
|
@@ -658,39 +1231,17 @@ export class BasicCrawler {
|
|
|
658
1231
|
});
|
|
659
1232
|
}
|
|
660
1233
|
})();
|
|
661
|
-
await Promise.all([
|
|
1234
|
+
await Promise.all([requestManagerPersistPromise, this.stats.persistState()]);
|
|
662
1235
|
}
|
|
663
1236
|
/**
|
|
664
|
-
* Fetches request
|
|
665
|
-
* and RequestQueue is present then enqueues it to the queue first.
|
|
1237
|
+
* Fetches the next request to process from the underlying request provider.
|
|
666
1238
|
*/
|
|
667
|
-
async
|
|
668
|
-
if (
|
|
669
|
-
|
|
670
|
-
}
|
|
671
|
-
const request = await this.requestList.fetchNextRequest();
|
|
672
|
-
if (!this.requestQueue)
|
|
673
|
-
return request;
|
|
674
|
-
if (!request)
|
|
675
|
-
return this.requestQueue.fetchNextRequest();
|
|
676
|
-
try {
|
|
677
|
-
await this.requestQueue.addRequest(request, { forefront: true });
|
|
678
|
-
}
|
|
679
|
-
catch (err) {
|
|
680
|
-
// If requestQueue.addRequest() fails here then we must reclaim it back to
|
|
681
|
-
// the RequestList because probably it's not yet in the queue!
|
|
682
|
-
this.log.error('Adding of request from the RequestList to the RequestQueue failed, reclaiming request back to the list.', { request });
|
|
683
|
-
await this.requestList.reclaimRequest(request);
|
|
684
|
-
return null;
|
|
1239
|
+
async fetchNextRequest() {
|
|
1240
|
+
if (this.requestManager === undefined) {
|
|
1241
|
+
throw new Error(`fetchNextRequest called on an uninitialized crawler`);
|
|
685
1242
|
}
|
|
686
|
-
|
|
687
|
-
return this.requestQueue.fetchNextRequest();
|
|
1243
|
+
return this.requestManager.fetchNextRequest();
|
|
688
1244
|
}
|
|
689
|
-
/**
|
|
690
|
-
* Executed when `errorHandler` finishes or the request is successful.
|
|
691
|
-
* Can be used to clean up orphaned browser pages.
|
|
692
|
-
*/
|
|
693
|
-
async _cleanupContext(_crawlingContext) { }
|
|
694
1245
|
/**
|
|
695
1246
|
* Delays processing of the request based on the `sameDomainDelaySecs` option,
|
|
696
1247
|
* adding it back to the queue after the timeout passes. Returns `true` if the request
|
|
@@ -707,149 +1258,152 @@ export class BasicCrawler {
|
|
|
707
1258
|
this.domainAccessedTime.set(domain, now);
|
|
708
1259
|
return false;
|
|
709
1260
|
}
|
|
710
|
-
if (source instanceof RequestQueueV1) {
|
|
711
|
-
// eslint-disable-next-line dot-notation
|
|
712
|
-
source['inProgress']?.delete(request.id);
|
|
713
|
-
}
|
|
714
1261
|
const delay = lastAccessTime + this.sameDomainDelayMillis - now;
|
|
715
1262
|
this.log.debug(`Request ${request.url} (${request.id}) will be reclaimed after ${delay} milliseconds due to same domain delay`);
|
|
716
1263
|
setTimeout(async () => {
|
|
717
1264
|
this.log.debug(`Adding request ${request.url} (${request.id}) back to the queue`);
|
|
718
|
-
if (source instanceof RequestQueueV1) {
|
|
719
|
-
// eslint-disable-next-line dot-notation
|
|
720
|
-
source['inProgress'].add(request.id);
|
|
721
|
-
}
|
|
722
1265
|
await source.reclaimRequest(request, { forefront: request.userData?.__crawlee?.forefront });
|
|
723
1266
|
}, delay);
|
|
724
1267
|
return true;
|
|
725
1268
|
}
|
|
726
|
-
/**
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
let request;
|
|
733
|
-
let session;
|
|
734
|
-
await this._timeoutAndRetry(async () => {
|
|
735
|
-
request = await this._fetchNextRequest();
|
|
736
|
-
}, this.internalTimeoutMillis, `Fetching next request timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
737
|
-
tryCancel();
|
|
738
|
-
if (this.useSessionPool) {
|
|
739
|
-
await this._timeoutAndRetry(async () => {
|
|
740
|
-
session = await this.sessionPool.getSession();
|
|
741
|
-
}, this.internalTimeoutMillis, `Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
742
|
-
}
|
|
743
|
-
tryCancel();
|
|
744
|
-
if (!request || this.delayRequest(request, source)) {
|
|
1269
|
+
/** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
|
|
1270
|
+
async handleRequest(crawlingContext, requestSource, request) {
|
|
1271
|
+
// An earlier phase we cannot cancel (e.g. a slow `extendContext`) may have run past the internal timeout,
|
|
1272
|
+
// which already failed the request in `runTaskFunction`. Bail before running the handler so it does not
|
|
1273
|
+
// execute (and re-report) on top of a request the crawler has already moved past.
|
|
1274
|
+
if (crawlingContext[timeoutExpiredKey]?.()) {
|
|
745
1275
|
return;
|
|
746
1276
|
}
|
|
747
|
-
if (!(await this.isAllowedBasedOnRobotsTxtFile(request.url))) {
|
|
748
|
-
this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`);
|
|
749
|
-
request.state = RequestState.SKIPPED;
|
|
750
|
-
request.noRetry = true;
|
|
751
|
-
await source.markRequestHandled(request);
|
|
752
|
-
await this.onSkippedRequest?.({
|
|
753
|
-
url: request.url,
|
|
754
|
-
reason: 'robotsTxt',
|
|
755
|
-
});
|
|
756
|
-
return;
|
|
757
|
-
}
|
|
758
|
-
// Reset loadedUrl so an old one is not carried over to retries.
|
|
759
|
-
request.loadedUrl = undefined;
|
|
760
1277
|
const statisticsId = request.id || request.uniqueKey;
|
|
761
|
-
this.stats.startJob(statisticsId);
|
|
762
|
-
// Shared crawling context
|
|
763
|
-
// @ts-expect-error
|
|
764
|
-
// All missing properties (that extend CrawlingContext) are set dynamically,
|
|
765
|
-
// but TS does not know that, so otherwise it would throw when compiling.
|
|
766
|
-
const crawlingContext = {
|
|
767
|
-
id: cryptoRandomObjectId(10),
|
|
768
|
-
crawler: this,
|
|
769
|
-
log: this.log,
|
|
770
|
-
request,
|
|
771
|
-
session,
|
|
772
|
-
enqueueLinks: async (options) => {
|
|
773
|
-
return enqueueLinks({
|
|
774
|
-
// specify the RQ first to allow overriding it
|
|
775
|
-
requestQueue: await this.getRequestQueue(),
|
|
776
|
-
robotsTxtFile: await this.getRobotsTxtFileForUrl(request.url),
|
|
777
|
-
onSkippedRequest: this.onSkippedRequest,
|
|
778
|
-
...options,
|
|
779
|
-
});
|
|
780
|
-
},
|
|
781
|
-
addRequests: this.addRequests.bind(this),
|
|
782
|
-
pushData: this.pushData.bind(this),
|
|
783
|
-
useState: this.useState.bind(this),
|
|
784
|
-
sendRequest: createSendRequest(this.httpClient, request, session, () => crawlingContext.proxyInfo?.url),
|
|
785
|
-
getKeyValueStore: async (idOrName) => KeyValueStore.open(idOrName, { config: this.config }),
|
|
786
|
-
};
|
|
787
|
-
this.crawlingContexts.set(crawlingContext.id, crawlingContext);
|
|
788
1278
|
let isRequestLocked = true;
|
|
789
1279
|
try {
|
|
790
1280
|
request.state = RequestState.REQUEST_HANDLER;
|
|
791
|
-
await
|
|
792
|
-
await this.
|
|
793
|
-
isRequestLocked = false; //
|
|
1281
|
+
await this.runRequestHandler(crawlingContext);
|
|
1282
|
+
await this.timeoutAndRetry(async () => requestSource.markRequestAsHandled(request), this.internalTimeoutMillis, `Marking request ${request.url} (${request.id}) as handled timed out after ${this.internalTimeoutMillis / 1e3} seconds.`);
|
|
1283
|
+
isRequestLocked = false; // markRequestAsHandled succeeded and unlocked the request
|
|
794
1284
|
this.stats.finishJob(statisticsId, request.retryCount);
|
|
795
|
-
this.handledRequestsCount++;
|
|
796
1285
|
// reclaim session if request finishes successfully
|
|
797
1286
|
request.state = RequestState.DONE;
|
|
798
|
-
crawlingContext.session
|
|
1287
|
+
crawlingContext.session.markGood();
|
|
799
1288
|
}
|
|
800
|
-
catch (
|
|
1289
|
+
catch (rawError) {
|
|
1290
|
+
const err = this.unwrapError(rawError);
|
|
801
1291
|
try {
|
|
802
1292
|
request.state = RequestState.ERROR_HANDLER;
|
|
803
|
-
await addTimeoutToPromise(async () => this.
|
|
1293
|
+
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.`);
|
|
804
1294
|
if (!(err instanceof CriticalError)) {
|
|
805
|
-
isRequestLocked = false; //
|
|
1295
|
+
isRequestLocked = false; // requestFunctionErrorHandler calls either markRequestAsHandled or reclaimRequest
|
|
806
1296
|
}
|
|
807
1297
|
request.state = RequestState.DONE;
|
|
808
1298
|
}
|
|
809
1299
|
catch (secondaryError) {
|
|
810
|
-
|
|
1300
|
+
const unwrappedSecondaryError = this.unwrapError(secondaryError);
|
|
1301
|
+
if (!unwrappedSecondaryError.triggeredFromUserHandler &&
|
|
811
1302
|
// avoid reprinting the same critical error multiple times, as it will be printed by Nodejs at the end anyway
|
|
812
|
-
!(
|
|
1303
|
+
!(unwrappedSecondaryError instanceof CriticalError)) {
|
|
813
1304
|
const apifySpecific = process.env.APIFY_IS_AT_HOME
|
|
814
1305
|
? `This may have happened due to an internal error of Apify's API or due to a misconfigured crawler.`
|
|
815
1306
|
: '';
|
|
816
|
-
this.log.exception(
|
|
1307
|
+
this.log.exception(unwrappedSecondaryError, 'An exception occurred during handling of failed request. ' +
|
|
817
1308
|
`This places the crawler and its underlying storages into an unknown state and crawling will be terminated. ${apifySpecific}`);
|
|
818
1309
|
}
|
|
819
1310
|
request.state = RequestState.ERROR;
|
|
820
|
-
throw
|
|
1311
|
+
throw unwrappedSecondaryError;
|
|
1312
|
+
}
|
|
1313
|
+
// decrease the session score if the request fails (but the error handler did not throw);
|
|
1314
|
+
// skip when the error is a SessionError, which already retired the session
|
|
1315
|
+
if (!(err instanceof SessionError)) {
|
|
1316
|
+
crawlingContext.session.markBad();
|
|
821
1317
|
}
|
|
822
|
-
// decrease the session score if the request fails (but the error handler did not throw)
|
|
823
|
-
crawlingContext.session?.markBad();
|
|
824
1318
|
}
|
|
825
1319
|
finally {
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
//
|
|
829
|
-
if (isRequestLocked &&
|
|
1320
|
+
// Safety net - return the request to the queue if nobody managed to mark it as handled
|
|
1321
|
+
// or reclaim it before (e.g. after a CriticalError). Reclaiming a request that is no longer
|
|
1322
|
+
// in progress is a harmless no-op on the storage backend.
|
|
1323
|
+
if (isRequestLocked && requestSource instanceof RequestQueue) {
|
|
830
1324
|
try {
|
|
831
|
-
await
|
|
1325
|
+
await requestSource.reclaimRequest(request);
|
|
832
1326
|
}
|
|
833
1327
|
catch {
|
|
834
|
-
//
|
|
1328
|
+
// The request was never in progress, or could not be reclaimed. Either way it's fine.
|
|
835
1329
|
}
|
|
836
1330
|
}
|
|
837
1331
|
}
|
|
838
1332
|
}
|
|
839
1333
|
/**
|
|
840
|
-
*
|
|
1334
|
+
* Wrapper around the crawling context's `enqueueLinks` method:
|
|
1335
|
+
* - Injects `crawlDepth` to each request being added based on the crawling context request.
|
|
1336
|
+
* - Provides defaults for the `enqueueLinks` options based on the crawler configuration.
|
|
1337
|
+
* - These options can be overridden by the user.
|
|
1338
|
+
* @internal
|
|
1339
|
+
*/
|
|
1340
|
+
async enqueueLinksWithCrawlDepth(options, request, requestManager) {
|
|
1341
|
+
const transformRequestFunctionWrapper = (requestOptions) => {
|
|
1342
|
+
requestOptions.crawlDepth = request.crawlDepth + 1;
|
|
1343
|
+
if (this.maxCrawlDepth !== undefined && requestOptions.crawlDepth > this.maxCrawlDepth) {
|
|
1344
|
+
// Setting `skippedReason` before returning `false` ensures that `reportSkippedRequests`
|
|
1345
|
+
// reports `'depth'` as the reason (via `request.skippedReason ?? reason` fallback),
|
|
1346
|
+
// rather than the generic `'transform'` reason.
|
|
1347
|
+
requestOptions.skippedReason = 'depth';
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
// After injecting the crawlDepth, we call the user-provided transform function, if there is one.
|
|
1351
|
+
return options.transformRequestFunction?.(requestOptions) ?? requestOptions;
|
|
1352
|
+
};
|
|
1353
|
+
// Create a request-scoped callback that logs enqueueLimit once per request handler call
|
|
1354
|
+
// Only log if an explicit limit was passed to enqueueLinks (not the internal maxRequestsPerCrawl-derived limit)
|
|
1355
|
+
let loggedEnqueueLimitForThisRequest = false;
|
|
1356
|
+
const onSkippedRequest = async (skippedOptions) => {
|
|
1357
|
+
if (skippedOptions.reason === 'enqueueLimit') {
|
|
1358
|
+
if (!loggedEnqueueLimitForThisRequest && options.limit !== undefined) {
|
|
1359
|
+
this.log.info(`Skipping URLs in the handler for ${request.url} due to the enqueueLinks limit of ${options.limit}.`);
|
|
1360
|
+
loggedEnqueueLimitForThisRequest = true;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
await this.handleSkippedRequest(skippedOptions);
|
|
1364
|
+
};
|
|
1365
|
+
// `enqueueLinks` applies `options.label`/`options.userData` to every newly enqueued request, so a single
|
|
1366
|
+
// validation against the label's schema covers them all (a no-op unless the router declares a schema).
|
|
1367
|
+
await this.validateRequestUserData({ label: options.label, userData: options.userData });
|
|
1368
|
+
return await enqueueLinks({
|
|
1369
|
+
requestManager,
|
|
1370
|
+
robotsTxtFile: await this.getRobotsTxtFileForUrl(request.url),
|
|
1371
|
+
respectRobotsTxtFile: this.respectRobotsTxtFile,
|
|
1372
|
+
onSkippedRequest,
|
|
1373
|
+
limit: await this.calculateEnqueuedRequestLimit(options.limit),
|
|
1374
|
+
// Allow user options to override defaults set above ⤴
|
|
1375
|
+
...options,
|
|
1376
|
+
transformRequestFunction: transformRequestFunctionWrapper,
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Generator function that yields requests injected with the given crawl depth.
|
|
1381
|
+
* @internal
|
|
1382
|
+
*/
|
|
1383
|
+
async *addCrawlDepthRequestGenerator(requests, newRequestDepth) {
|
|
1384
|
+
for await (const request of requests) {
|
|
1385
|
+
if (typeof request === 'string') {
|
|
1386
|
+
yield { url: request, crawlDepth: newRequestDepth };
|
|
1387
|
+
}
|
|
1388
|
+
else {
|
|
1389
|
+
request.crawlDepth ??= newRequestDepth;
|
|
1390
|
+
yield request;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
841
1396
|
* @ignore
|
|
842
1397
|
*/
|
|
843
|
-
async
|
|
1398
|
+
async timeoutAndRetry(handler, timeout, error, maxRetries = 3, retried = 1) {
|
|
844
1399
|
try {
|
|
845
|
-
await addTimeoutToPromise(handler, timeout, error);
|
|
1400
|
+
return await addTimeoutToPromise(handler, timeout, error);
|
|
846
1401
|
}
|
|
847
1402
|
catch (e) {
|
|
848
1403
|
if (retried <= maxRetries) {
|
|
849
1404
|
// we retry on any error, not just timeout
|
|
850
1405
|
this.log.warning(`${e.message} (retrying ${retried}/${maxRetries})`);
|
|
851
|
-
|
|
852
|
-
return;
|
|
1406
|
+
return this.timeoutAndRetry(handler, timeout, error, maxRetries, retried + 1);
|
|
853
1407
|
}
|
|
854
1408
|
throw e;
|
|
855
1409
|
}
|
|
@@ -857,47 +1411,44 @@ export class BasicCrawler {
|
|
|
857
1411
|
/**
|
|
858
1412
|
* Returns true if either RequestList or RequestQueue have a request ready for processing.
|
|
859
1413
|
*/
|
|
860
|
-
async
|
|
861
|
-
|
|
862
|
-
const isRequestListEmpty = this.requestList ? await this.requestList.isEmpty() : true;
|
|
863
|
-
// If RequestList is not empty, task is ready, no reason to check RequestQueue.
|
|
864
|
-
if (!isRequestListEmpty)
|
|
865
|
-
return true;
|
|
866
|
-
// If RequestQueue is not empty, task is ready, return true, otherwise false.
|
|
867
|
-
return this.requestQueue ? !(await this.requestQueue.isEmpty()) : false;
|
|
1414
|
+
async isTaskReadyFunction() {
|
|
1415
|
+
return this.requestManager !== undefined && !(await this.requestManager.isEmpty());
|
|
868
1416
|
}
|
|
869
1417
|
/**
|
|
870
1418
|
* Returns true if both RequestList and RequestQueue have all requests finished.
|
|
871
1419
|
*/
|
|
872
|
-
async
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
1420
|
+
async defaultIsFinishedFunction() {
|
|
1421
|
+
return !this.requestManager || (await this.requestManager.isFinished());
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
1425
|
+
* RequestHandlerError and ContextPipelineInitializationError wrap the actual error.
|
|
1426
|
+
*/
|
|
1427
|
+
unwrapError(error) {
|
|
1428
|
+
if (error instanceof RequestHandlerError ||
|
|
1429
|
+
error instanceof ContextPipelineInitializationError ||
|
|
1430
|
+
error instanceof ContextPipelineCleanupError) {
|
|
1431
|
+
return this.unwrapError(error.cause);
|
|
1432
|
+
}
|
|
1433
|
+
return error;
|
|
885
1434
|
}
|
|
886
1435
|
/**
|
|
887
1436
|
* Handles errors thrown by user provided requestHandler()
|
|
1437
|
+
*
|
|
1438
|
+
* @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
|
|
888
1439
|
*/
|
|
889
|
-
async
|
|
890
|
-
const { request } = crawlingContext;
|
|
1440
|
+
async requestFunctionErrorHandler(error, crawlingContext, request, source) {
|
|
891
1441
|
request.pushErrorMessage(error);
|
|
892
1442
|
if (error instanceof CriticalError) {
|
|
893
1443
|
throw error;
|
|
894
1444
|
}
|
|
895
|
-
const shouldRetryRequest = this.
|
|
1445
|
+
const shouldRetryRequest = this.canRequestBeRetried(request, error);
|
|
896
1446
|
if (shouldRetryRequest) {
|
|
897
1447
|
await this.stats.errorTrackerRetry.addAsync(error, crawlingContext);
|
|
898
|
-
await this.errorHandler?.(crawlingContext,
|
|
1448
|
+
await this.errorHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1449
|
+
error);
|
|
899
1450
|
if (error instanceof SessionError) {
|
|
900
|
-
|
|
1451
|
+
crawlingContext.session?.retire();
|
|
901
1452
|
}
|
|
902
1453
|
if (!request.noRetry) {
|
|
903
1454
|
request.retryCount++;
|
|
@@ -914,6 +1465,9 @@ export class BasicCrawler {
|
|
|
914
1465
|
return;
|
|
915
1466
|
}
|
|
916
1467
|
}
|
|
1468
|
+
if (error instanceof SessionError) {
|
|
1469
|
+
crawlingContext.session?.retire();
|
|
1470
|
+
}
|
|
917
1471
|
// If the request is non-retryable, the error and snapshot aren't saved in the errorTrackerRetry object.
|
|
918
1472
|
// Therefore, we pass the crawlingContext to the errorTracker.add method, enabling snapshot capture.
|
|
919
1473
|
// This is to make sure the error snapshot is not duplicated in the errorTrackerRetry and errorTracker objects.
|
|
@@ -927,27 +1481,18 @@ export class BasicCrawler {
|
|
|
927
1481
|
// If we get here, the request is either not retryable
|
|
928
1482
|
// or failed more than retryCount times and will not be retried anymore.
|
|
929
1483
|
// Mark the request as failed and do not retry.
|
|
930
|
-
|
|
931
|
-
await source.markRequestHandled(request);
|
|
1484
|
+
await source.markRequestAsHandled(request);
|
|
932
1485
|
this.stats.failJob(request.id || request.uniqueKey, request.retryCount);
|
|
933
|
-
await this.
|
|
1486
|
+
await this.handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
|
|
934
1487
|
}
|
|
935
|
-
async
|
|
936
|
-
try {
|
|
937
|
-
return (await cb());
|
|
938
|
-
}
|
|
939
|
-
catch (e) {
|
|
940
|
-
Object.defineProperty(e, 'triggeredFromUserHandler', { value: true });
|
|
941
|
-
throw e;
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
async _handleFailedRequestHandler(crawlingContext, error) {
|
|
1488
|
+
async handleFailedRequestHandler(crawlingContext, error) {
|
|
945
1489
|
// Always log the last error regardless if the user provided a failedRequestHandler
|
|
946
1490
|
const { id, url, method, uniqueKey } = crawlingContext.request;
|
|
947
1491
|
const message = this._getMessageFromError(error, true);
|
|
948
1492
|
this.log.error(`Request failed and reached maximum retries. ${message}`, { id, url, method, uniqueKey });
|
|
949
1493
|
if (this.failedRequestHandler) {
|
|
950
|
-
await this.failedRequestHandler?.(crawlingContext,
|
|
1494
|
+
await this.failedRequestHandler?.(crawlingContext, // valid cast - ExtendedContext transitively extends CrawlingContext
|
|
1495
|
+
error);
|
|
951
1496
|
}
|
|
952
1497
|
}
|
|
953
1498
|
/**
|
|
@@ -969,11 +1514,9 @@ export class BasicCrawler {
|
|
|
969
1514
|
? (error.stack ?? [error.message || error, ...stackLines].join('\n'))
|
|
970
1515
|
: [error.message || error, userLine].join('\n');
|
|
971
1516
|
}
|
|
972
|
-
|
|
973
|
-
// Request should never be retried, or the error encountered makes it not able to be retried
|
|
974
|
-
if (request.noRetry ||
|
|
975
|
-
error instanceof NonRetryableError ||
|
|
976
|
-
(error instanceof SessionError && this.maxSessionRotations <= (request.sessionRotationCount ?? 0))) {
|
|
1517
|
+
canRequestBeRetried(request, error) {
|
|
1518
|
+
// Request should never be retried, or the error encountered makes it not able to be retried.
|
|
1519
|
+
if (request.noRetry || error instanceof NonRetryableError) {
|
|
977
1520
|
return false;
|
|
978
1521
|
}
|
|
979
1522
|
// User requested retry (we ignore retry count here as its explicitly told by the user to retry)
|
|
@@ -985,41 +1528,20 @@ export class BasicCrawler {
|
|
|
985
1528
|
return request.retryCount < maxRequestRetries;
|
|
986
1529
|
}
|
|
987
1530
|
/**
|
|
988
|
-
*
|
|
989
|
-
*
|
|
990
|
-
*
|
|
991
|
-
*
|
|
992
|
-
*
|
|
993
|
-
* empty.
|
|
994
|
-
*/
|
|
995
|
-
async _loadHandledRequestCount() {
|
|
996
|
-
if (this.requestQueue) {
|
|
997
|
-
this.handledRequestsCount = await this.requestQueue.handledCount();
|
|
998
|
-
}
|
|
999
|
-
else if (this.requestList) {
|
|
1000
|
-
this.handledRequestsCount = this.requestList.handledCount();
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
async _executeHooks(hooks, ...args) {
|
|
1004
|
-
if (Array.isArray(hooks) && hooks.length) {
|
|
1005
|
-
for (const hook of hooks) {
|
|
1006
|
-
await hook(...args);
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Function for cleaning up after all request are processed.
|
|
1012
|
-
* @ignore
|
|
1531
|
+
* Stops the crawler immediately.
|
|
1532
|
+
*
|
|
1533
|
+
* This method doesn't wait for currently active requests to finish.
|
|
1534
|
+
*
|
|
1535
|
+
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
1013
1536
|
*/
|
|
1014
1537
|
async teardown() {
|
|
1015
|
-
|
|
1016
|
-
if (this.useSessionPool) {
|
|
1017
|
-
await this.sessionPool.teardown();
|
|
1018
|
-
}
|
|
1538
|
+
serviceLocator.getEventManager().emit("persistState" /* EventType.PERSIST_STATE */, { isMigrating: false });
|
|
1019
1539
|
if (this._closeEvents) {
|
|
1020
|
-
await
|
|
1540
|
+
await serviceLocator.getEventManager().close();
|
|
1021
1541
|
}
|
|
1542
|
+
await this.sessionPoolDep.ifOwned((pool) => pool.teardown());
|
|
1022
1543
|
await this.autoscaledPool?.abort();
|
|
1544
|
+
await this.concurrencySystemDep?.ifOwned((system) => system.stop());
|
|
1023
1545
|
}
|
|
1024
1546
|
_getCookieHeaderFromRequest(request) {
|
|
1025
1547
|
if (request.headers?.Cookie && request.headers?.cookie) {
|
|
@@ -1028,18 +1550,18 @@ export class BasicCrawler {
|
|
|
1028
1550
|
}
|
|
1029
1551
|
return request.headers?.Cookie || request.headers?.cookie || '';
|
|
1030
1552
|
}
|
|
1031
|
-
|
|
1032
|
-
//
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1553
|
+
requestMatchesEnqueueStrategy(request) {
|
|
1554
|
+
// If `skipNavigation` was used, just return `true`
|
|
1555
|
+
try {
|
|
1556
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
|
1557
|
+
request.loadedUrl;
|
|
1558
|
+
}
|
|
1559
|
+
catch (err) {
|
|
1560
|
+
if (err instanceof NavigationSkippedError) {
|
|
1561
|
+
return true;
|
|
1037
1562
|
}
|
|
1038
|
-
|
|
1563
|
+
throw err;
|
|
1039
1564
|
}
|
|
1040
|
-
return RequestQueue.open(null, { config: this.config });
|
|
1041
|
-
}
|
|
1042
|
-
requestMatchesEnqueueStrategy(request) {
|
|
1043
1565
|
const { url, loadedUrl } = request;
|
|
1044
1566
|
// eslint-disable-next-line dot-notation -- private access
|
|
1045
1567
|
const strategy = request['enqueueStrategy'];
|
|
@@ -1077,31 +1599,6 @@ export class BasicCrawler {
|
|
|
1077
1599
|
}
|
|
1078
1600
|
}
|
|
1079
1601
|
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Creates new {@link Router} instance that works based on request labels.
|
|
1082
|
-
* This instance can then serve as a {@link BasicCrawlerOptions.requestHandler|`requestHandler`} of our {@link BasicCrawler}.
|
|
1083
|
-
* Defaults to the {@link BasicCrawlingContext}.
|
|
1084
|
-
*
|
|
1085
|
-
* > Serves as a shortcut for using `Router.create<BasicCrawlingContext>()`.
|
|
1086
|
-
*
|
|
1087
|
-
* ```ts
|
|
1088
|
-
* import { BasicCrawler, createBasicRouter } from 'crawlee';
|
|
1089
|
-
*
|
|
1090
|
-
* const router = createBasicRouter();
|
|
1091
|
-
* router.addHandler('label-a', async (ctx) => {
|
|
1092
|
-
* ctx.log.info('...');
|
|
1093
|
-
* });
|
|
1094
|
-
* router.addDefaultHandler(async (ctx) => {
|
|
1095
|
-
* ctx.log.info('...');
|
|
1096
|
-
* });
|
|
1097
|
-
*
|
|
1098
|
-
* const crawler = new BasicCrawler({
|
|
1099
|
-
* requestHandler: router,
|
|
1100
|
-
* });
|
|
1101
|
-
* await crawler.run();
|
|
1102
|
-
* ```
|
|
1103
|
-
*/
|
|
1104
1602
|
export function createBasicRouter(routes) {
|
|
1105
1603
|
return Router.create(routes);
|
|
1106
1604
|
}
|
|
1107
|
-
//# sourceMappingURL=basic-crawler.js.map
|