@crawlee/basic 4.0.0-beta.99 → 4.0.0-rc.1

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 (80) hide show
  1. package/README.md +1 -1
  2. package/index.d.ts +11 -1
  3. package/index.js +11 -0
  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 +185 -389
  27. package/internals/basic-crawler.js +982 -684
  28. package/internals/cookie_utils.d.ts +40 -0
  29. package/internals/cookie_utils.js +122 -0
  30. package/internals/crawler-run.d.ts +76 -0
  31. package/internals/crawler-run.js +142 -0
  32. package/internals/crawlers/context_pipeline.d.ts +75 -0
  33. package/internals/crawlers/context_pipeline.js +109 -0
  34. package/internals/crawlers/crawler_commons.d.ts +216 -0
  35. package/internals/crawlers/crawler_commons.js +1 -0
  36. package/internals/crawlers/error_snapshotter.d.ts +29 -0
  37. package/internals/crawlers/error_snapshotter.js +116 -0
  38. package/internals/crawlers/error_tracker.d.ts +51 -0
  39. package/internals/crawlers/error_tracker.js +316 -0
  40. package/internals/crawlers/index.d.ts +4 -0
  41. package/internals/crawlers/index.js +3 -0
  42. package/internals/crawlers/internals/types.d.ts +7 -0
  43. package/internals/crawlers/internals/types.js +1 -0
  44. package/internals/crawlers/statistics.d.ts +316 -0
  45. package/internals/crawlers/statistics.js +525 -0
  46. package/internals/crawling_request.d.ts +86 -0
  47. package/internals/crawling_request.js +127 -0
  48. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  49. package/internals/enqueue_links/enqueue_links.js +76 -0
  50. package/internals/enqueue_links/index.d.ts +3 -0
  51. package/internals/enqueue_links/index.js +3 -0
  52. package/internals/enqueue_links/shared.d.ts +106 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +68 -0
  55. package/internals/errors.js +83 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +6 -0
  59. package/internals/request-timeout.js +27 -2
  60. package/internals/router.d.ts +299 -0
  61. package/internals/router.js +312 -0
  62. package/internals/send-request.d.ts +2 -1
  63. package/internals/send-request.js +1 -0
  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 +17 -14
@@ -0,0 +1,432 @@
1
+ import { Transform } from 'node:stream';
2
+ import { EnqueueStrategy } from '@crawlee/utils';
3
+ import { parseArgument, parseSitemap, schemas } from '@crawlee/utils/internal';
4
+ import { minimatch } from 'minimatch';
5
+ import { z } from 'zod';
6
+ import { EventType, KeyValueStore, purgeDefaultStorages, Request, RequestManagerTandem, RequestQueue, serviceLocator, } from '@crawlee/core';
7
+ import { constructUrlPatternObjects, urlPatternSchema } from './enqueue_links/index.js';
8
+ const sitemapRequestLoaderOptionsSchema = z.strictObject({
9
+ sitemapUrls: schemas.arrayOf(z.string(), 'strings'),
10
+ proxyUrl: z.string().optional(),
11
+ persistStateKey: z.string().optional(),
12
+ signal: z.unknown().optional(),
13
+ timeoutMillis: schemas.anyNumber.optional(),
14
+ maxBufferSize: schemas.anyNumber.default(200),
15
+ enqueueStrategy: z.enum(EnqueueStrategy).default(EnqueueStrategy.SameHostname),
16
+ parseSitemapOptions: z.looseObject({}).optional(),
17
+ include: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
18
+ exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
19
+ persistenceOptions: z.looseObject({}).optional(),
20
+ httpClient: schemas.httpClient.optional(),
21
+ });
22
+ /** @internal */
23
+ const STATE_PERSISTENCE_KEY = 'SITEMAP_REQUEST_LOADER_STATE';
24
+ /**
25
+ * A list of URLs to crawl parsed from a sitemap.
26
+ *
27
+ * The loading of the sitemap is performed in the background so that crawling can start before the sitemap is fully loaded.
28
+ */
29
+ export class SitemapRequestLoader {
30
+ /**
31
+ * Set of URLs that were returned by `fetchNextRequest()` and not marked as handled yet.
32
+ * @internal
33
+ */
34
+ inProgress = new Set();
35
+ /**
36
+ * Map of returned Request objects that have not been marked as handled yet.
37
+ *
38
+ * We use this to persist custom user fields on the in-progress requests.
39
+ */
40
+ #requestData = new Map();
41
+ /**
42
+ * Object for keeping track of the sitemap parsing progress.
43
+ */
44
+ #sitemapParsingProgress = {
45
+ /**
46
+ * URL of the sitemap that is currently being parsed. `null` if no sitemap is being parsed.
47
+ */
48
+ inProgressSitemapUrl: null,
49
+ /**
50
+ * Buffer for URLs from the currently parsed sitemap. Used for tracking partially loaded sitemaps across migrations.
51
+ */
52
+ inProgressEntries: new Set(),
53
+ /**
54
+ * Set of sitemap URLs that have not been parsed yet. If the set is empty and `inProgressSitemapUrl` is `null`, the sitemap loading is finished.
55
+ */
56
+ pendingSitemapUrls: new Set(),
57
+ };
58
+ /**
59
+ * Object stream of URLs parsed from the sitemaps.
60
+ * Using `highWaterMark`, this can manage the speed of the sitemap loading.
61
+ *
62
+ * Fetch the next URL to be processed using `fetchNextRequest()`.
63
+ */
64
+ #urlQueueStream;
65
+ /**
66
+ * Indicates whether the request list sitemap loading was aborted.
67
+ *
68
+ * If the loading was aborted before the sitemaps were fully loaded, the request list might be missing some URLs.
69
+ * The `isSitemapFullyLoaded` method can be used to check if the sitemaps were fully loaded.
70
+ *
71
+ * If the loading is aborted and all the requests are handled, `checkReadiness()` will report `finished`.
72
+ */
73
+ #abortLoading = false;
74
+ /** Number of URLs that were marked as handled */
75
+ #handledUrlCount = 0;
76
+ #persistStateKey;
77
+ #store;
78
+ #closed = false;
79
+ /**
80
+ * Proxy URL to be used for sitemap loading.
81
+ */
82
+ #proxyUrl;
83
+ /**
84
+ * Enqueue strategy applied to sitemap-derived URLs and stamped onto the emitted `Request` objects.
85
+ */
86
+ #enqueueStrategy;
87
+ /**
88
+ * Logger instance.
89
+ */
90
+ #log;
91
+ #urlExcludePatternObjects = [];
92
+ #urlPatternObjects = [];
93
+ /** EventManager used to handle persistence */
94
+ #events;
95
+ #persistenceOptions;
96
+ /** @internal */
97
+ constructor(options) {
98
+ const { include, exclude, persistStateKey, persistenceOptions, proxyUrl, maxBufferSize, sitemapUrls, enqueueStrategy, } = parseArgument(options, sitemapRequestLoaderOptionsSchema, 'SitemapRequestLoaderOptions');
99
+ this.#log = serviceLocator.getLogger().child({ prefix: 'SitemapRequestLoader' });
100
+ if (exclude?.length) {
101
+ this.#urlExcludePatternObjects.push(...constructUrlPatternObjects(exclude));
102
+ }
103
+ if (include?.length) {
104
+ this.#urlPatternObjects.push(...constructUrlPatternObjects(include));
105
+ }
106
+ this.#persistStateKey = persistStateKey;
107
+ this.#persistenceOptions = { enable: true, ...persistenceOptions };
108
+ this.#proxyUrl = proxyUrl;
109
+ this.#enqueueStrategy = enqueueStrategy;
110
+ this.#urlQueueStream = this.#createNewStream(maxBufferSize);
111
+ this.#sitemapParsingProgress.pendingSitemapUrls = new Set(sitemapUrls);
112
+ this.#events = serviceLocator.getEventManager();
113
+ this.persistState = this.persistState.bind(this);
114
+ }
115
+ /**
116
+ * Creates a new object stream with the specified highWaterMark.
117
+ * @param highWaterMark High water mark for the stream (the maximum number of objects the stream will buffer).
118
+ * @returns A new object stream.
119
+ */
120
+ #createNewStream(highWaterMark) {
121
+ return new Transform({
122
+ objectMode: true,
123
+ highWaterMark,
124
+ }).pause();
125
+ }
126
+ /**
127
+ * Returns a function that checks whether the provided pattern matches the closure URL.
128
+ * @param url URL to be checked.
129
+ * @returns A matcher function that checks whether the pattern matches the closure URL.
130
+ */
131
+ #matchesUrl(url) {
132
+ return (patternObject) => {
133
+ const { regexp, glob } = patternObject;
134
+ const matchesRegex = (regexp && url.match(regexp)) || false;
135
+ const matchesGlob = (glob && minimatch(url, glob, { nocase: true })) || false;
136
+ return Boolean(matchesRegex || matchesGlob);
137
+ };
138
+ }
139
+ /**
140
+ * Checks whether the URL matches the `include` / `exclude` patterns provided in the `options`.
141
+ * @param url URL to be checked.
142
+ * @returns `true` if the URL matches the patterns, `false` otherwise.
143
+ */
144
+ #isUrlMatchingPatterns(url) {
145
+ return (!this.#urlExcludePatternObjects.some(this.#matchesUrl(url)) &&
146
+ (this.#urlPatternObjects.length === 0 || this.#urlPatternObjects.some(this.#matchesUrl(url))));
147
+ }
148
+ /**
149
+ * Adds a URL to the queue of parsed URLs.
150
+ *
151
+ * Blocks if the stream is full until it is drained.
152
+ */
153
+ async #pushNextUrl(url) {
154
+ return new Promise((resolve) => {
155
+ if (this.#closed || (url && !this.#isUrlMatchingPatterns(url))) {
156
+ resolve();
157
+ return;
158
+ }
159
+ if (!this.#urlQueueStream.push(url)) {
160
+ // This doesn't work with the 'drain' event (it's not emitted for some reason).
161
+ this.#urlQueueStream.once('readdata', () => {
162
+ resolve();
163
+ });
164
+ }
165
+ else {
166
+ resolve();
167
+ }
168
+ });
169
+ }
170
+ /**
171
+ * Reads the next URL from the queue of parsed URLs.
172
+ *
173
+ * If the stream is empty, blocks until a new URL is pushed.
174
+ * @returns The next URL from the queue or `null` if we have read all URLs.
175
+ */
176
+ async #readNextUrl() {
177
+ return new Promise((resolve) => {
178
+ if (this.#closed) {
179
+ resolve(null);
180
+ return;
181
+ }
182
+ const result = this.#urlQueueStream.read();
183
+ if (!result && !this.isSitemapFullyLoaded()) {
184
+ this.#urlQueueStream.once('readable', () => {
185
+ const nextUrl = this.#urlQueueStream.read();
186
+ resolve(nextUrl);
187
+ });
188
+ }
189
+ else {
190
+ resolve(result);
191
+ }
192
+ this.#urlQueueStream.emit('readdata');
193
+ });
194
+ }
195
+ /**
196
+ * Indicates whether the background processing of sitemap contents has successfully finished.
197
+ *
198
+ * If this is `false`, the background processing is either still in progress or was aborted.
199
+ */
200
+ isSitemapFullyLoaded() {
201
+ return (this.#sitemapParsingProgress.inProgressSitemapUrl === null &&
202
+ this.#sitemapParsingProgress.pendingSitemapUrls.size === 0);
203
+ }
204
+ /**
205
+ * Start processing the sitemaps and loading the URLs.
206
+ *
207
+ * Resolves once all the sitemaps URLs have been fully loaded (sets `isSitemapFullyLoaded` to `true`).
208
+ */
209
+ async #load({ parseSitemapOptions, }) {
210
+ while (!this.isSitemapFullyLoaded() && !this.#abortLoading) {
211
+ const sitemapUrl = this.#sitemapParsingProgress.inProgressSitemapUrl ??
212
+ this.#sitemapParsingProgress.pendingSitemapUrls.values().next().value;
213
+ try {
214
+ for await (const item of parseSitemap([{ type: 'url', url: sitemapUrl }], this.#proxyUrl, {
215
+ ...parseSitemapOptions,
216
+ maxDepth: 0,
217
+ emitNestedSitemaps: true,
218
+ enqueueStrategy: this.#enqueueStrategy,
219
+ })) {
220
+ if (!item.originSitemapUrl) {
221
+ // This is a nested sitemap
222
+ this.#sitemapParsingProgress.pendingSitemapUrls.add(item.loc);
223
+ continue;
224
+ }
225
+ if (!this.#sitemapParsingProgress.inProgressEntries.has(item.loc)) {
226
+ await this.#pushNextUrl(item.loc);
227
+ this.#sitemapParsingProgress.inProgressEntries.add(item.loc);
228
+ }
229
+ }
230
+ }
231
+ catch (e) {
232
+ this.#log.error('Error loading sitemap contents:', e);
233
+ }
234
+ this.#sitemapParsingProgress.pendingSitemapUrls.delete(sitemapUrl);
235
+ this.#sitemapParsingProgress.inProgressEntries.clear();
236
+ this.#sitemapParsingProgress.inProgressSitemapUrl = null;
237
+ }
238
+ this.#urlQueueStream.end();
239
+ }
240
+ /**
241
+ * Open a sitemap and start processing it.
242
+ *
243
+ * Resolves to a new instance of `SitemapRequestLoader`, which **might not be fully loaded yet** - i.e. the sitemap might still be loading in the background.
244
+ *
245
+ * Track the loading progress using the `isSitemapFullyLoaded` property.
246
+ */
247
+ static async open(options) {
248
+ const { httpClient, ...restOptions } = options;
249
+ const requestList = new SitemapRequestLoader({
250
+ ...restOptions,
251
+ persistStateKey: options.persistStateKey ?? STATE_PERSISTENCE_KEY,
252
+ });
253
+ await requestList.#restoreState();
254
+ void requestList.#load({
255
+ parseSitemapOptions: { logger: serviceLocator.getLogger(), ...options.parseSitemapOptions, httpClient },
256
+ });
257
+ if (requestList.#persistenceOptions.enable) {
258
+ requestList.#events.on(EventType.PERSIST_STATE, requestList.persistState);
259
+ }
260
+ options?.signal?.addEventListener('abort', () => {
261
+ requestList.#abortLoading = true;
262
+ });
263
+ if (options.timeoutMillis) {
264
+ setTimeout(() => {
265
+ requestList.#abortLoading = true;
266
+ }, options.timeoutMillis);
267
+ }
268
+ return requestList;
269
+ }
270
+ /**
271
+ * @inheritDoc
272
+ */
273
+ async getTotalCount() {
274
+ // Total known so far = not-yet-fetched (still buffered in the stream) + in-progress (fetched but not
275
+ // yet handled) + already handled.
276
+ return this.#urlQueueStream.readableLength + this.inProgress.size + this.#handledUrlCount;
277
+ }
278
+ /**
279
+ * @inheritDoc
280
+ */
281
+ async getPendingCount() {
282
+ // Pending = everything not yet handled = not-yet-fetched + in-progress.
283
+ return this.#urlQueueStream.readableLength + this.inProgress.size;
284
+ }
285
+ /**
286
+ * Combines this list with a request manager (a {@link RequestQueue} by default) into a
287
+ * {@link RequestManagerTandem}, allowing requests to be added and reclaimed while still
288
+ * being read from this list first.
289
+ */
290
+ async toTandem(requestManager) {
291
+ return new RequestManagerTandem(this, requestManager ?? (await RequestQueue.open()));
292
+ }
293
+ /**
294
+ * @inheritDoc
295
+ */
296
+ async checkReadiness() {
297
+ if (this.#urlQueueStream.readableLength > 0) {
298
+ return { status: 'ready' };
299
+ }
300
+ // The parser is still running, so more URLs may yet arrive - on no schedule, hence no `readyAt`.
301
+ if (!this.isSitemapFullyLoaded() && !this.#abortLoading) {
302
+ return { status: 'waiting' };
303
+ }
304
+ return this.inProgress.size === 0 ? { status: 'finished' } : { status: 'waiting' };
305
+ }
306
+ /**
307
+ * @inheritDoc
308
+ */
309
+ async getHandledCount() {
310
+ return this.#handledUrlCount;
311
+ }
312
+ /**
313
+ * @inheritDoc
314
+ */
315
+ async persistState() {
316
+ if (this.#persistStateKey === undefined) {
317
+ return;
318
+ }
319
+ this.#store ??= await KeyValueStore.open();
320
+ const urlQueue = [];
321
+ while (this.#urlQueueStream.readableLength > 0) {
322
+ const url = this.#urlQueueStream.read();
323
+ if (url === null) {
324
+ break;
325
+ }
326
+ urlQueue.push(url);
327
+ }
328
+ // Create a new stream, as we have read all the URLs from the current one.
329
+ // Pushing the urls back to the original stream might not be possible if it has been ended.
330
+ const previousStream = this.#urlQueueStream;
331
+ const newStream = this.#createNewStream(previousStream.readableHighWaterMark);
332
+ for (const url of urlQueue) {
333
+ newStream.push(url);
334
+ }
335
+ if (previousStream.writableEnded) {
336
+ newStream.end();
337
+ }
338
+ this.#urlQueueStream = newStream;
339
+ // A `pushNextUrl()` call may be blocked on backpressure, waiting for a `readdata` event on the
340
+ // previous stream. That event is only ever emitted by `readNextUrl()` on the current stream, so
341
+ // after the swap the waiter would never be notified and the background sitemap loading would hang.
342
+ // Re-emit `readdata` on the previous stream to release any such pending waiter (its URL has already
343
+ // been transferred to the new stream above).
344
+ previousStream.emit('readdata');
345
+ await this.#store.setValue(this.#persistStateKey, {
346
+ sitemapParsingProgress: {
347
+ pendingSitemapUrls: Array.from(this.#sitemapParsingProgress.pendingSitemapUrls),
348
+ inProgressSitemapUrl: this.#sitemapParsingProgress.inProgressSitemapUrl,
349
+ inProgressEntries: Array.from(this.#sitemapParsingProgress.inProgressEntries),
350
+ },
351
+ // Re-queue in-progress requests to the front so they are retried if the state is restored.
352
+ urlQueue: [...this.inProgress, ...urlQueue],
353
+ requestData: Array.from(this.#requestData.entries()),
354
+ abortLoading: this.#abortLoading,
355
+ closed: this.#closed,
356
+ });
357
+ }
358
+ async #restoreState() {
359
+ await purgeDefaultStorages({ onlyPurgeOnce: true });
360
+ if (this.#persistStateKey === undefined) {
361
+ return;
362
+ }
363
+ this.#store ??= await KeyValueStore.open();
364
+ const state = await this.#store.getValue(this.#persistStateKey);
365
+ if (state === null) {
366
+ return;
367
+ }
368
+ this.#sitemapParsingProgress = {
369
+ pendingSitemapUrls: new Set(state.sitemapParsingProgress.pendingSitemapUrls),
370
+ inProgressSitemapUrl: state.sitemapParsingProgress.inProgressSitemapUrl,
371
+ inProgressEntries: new Set(state.sitemapParsingProgress.inProgressEntries),
372
+ };
373
+ this.#requestData = new Map(state.requestData ?? []);
374
+ for (const url of state.urlQueue) {
375
+ this.#urlQueueStream.push(url);
376
+ }
377
+ this.#abortLoading = state.abortLoading;
378
+ this.#closed = state.closed;
379
+ }
380
+ /**
381
+ * @inheritDoc
382
+ */
383
+ async fetchNextRequest() {
384
+ const nextUrl = await this.#readNextUrl();
385
+ if (!nextUrl) {
386
+ return null;
387
+ }
388
+ // A restored in-progress request already has its Request data; don't overwrite it.
389
+ if (!this.#requestData.has(nextUrl)) {
390
+ this.#requestData.set(nextUrl, new Request({ url: nextUrl, enqueueStrategy: this.#enqueueStrategy }));
391
+ }
392
+ this.inProgress.add(nextUrl);
393
+ return this.#requestData.get(nextUrl);
394
+ }
395
+ /**
396
+ * @inheritDoc
397
+ */
398
+ async *[Symbol.asyncIterator]() {
399
+ while ((await this.checkReadiness()).status !== 'finished') {
400
+ const request = await this.fetchNextRequest();
401
+ if (!request)
402
+ break;
403
+ yield request;
404
+ }
405
+ }
406
+ /**
407
+ * Aborts the internal sitemap loading, stops the processing of the sitemap contents and drops all the pending URLs.
408
+ *
409
+ * Calling `fetchNextRequest()` after this method will always return `null`.
410
+ */
411
+ async teardown() {
412
+ this.#closed = true;
413
+ this.#abortLoading = true;
414
+ this.#events.off(EventType.PERSIST_STATE, this.persistState);
415
+ await this.persistState();
416
+ this.#urlQueueStream.emit('readdata'); // unblocks the potentially waiting `pushNextUrl` call
417
+ }
418
+ /**
419
+ * @inheritDoc
420
+ */
421
+ async markRequestAsHandled(request) {
422
+ this.#handledUrlCount += 1;
423
+ this.#ensureInProgress(request.url);
424
+ this.inProgress.delete(request.url);
425
+ this.#requestData.delete(request.url);
426
+ }
427
+ #ensureInProgress(url) {
428
+ if (!this.inProgress.has(url)) {
429
+ throw new Error(`The request is not being processed (url: ${url})`);
430
+ }
431
+ }
432
+ }
@@ -0,0 +1,229 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, Configuration, IRequestManager, PacingSignal, RequestQueueOperationInfo, RequestQueueOperationOptions, RequestsLike, Source, StorageIdentifier, RequestSourceStatus, StorageOpenOptions } from '@crawlee/core';
3
+ import { Request } from '@crawlee/core';
4
+ /**
5
+ * Opens a request manager, matching the shape of storage `open` methods such as
6
+ * {@link RequestQueue.open|`RequestQueue.open`}.
7
+ *
8
+ * {@link ThrottlingRequestManager} calls this once per configured domain, so every per-domain queue shares the
9
+ * concrete type and storage backend of the manager being wrapped.
10
+ *
11
+ * Not exported: the only option that takes one is `@internal`.
12
+ */
13
+ type RequestManagerOpener<T extends IRequestManager = IRequestManager> = (identifier?: string | StorageIdentifier | null, options?: StorageOpenOptions) => Promise<T>;
14
+ /** Options for {@link ThrottlingRequestManager}. */
15
+ export interface ThrottlingRequestManagerOptions<T extends IRequestManager = IRequestManager> {
16
+ /**
17
+ * The request manager to wrap, usually a {@link RequestQueue}. Requests for domains that are not throttled
18
+ * are stored here. May be a factory, so that the throttler can be constructed synchronously and the manager
19
+ * under it opened only on first use.
20
+ *
21
+ * Omitted, the default request queue is opened on first use through
22
+ * {@link ThrottlingRequestManagerOptions.requestManagerOpener|`requestManagerOpener`}.
23
+ */
24
+ inner?: T | (() => T | Promise<T>);
25
+ /**
26
+ * Which domains to throttle: a list of hostnames, or `'all'` for every domain the crawl encounters.
27
+ *
28
+ * Matching a listed hostname is case-insensitive and exact - wildcards such as `*.example.com` are not
29
+ * supported, so list each subdomain you care about (or set
30
+ * {@link ThrottlingRequestManagerOptions.throttleBy|`throttleBy: 'registrableDomain'`}). An
31
+ * internationalized domain may be given in either its unicode or its punycode form, and an IPv6 address has
32
+ * to be bracketed (`[::1]`). Requests for any other domain bypass throttling entirely.
33
+ *
34
+ * `'all'` gives each domain a queue of its own the first time it is seen, so that it can be held back
35
+ * without its requests being repeatedly popped and re-enqueued. One request queue per domain is not free,
36
+ * which is what {@link ThrottlingRequestManagerOptions.maxThrottledDomains|`maxThrottledDomains`} is
37
+ * there to bound.
38
+ */
39
+ domains: string[] | 'all';
40
+ /**
41
+ * A floor under the crawl delay of every throttled domain, in seconds - the proactive clock described on
42
+ * {@link ThrottlingRequestManager}. A domain whose robots.txt asks for a longer `Crawl-delay` gets the
43
+ * longer one; this is a minimum, not an override. A `minIntervalEverywhere` {@link PacingSignal} raises
44
+ * this floor at runtime, and never lowers it.
45
+ * @default 0
46
+ */
47
+ minCrawlDelaySecs?: number;
48
+ /**
49
+ * What counts as "the same domain": the exact hostname, or the registrable domain it belongs to
50
+ * (`example.com` for `www.example.com`, `a.example.co.uk` and so on). Hosts with no registrable domain -
51
+ * IP addresses, `localhost` - are always throttled per hostname.
52
+ *
53
+ * Grouping by registrable domain gives subdomains a single pair of clocks and a single queue, which is what
54
+ * you want when the pacing is there to be polite to one server rather than to satisfy a specific host's
55
+ * rate limit.
56
+ * @default 'hostname'
57
+ */
58
+ throttleBy?: 'hostname' | 'registrableDomain';
59
+ /**
60
+ * The most domains a run may throttle at once. Exceeding it throws, rather than silently letting the
61
+ * throttling lapse - one request queue per domain is not free, and a crawl that discovers domains without
62
+ * bound would drown the storage backend in them.
63
+ *
64
+ * Only domains discovered under `domains: 'all'` count against this; an explicit list is taken at face value.
65
+ * @default 100
66
+ */
67
+ maxThrottledDomains?: number;
68
+ /**
69
+ * The key under which the discovered domain list is kept in the default key-value store, so that a restart
70
+ * with `purgeOnStart` disabled reopens their queues instead of stranding whatever they still hold. Only
71
+ * written under `domains: 'all'`.
72
+ *
73
+ * Give each manager its own key when running several of them against the same storage.
74
+ * @default 'CRAWLEE_THROTTLED_DOMAINS'
75
+ */
76
+ persistStateKey?: string;
77
+ /**
78
+ * Opens the per-domain queues, one per throttled domain, each under the alias `throttled-<domain>`.
79
+ * @default RequestQueue.open
80
+ * @internal
81
+ */
82
+ requestManagerOpener?: RequestManagerOpener<T>;
83
+ /**
84
+ * The delay applied after a domain's first HTTP 429, doubled on each subsequent one.
85
+ * @default 2
86
+ */
87
+ baseDelaySecs?: number;
88
+ /**
89
+ * Upper bound on the delay between requests to a rate-limited domain, applied to both the exponential
90
+ * backoff and a `Retry-After` value.
91
+ * @default 60
92
+ */
93
+ maxDelaySecs?: number;
94
+ /**
95
+ * How long a domain may rate-limit us without a single request getting through before the crawl is
96
+ * abandoned with a {@link PersistentRateLimitError}.
97
+ *
98
+ * A domain that keeps answering 429 for this long is not going to be crawled by waiting longer - the
99
+ * concurrency is too high for it, or it has blocked us outright. Its requests are deliberately left in
100
+ * their queue, so re-running the crawl with `purgeOnStart` disabled picks them up once the domain recovers.
101
+ *
102
+ * A crawler running with `keepAlive` is exempt - outliving a domain that will not let us through is the
103
+ * whole point there.
104
+ * @default 900
105
+ */
106
+ maxDomainStallSecs?: number;
107
+ }
108
+ /**
109
+ * A request manager that wraps another one and paces requests per domain.
110
+ *
111
+ * Requests for a throttled domain are routed into their own queue when they are added, so each request lives in
112
+ * exactly one place and deduplication keeps working. Everything else goes to the wrapped manager untouched.
113
+ *
114
+ * {@link ThrottlingRequestManager.fetchNextRequest|`fetchNextRequest()`} serves the domain that has been waiting
115
+ * longest and skips any that are backing off, falling back to the wrapped manager. It never blocks: while every
116
+ * remaining request belongs to a throttled domain it returns `null` and
117
+ * {@link ThrottlingRequestManager.checkReadiness|`checkReadiness()`} reports `waiting` with the moment the
118
+ * earliest of them comes due, so the crawler idles instead of holding a concurrency slot open.
119
+ *
120
+ * Each throttled domain runs two independent clocks, and may be dispatched to once **both** have run out:
121
+ * - **Backoff**, set by HTTP 429 responses - honouring `Retry-After`, and otherwise doubling from `baseDelaySecs`.
122
+ * Reactive and temporary: it decays once the domain stops turning us away. The crawlers report the 429s
123
+ * themselves; a request held back this way is retried later without counting against `maxRequestRetries` and
124
+ * without penalising its session.
125
+ * - **Crawl delay**, the minimum interval between two dispatches to the domain, armed after each one. Proactive
126
+ * and constant: whatever the domain's robots.txt asks for, floored by
127
+ * {@link ThrottlingRequestManagerOptions.minCrawlDelaySecs|`minCrawlDelaySecs`}. Either may be absent, in
128
+ * which case the other one is the delay.
129
+ *
130
+ * Which domains get those clocks is {@link ThrottlingRequestManagerOptions.domains|`domains`} - a list, or
131
+ * `'all'` for every domain the crawl encounters.
132
+ *
133
+ * Pass one as a crawler's `requestManager`; the `sameDomainDelaySecs` shorthand builds one with `domains: 'all'`
134
+ * and `throttleBy: 'registrableDomain'`. Construct it yourself to name the domains or tune the delays - one
135
+ * covering every domain also makes `sameDomainDelaySecs` land on it as a floor rather than adding a second pacer.
136
+ *
137
+ * Signals - 429s, robots.txt `Crawl-delay`, that floor - arrive through
138
+ * {@link IRequestManager.recordPacingSignal|`recordPacingSignal`}, which wrapping managers forward, so this
139
+ * works wherever it sits in a composition, including inside a {@link RequestManagerTandem}.
140
+ *
141
+ * **Example usage:**
142
+ *
143
+ * ```ts
144
+ * const crawler = new CheerioCrawler({
145
+ * requestManager: new ThrottlingRequestManager({
146
+ * domains: ['api.example.com', 'slow-site.org'],
147
+ * }),
148
+ * requestHandler: async ({ request }) => { ... },
149
+ * });
150
+ * ```
151
+ *
152
+ * @category Sources
153
+ */
154
+ export declare class ThrottlingRequestManager<T extends IRequestManager = IRequestManager> implements IRequestManager {
155
+ #private;
156
+ constructor(options: ThrottlingRequestManagerOptions<T>, config?: Configuration);
157
+ /**
158
+ * The wrapped manager, holding every request whose domain is not throttled. `undefined` until an `inner`
159
+ * passed as a factory is resolved - reading this never forces it, because a getter should not open a queue
160
+ * behind a caller's back.
161
+ *
162
+ * @internal
163
+ */
164
+ get innerManager(): T | undefined;
165
+ /**
166
+ * Records a pacing signal: a refusal puts the URL's domain into backoff, a declared interval becomes its
167
+ * crawl delay, and a crawl-wide floor raises {@link recordEverywhereFloor|the floor under all of them}.
168
+ *
169
+ * @returns `false` if the domain the signal covers is not throttled, in which case this is a no-op.
170
+ * @throws If the signal's scope is one this manager cannot honour - see {@link assertScopeHonourable}.
171
+ * @inheritdoc
172
+ */
173
+ recordPacingSignal(signal: PacingSignal): boolean;
174
+ addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
175
+ /**
176
+ * Adds requests in batches, routing each one to the manager that owns its domain.
177
+ *
178
+ * Batching, validation, deduplication and `Retry-After`-free bookkeeping are all delegated to the target
179
+ * managers - this only decides where each request goes, one batch at a time, so a lazy or unbounded input
180
+ * iterable is never fully materialized.
181
+ */
182
+ addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
183
+ reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
184
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
185
+ getTotalCount(): Promise<number>;
186
+ getPendingCount(): Promise<number>;
187
+ getHandledCount(): Promise<number>;
188
+ /**
189
+ * Reports whether anything can be dispatched right now, and if not, when — or why never.
190
+ *
191
+ * One traversal of the domain clocks answers all of it: only domains whose delays have run out are probed,
192
+ * the rest merely contribute the moment they come due. Throttled requests count as outstanding work, so a
193
+ * crawler gated on this idles for the backoff instead of concluding it is done.
194
+ *
195
+ * `ready` from anywhere else outranks a stalling domain and is returned without looking at the stall clocks,
196
+ * so one hopeless domain never ends a crawl making progress elsewhere. It cannot outrank itself, though -
197
+ * see the traversal.
198
+ */
199
+ checkReadiness(): Promise<RequestSourceStatus>;
200
+ /**
201
+ * Empties every manager and clears the accumulated backoff. A robots.txt `Crawl-delay` is a property of the
202
+ * site rather than of the run, so it survives.
203
+ */
204
+ purge(): Promise<void>;
205
+ setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
206
+ /**
207
+ * @inheritdoc
208
+ * Extending a lock must not consume the in-flight marker that later routes
209
+ * {@link ThrottlingRequestManager.markRequestAsHandled} / {@link ThrottlingRequestManager.reclaimRequest}.
210
+ */
211
+ extendRequestProcessingTimeSecs(request: Request, secs: number): Promise<boolean>;
212
+ /**
213
+ * Returns the next request from a domain that is not backing off, or from the inner manager.
214
+ *
215
+ * Returns `null` while every remaining request belongs to a throttled domain - it never waits the backoff
216
+ * out, because a consumer parked in here holds a concurrency slot, which the autoscaler reads as spare
217
+ * capacity and answers by scaling up. Callers poll instead, and
218
+ * {@link ThrottlingRequestManager.checkReadiness|`checkReadiness()`} reports `waiting` meanwhile so the
219
+ * crawler's task loop idles rather than spins.
220
+ */
221
+ fetchNextRequest<R extends Dictionary = Dictionary>(): Promise<Request<R> | null>;
222
+ [Symbol.asyncIterator](): AsyncGenerator<Request<Dictionary>, void, unknown>;
223
+ /**
224
+ * Drops every managed storage - the wrapped manager and each per-domain queue.
225
+ * @internal
226
+ */
227
+ drop(): Promise<void>;
228
+ }
229
+ export {};