@crawlee/basic 4.0.0-beta.1 → 4.0.0-beta.100

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