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