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