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