@crawlee/basic 4.0.0-beta.14 → 4.0.0-beta.141

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