@crawlee/basic 4.0.0-beta.13 → 4.0.0-beta.130

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