@crawlee/basic 4.0.0-beta.11 → 4.0.0-beta.111

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