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