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

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