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

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