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