@crawlee/basic 4.0.0-beta.19 → 4.0.0-beta.191

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 +14 -14
  2. package/index.d.ts +11 -2
  3. package/index.js +11 -1
  4. package/internals/autoscaling/autoscaled_pool.d.ts +198 -0
  5. package/internals/autoscaling/autoscaled_pool.js +388 -0
  6. package/internals/autoscaling/concurrency_system.d.ts +275 -0
  7. package/internals/autoscaling/concurrency_system.js +365 -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 +47 -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 +122 -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 +465 -335
  27. package/internals/basic-crawler.js +1402 -820
  28. package/internals/cookie_utils.d.ts +44 -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 +71 -0
  33. package/internals/crawlers/context_pipeline.js +117 -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 +57 -0
  37. package/internals/crawlers/error_snapshotter.js +117 -0
  38. package/internals/crawlers/error_tracker.d.ts +54 -0
  39. package/internals/crawlers/error_tracker.js +308 -0
  40. package/internals/crawlers/index.d.ts +5 -0
  41. package/internals/crawlers/index.js +4 -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 +318 -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 +2 -0
  51. package/internals/enqueue_links/index.js +2 -0
  52. package/internals/enqueue_links/shared.d.ts +99 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +55 -0
  55. package/internals/errors.js +67 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +48 -0
  59. package/internals/request-timeout.js +73 -0
  60. package/internals/router.d.ts +306 -0
  61. package/internals/router.js +310 -0
  62. package/internals/send-request.d.ts +4 -4
  63. package/internals/send-request.js +22 -11
  64. package/internals/session_pool/consts.d.ts +3 -0
  65. package/internals/session_pool/consts.js +3 -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 +153 -0
  73. package/internals/session_pool/session.js +221 -0
  74. package/internals/session_pool/session_pool.d.ts +242 -0
  75. package/internals/session_pool/session_pool.js +429 -0
  76. package/internals/sitemap_request_loader.d.ts +196 -0
  77. package/internals/sitemap_request_loader.js +432 -0
  78. package/internals/throttling_request_manager.d.ts +214 -0
  79. package/internals/throttling_request_manager.js +825 -0
  80. package/package.json +19 -13
  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
@@ -0,0 +1,196 @@
1
+ import type { BaseHttpClient } from '@crawlee/http-client';
2
+ import { EnqueueStrategy, type ParseSitemapOptions } from '@crawlee/utils';
3
+ import type { IRequestLoader, IRequestManager, RequestLoaderStatus } from '@crawlee/core';
4
+ import { Request } from '@crawlee/core';
5
+ import type { UrlPatternInput } from './enqueue_links/index.js';
6
+ interface UrlConstraints {
7
+ /**
8
+ * An array of URL patterns that URLs must match to be included.
9
+ *
10
+ * Accepts glob pattern strings, `{ glob: string }` objects, `RegExp` instances, or `{ regexp: RegExp }` objects.
11
+ *
12
+ * Glob matching is always case-insensitive.
13
+ * If you need case-sensitive matching, use a `RegExp`.
14
+ *
15
+ * If `include` is an empty array or `undefined`, then the `SitemapRequestLoader`
16
+ * includes all the URLs from the sitemap.
17
+ */
18
+ include?: readonly UrlPatternInput[];
19
+ /**
20
+ * An array of URL patterns. Matching URLs will **not** be included.
21
+ *
22
+ * Accepts glob pattern strings, `{ glob: string }` objects, `RegExp` instances, or `{ regexp: RegExp }` objects.
23
+ *
24
+ * Glob matching is always case-insensitive.
25
+ * If you need case-sensitive matching, use a `RegExp`.
26
+ */
27
+ exclude?: readonly UrlPatternInput[];
28
+ }
29
+ export interface SitemapRequestLoaderOptions extends UrlConstraints {
30
+ /**
31
+ * List of sitemap URLs to parse.
32
+ */
33
+ sitemapUrls: string[];
34
+ /**
35
+ * Proxy URL to be used for sitemap loading.
36
+ */
37
+ proxyUrl?: string;
38
+ /**
39
+ * Key for persisting the state of the request list in the `KeyValueStore`.
40
+ */
41
+ persistStateKey?: string;
42
+ /**
43
+ * Persistence-related options to control how and when crawler's data gets persisted.
44
+ */
45
+ persistenceOptions?: {
46
+ /**
47
+ * Use this flag to disable or enable periodic persistence to key value store.
48
+ * @default true
49
+ */
50
+ enable?: boolean;
51
+ };
52
+ /**
53
+ * Abort signal to be used for sitemap loading.
54
+ */
55
+ signal?: AbortSignal;
56
+ /**
57
+ * Timeout for sitemap loading in milliseconds. If both `signal` and `timeoutMillis` are provided, either of them can abort the loading.
58
+ */
59
+ timeoutMillis?: number;
60
+ /**
61
+ * Maximum number of buffered URLs for the sitemap loading stream.
62
+ * If the buffer is full, the stream will pause until the buffer is drained.
63
+ *
64
+ * @default 200
65
+ */
66
+ maxBufferSize?: number;
67
+ /**
68
+ * Keep only sitemap-derived URLs matching this strategy relative to the parent sitemap URL; non-`http(s)`
69
+ * schemes are always dropped. The filtering stays enforced after navigation (e.g. across redirects).
70
+ * Pass `'all'` to disable host filtering.
71
+ * @default EnqueueStrategy.SameHostname
72
+ */
73
+ enqueueStrategy?: EnqueueStrategy | `${EnqueueStrategy}`;
74
+ /**
75
+ * Advanced options for the underlying `parseSitemap` call.
76
+ */
77
+ parseSitemapOptions?: Omit<ParseSitemapOptions, 'emitNestedSitemaps' | 'maxDepth'>;
78
+ /**
79
+ * Custom HTTP client to be used for sitemap loading.
80
+ */
81
+ httpClient?: BaseHttpClient;
82
+ }
83
+ /**
84
+ * A list of URLs to crawl parsed from a sitemap.
85
+ *
86
+ * The loading of the sitemap is performed in the background so that crawling can start before the sitemap is fully loaded.
87
+ */
88
+ export declare class SitemapRequestLoader implements IRequestLoader {
89
+ #private;
90
+ /**
91
+ * Set of URLs that were returned by `fetchNextRequest()` and not marked as handled yet.
92
+ * @internal
93
+ */
94
+ inProgress: Set<string>;
95
+ /** @internal */
96
+ private constructor();
97
+ /**
98
+ * Creates a new object stream with the specified highWaterMark.
99
+ * @param highWaterMark High water mark for the stream (the maximum number of objects the stream will buffer).
100
+ * @returns A new object stream.
101
+ */
102
+ private createNewStream;
103
+ /**
104
+ * Returns a function that checks whether the provided pattern matches the closure URL.
105
+ * @param url URL to be checked.
106
+ * @returns A matcher function that checks whether the pattern matches the closure URL.
107
+ */
108
+ private matchesUrl;
109
+ /**
110
+ * Checks whether the URL matches the `include` / `exclude` patterns provided in the `options`.
111
+ * @param url URL to be checked.
112
+ * @returns `true` if the URL matches the patterns, `false` otherwise.
113
+ */
114
+ private isUrlMatchingPatterns;
115
+ /**
116
+ * Adds a URL to the queue of parsed URLs.
117
+ *
118
+ * Blocks if the stream is full until it is drained.
119
+ */
120
+ private pushNextUrl;
121
+ /**
122
+ * Reads the next URL from the queue of parsed URLs.
123
+ *
124
+ * If the stream is empty, blocks until a new URL is pushed.
125
+ * @returns The next URL from the queue or `null` if we have read all URLs.
126
+ */
127
+ private readNextUrl;
128
+ /**
129
+ * Indicates whether the background processing of sitemap contents has successfully finished.
130
+ *
131
+ * If this is `false`, the background processing is either still in progress or was aborted.
132
+ */
133
+ isSitemapFullyLoaded(): boolean;
134
+ /**
135
+ * Start processing the sitemaps and loading the URLs.
136
+ *
137
+ * Resolves once all the sitemaps URLs have been fully loaded (sets `isSitemapFullyLoaded` to `true`).
138
+ */
139
+ private load;
140
+ /**
141
+ * Open a sitemap and start processing it.
142
+ *
143
+ * 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.
144
+ *
145
+ * Track the loading progress using the `isSitemapFullyLoaded` property.
146
+ */
147
+ static open(options: SitemapRequestLoaderOptions): Promise<SitemapRequestLoader>;
148
+ /**
149
+ * @inheritDoc
150
+ */
151
+ getTotalCount(): Promise<number>;
152
+ /**
153
+ * @inheritDoc
154
+ */
155
+ getPendingCount(): Promise<number>;
156
+ /**
157
+ * Combines this list with a request manager (a {@link RequestQueue} by default) into a
158
+ * {@link RequestManagerTandem}, allowing requests to be added and reclaimed while still
159
+ * being read from this list first.
160
+ */
161
+ toTandem(requestManager?: IRequestManager): Promise<IRequestManager>;
162
+ /**
163
+ * @inheritDoc
164
+ */
165
+ checkReadiness(): Promise<RequestLoaderStatus>;
166
+ /**
167
+ * @inheritDoc
168
+ */
169
+ getHandledCount(): Promise<number>;
170
+ /**
171
+ * @inheritDoc
172
+ */
173
+ persistState(): Promise<void>;
174
+ private restoreState;
175
+ /**
176
+ * @inheritDoc
177
+ */
178
+ fetchNextRequest(): Promise<Request | null>;
179
+ /**
180
+ * @inheritDoc
181
+ */
182
+ // @ts-ignore optional peer dependency or compatibility with es2022
183
+ [Symbol.asyncIterator](): AsyncGenerator<Request<import("@crawlee/types").Dictionary>, void, unknown>;
184
+ /**
185
+ * Aborts the internal sitemap loading, stops the processing of the sitemap contents and drops all the pending URLs.
186
+ *
187
+ * Calling `fetchNextRequest()` after this method will always return `null`.
188
+ */
189
+ teardown(): Promise<void>;
190
+ /**
191
+ * @inheritDoc
192
+ */
193
+ markRequestAsHandled(request: Request): Promise<void>;
194
+ private ensureInProgress;
195
+ }
196
+ export {};
@@ -0,0 +1,432 @@
1
+ import { Transform } from 'node:stream';
2
+ import { EnqueueStrategy, parseSitemap } from '@crawlee/utils';
3
+ import { minimatch } from 'minimatch';
4
+ import { z } from 'zod';
5
+ import { EventType, KeyValueStore, purgeDefaultStorages, Request, RequestManagerTandem, RequestQueue, serviceLocator, } from '@crawlee/core';
6
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
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
+ }