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