@crawlee/basic 4.0.0-beta.22 → 4.0.0-beta.220

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