@crawlee/basic 4.0.0-beta.8 → 4.0.0-beta.81

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