@crawlee/basic 4.0.0-beta.10 → 4.0.0-beta.101

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