@crawlee/basic 4.0.0-beta.23 → 4.0.0-beta.230

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