@crawlee/basic 4.0.0-beta.12 → 4.0.0-beta.120

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