@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.
- package/README.md +1 -1
- package/index.d.ts +11 -1
- package/index.js +11 -0
- package/internals/autoscaling/autoscaled_pool.d.ts +178 -0
- package/internals/autoscaling/autoscaled_pool.js +387 -0
- package/internals/autoscaling/concurrency_system.d.ts +235 -0
- package/internals/autoscaling/concurrency_system.js +357 -0
- package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
- package/internals/autoscaling/cpu_load_signal.js +46 -0
- package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/internals/autoscaling/event_loop_load_signal.js +60 -0
- package/internals/autoscaling/index.d.ts +9 -0
- package/internals/autoscaling/index.js +9 -0
- package/internals/autoscaling/load_signal.d.ts +98 -0
- package/internals/autoscaling/load_signal.js +103 -0
- package/internals/autoscaling/memory_load_signal.d.ts +45 -0
- package/internals/autoscaling/memory_load_signal.js +104 -0
- package/internals/autoscaling/snapshotter.d.ts +84 -0
- package/internals/autoscaling/snapshotter.js +67 -0
- package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/internals/autoscaling/storage_backend_load_signal.js +73 -0
- package/internals/autoscaling/system_status.d.ts +112 -0
- package/internals/autoscaling/system_status.js +139 -0
- package/internals/autoscaling/weighted_avg.d.ts +5 -0
- package/internals/autoscaling/weighted_avg.js +14 -0
- package/internals/basic-crawler.d.ts +185 -389
- package/internals/basic-crawler.js +982 -684
- package/internals/cookie_utils.d.ts +40 -0
- package/internals/cookie_utils.js +122 -0
- package/internals/crawler-run.d.ts +76 -0
- package/internals/crawler-run.js +142 -0
- package/internals/crawlers/context_pipeline.d.ts +75 -0
- package/internals/crawlers/context_pipeline.js +109 -0
- package/internals/crawlers/crawler_commons.d.ts +216 -0
- package/internals/crawlers/crawler_commons.js +1 -0
- package/internals/crawlers/error_snapshotter.d.ts +29 -0
- package/internals/crawlers/error_snapshotter.js +116 -0
- package/internals/crawlers/error_tracker.d.ts +51 -0
- package/internals/crawlers/error_tracker.js +316 -0
- package/internals/crawlers/index.d.ts +4 -0
- package/internals/crawlers/index.js +3 -0
- package/internals/crawlers/internals/types.d.ts +7 -0
- package/internals/crawlers/internals/types.js +1 -0
- package/internals/crawlers/statistics.d.ts +316 -0
- package/internals/crawlers/statistics.js +525 -0
- package/internals/crawling_request.d.ts +86 -0
- package/internals/crawling_request.js +127 -0
- package/internals/enqueue_links/enqueue_links.d.ts +152 -0
- package/internals/enqueue_links/enqueue_links.js +76 -0
- package/internals/enqueue_links/index.d.ts +3 -0
- package/internals/enqueue_links/index.js +3 -0
- package/internals/enqueue_links/shared.d.ts +106 -0
- package/internals/enqueue_links/shared.js +258 -0
- package/internals/errors.d.ts +68 -0
- package/internals/errors.js +83 -0
- package/internals/http.d.ts +9 -0
- package/internals/http.js +28 -0
- package/internals/request-timeout.d.ts +6 -0
- package/internals/request-timeout.js +27 -2
- package/internals/router.d.ts +299 -0
- package/internals/router.js +312 -0
- package/internals/send-request.d.ts +2 -1
- package/internals/send-request.js +1 -0
- package/internals/session_pool/consts.d.ts +1 -0
- package/internals/session_pool/consts.js +1 -0
- package/internals/session_pool/errors.d.ts +7 -0
- package/internals/session_pool/errors.js +11 -0
- package/internals/session_pool/fingerprint.d.ts +9 -0
- package/internals/session_pool/fingerprint.js +30 -0
- package/internals/session_pool/index.d.ts +4 -0
- package/internals/session_pool/index.js +4 -0
- package/internals/session_pool/session.d.ts +151 -0
- package/internals/session_pool/session.js +225 -0
- package/internals/session_pool/session_pool.d.ts +193 -0
- package/internals/session_pool/session_pool.js +453 -0
- package/internals/sitemap_request_loader.d.ts +158 -0
- package/internals/sitemap_request_loader.js +432 -0
- package/internals/throttling_request_manager.d.ts +229 -0
- package/internals/throttling_request_manager.js +843 -0
- package/package.json +17 -14
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { URL } from 'node:url';
|
|
2
|
+
import { Minimatch } from 'minimatch';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { Request } from '@crawlee/core';
|
|
5
|
+
import { schemas } from '@crawlee/utils/internal';
|
|
6
|
+
const MAX_ENQUEUE_LINKS_CACHE_SIZE = 1000;
|
|
7
|
+
/**
|
|
8
|
+
* To keep high performance when the same patterns are passed on every `enqueueLinks()` call,
|
|
9
|
+
* each glob/regexp is only compiled once and then kept in a cache.
|
|
10
|
+
* @ignore
|
|
11
|
+
*/
|
|
12
|
+
const enqueueLinksPatternCache = new Map();
|
|
13
|
+
/**
|
|
14
|
+
* Accepts one {@link UrlPatternInput} — a glob string, a RegExp instance, or a `{ glob }` / `{ regexp }` object.
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
export const urlPatternSchema = z.union([
|
|
18
|
+
z.string(),
|
|
19
|
+
z.instanceof(RegExp),
|
|
20
|
+
schemas.objectWithKeys(['glob']),
|
|
21
|
+
schemas.objectWithKeys(['regexp']),
|
|
22
|
+
]);
|
|
23
|
+
/**
|
|
24
|
+
* Builds the `{ request, reason }` argument passed to a {@link SkippedRequestCallback}, constructing the
|
|
25
|
+
* `Request` lazily on first access to `request` (and caching it) since most skips are never observed by a
|
|
26
|
+
* real callback and building a `Request` isn't free.
|
|
27
|
+
* @ignore
|
|
28
|
+
*/
|
|
29
|
+
export function createSkippedRequestArgs(source, reason) {
|
|
30
|
+
let request;
|
|
31
|
+
return {
|
|
32
|
+
reason,
|
|
33
|
+
get request() {
|
|
34
|
+
request ??=
|
|
35
|
+
source instanceof Request
|
|
36
|
+
? source
|
|
37
|
+
: new Request(typeof source === 'string' ? { url: source } : source);
|
|
38
|
+
return request;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* @ignore
|
|
44
|
+
*/
|
|
45
|
+
export function updateEnqueueLinksPatternCache(item, pattern) {
|
|
46
|
+
enqueueLinksPatternCache.set(item, pattern);
|
|
47
|
+
if (enqueueLinksPatternCache.size > MAX_ENQUEUE_LINKS_CACHE_SIZE) {
|
|
48
|
+
const key = enqueueLinksPatternCache.keys().next().value;
|
|
49
|
+
enqueueLinksPatternCache.delete(key);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Helper factory used in the `enqueueLinks()` and enqueueLinksByClickingElements() function
|
|
54
|
+
* to construct Glob objects from Glob pattern strings.
|
|
55
|
+
* @ignore
|
|
56
|
+
*/
|
|
57
|
+
export function constructGlobObjectsFromGlobs(globs) {
|
|
58
|
+
return globs
|
|
59
|
+
.filter((glob) => {
|
|
60
|
+
// Skip possibly nullish, empty strings
|
|
61
|
+
if (!glob) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (typeof glob === 'string') {
|
|
65
|
+
return glob.trim().length > 0;
|
|
66
|
+
}
|
|
67
|
+
if (glob.glob) {
|
|
68
|
+
return glob.glob.trim().length > 0;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
})
|
|
72
|
+
.map((item) => {
|
|
73
|
+
// Get glob object from cache.
|
|
74
|
+
let globObject = enqueueLinksPatternCache.get(item);
|
|
75
|
+
if (globObject)
|
|
76
|
+
return globObject;
|
|
77
|
+
if (typeof item === 'string') {
|
|
78
|
+
globObject = { glob: validateGlobPattern(item) };
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
globObject = { glob: validateGlobPattern(item.glob) };
|
|
82
|
+
}
|
|
83
|
+
updateEnqueueLinksPatternCache(item, globObject);
|
|
84
|
+
return globObject;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* @internal
|
|
89
|
+
*/
|
|
90
|
+
export function validateGlobPattern(glob) {
|
|
91
|
+
const globTrimmed = glob.trim();
|
|
92
|
+
if (globTrimmed.length === 0)
|
|
93
|
+
throw new Error(`Cannot parse Glob pattern '${globTrimmed}': it must be an non-empty string`);
|
|
94
|
+
return globTrimmed;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Helper factory used in the `enqueueLinks()` and enqueueLinksByClickingElements() function
|
|
98
|
+
* to check RegExps input and return valid RegExps.
|
|
99
|
+
* @ignore
|
|
100
|
+
*/
|
|
101
|
+
export function constructRegExpObjectsFromRegExps(regexps) {
|
|
102
|
+
return regexps.map((item) => {
|
|
103
|
+
// Get regexp object from cache.
|
|
104
|
+
let regexpObject = enqueueLinksPatternCache.get(item);
|
|
105
|
+
if (regexpObject)
|
|
106
|
+
return regexpObject;
|
|
107
|
+
if (item instanceof RegExp) {
|
|
108
|
+
regexpObject = { regexp: item };
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
regexpObject = { regexp: item.regexp };
|
|
112
|
+
}
|
|
113
|
+
updateEnqueueLinksPatternCache(item, regexpObject);
|
|
114
|
+
return regexpObject;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Helper factory used in the `enqueueLinks()` function to construct UrlPatternObjects
|
|
119
|
+
* from a mixed array of glob strings, glob objects, RegExp instances, and regexp objects.
|
|
120
|
+
* @ignore
|
|
121
|
+
*/
|
|
122
|
+
export function constructUrlPatternObjects(patterns) {
|
|
123
|
+
const result = [];
|
|
124
|
+
for (const item of patterns) {
|
|
125
|
+
if (typeof item === 'string' || 'glob' in item) {
|
|
126
|
+
result.push(...constructGlobObjectsFromGlobs([item]));
|
|
127
|
+
}
|
|
128
|
+
else if (item instanceof RegExp || 'regexp' in item) {
|
|
129
|
+
result.push(...constructRegExpObjectsFromRegExps([item]));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Filters request options by URL patterns.
|
|
136
|
+
*
|
|
137
|
+
* When `includePatterns` is empty/undefined, all options pass through (only exclude filtering applies).
|
|
138
|
+
* @ignore
|
|
139
|
+
*/
|
|
140
|
+
export function filterRequestOptionsByPatterns(requestOptions, includePatterns, excludePatterns = [], strategy, onSkippedRequestOptions) {
|
|
141
|
+
const excludeMatchers = excludePatterns.map(createPatternObjectMatcher);
|
|
142
|
+
const includeMatchers = includePatterns?.length ? includePatterns.map(createPatternObjectMatcher) : undefined;
|
|
143
|
+
return requestOptions
|
|
144
|
+
.filter((opts) => {
|
|
145
|
+
const matchesExclude = excludeMatchers.some(({ match }) => match(opts.url));
|
|
146
|
+
if (matchesExclude) {
|
|
147
|
+
onSkippedRequestOptions?.(opts);
|
|
148
|
+
}
|
|
149
|
+
return !matchesExclude;
|
|
150
|
+
})
|
|
151
|
+
.map((opts) => {
|
|
152
|
+
if (!includeMatchers) {
|
|
153
|
+
return { ...opts, enqueueStrategy: strategy };
|
|
154
|
+
}
|
|
155
|
+
for (const { match } of includeMatchers) {
|
|
156
|
+
if (match(opts.url)) {
|
|
157
|
+
return { ...opts, enqueueStrategy: strategy };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// didn't match any positive pattern
|
|
161
|
+
onSkippedRequestOptions?.(opts);
|
|
162
|
+
return null;
|
|
163
|
+
})
|
|
164
|
+
.filter((opts) => opts !== null);
|
|
165
|
+
}
|
|
166
|
+
function isAbsoluteUrl(url) {
|
|
167
|
+
try {
|
|
168
|
+
// eslint-disable-next-line no-new
|
|
169
|
+
new URL(url);
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* @ignore
|
|
178
|
+
*/
|
|
179
|
+
export function createRequestOptions(sources, options = {}) {
|
|
180
|
+
return sources
|
|
181
|
+
.map((src) => typeof src === 'string'
|
|
182
|
+
? { url: src, enqueueStrategy: options.strategy }
|
|
183
|
+
: { ...src, enqueueStrategy: options.strategy })
|
|
184
|
+
.filter(({ url }) => {
|
|
185
|
+
try {
|
|
186
|
+
return new URL(url, options.baseUrl).href;
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
})
|
|
192
|
+
.map((requestOptions) => {
|
|
193
|
+
// Leave already-absolute URLs untouched - re-deriving them via `new URL()` would normalize them
|
|
194
|
+
// (e.g. adding a trailing slash to a bare domain), which is surprising for URLs that didn't need
|
|
195
|
+
// resolving against `baseUrl` in the first place.
|
|
196
|
+
if (!isAbsoluteUrl(requestOptions.url)) {
|
|
197
|
+
requestOptions.url = new URL(requestOptions.url, options.baseUrl).href;
|
|
198
|
+
}
|
|
199
|
+
requestOptions.userData ??= options.userData ?? {};
|
|
200
|
+
if (typeof options.label === 'string') {
|
|
201
|
+
requestOptions.userData = {
|
|
202
|
+
...requestOptions.userData,
|
|
203
|
+
label: options.label,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
if (options.skipNavigation) {
|
|
207
|
+
requestOptions.skipNavigation = true;
|
|
208
|
+
}
|
|
209
|
+
if (options.sessionId) {
|
|
210
|
+
requestOptions.sessionId = options.sessionId;
|
|
211
|
+
}
|
|
212
|
+
return requestOptions;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* @ignore
|
|
217
|
+
*/
|
|
218
|
+
function createPatternObjectMatcher(urlPatternObject) {
|
|
219
|
+
const { regexp, glob } = urlPatternObject;
|
|
220
|
+
let match;
|
|
221
|
+
if (regexp) {
|
|
222
|
+
match = (url) => regexp.test(url);
|
|
223
|
+
}
|
|
224
|
+
else if (glob) {
|
|
225
|
+
const m = new Minimatch(glob, { nocase: true });
|
|
226
|
+
match = (url) => m.match(url);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
match = () => false;
|
|
230
|
+
}
|
|
231
|
+
return { match };
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Applies a {@link RequestTransform} function to a list of request options.
|
|
235
|
+
* Options for which the transform returns a falsy value are removed from the list.
|
|
236
|
+
* @param onSkipped Called with the original request options when the transform returns a falsy value (i.e. the request is skipped).
|
|
237
|
+
* @ignore
|
|
238
|
+
* @internal
|
|
239
|
+
*/
|
|
240
|
+
export function applyRequestTransform(requestOptions, transformFn, onSkipped) {
|
|
241
|
+
return requestOptions
|
|
242
|
+
.map((opts) => {
|
|
243
|
+
const transformed = transformFn(opts);
|
|
244
|
+
if (transformed === 'skip') {
|
|
245
|
+
onSkipped?.(opts);
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
if (transformed === 'unchanged') {
|
|
249
|
+
return opts;
|
|
250
|
+
}
|
|
251
|
+
if (!transformed) {
|
|
252
|
+
onSkipped?.(opts);
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return transformed;
|
|
256
|
+
})
|
|
257
|
+
.filter((r) => r !== null);
|
|
258
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { CriticalError, NonRetryableError } from '@crawlee/core';
|
|
2
|
+
import type { SkippedRequestReason } from './crawling_request.js';
|
|
3
|
+
/**
|
|
4
|
+
* @ignore
|
|
5
|
+
*/
|
|
6
|
+
export declare class MissingRouteError extends CriticalError {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Errors of `RetryRequestError` type will always be retried by the crawler.
|
|
10
|
+
*
|
|
11
|
+
* *This error overrides the `maxRequestRetries` option, i.e. the request can be retried indefinitely until it succeeds.*
|
|
12
|
+
*/
|
|
13
|
+
export declare class RetryRequestError extends Error {
|
|
14
|
+
constructor(message?: string);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Thrown when a domain has rate-limited us and the request should simply be attempted again later.
|
|
18
|
+
*
|
|
19
|
+
* The request is reclaimed without recording a failure: it costs neither a retry nor session reputation, because
|
|
20
|
+
* nothing about the request or the session was at fault. A {@link ThrottlingRequestManager} holds it back until
|
|
21
|
+
* the domain's backoff expires, so retries are paced rather than immediate.
|
|
22
|
+
*/
|
|
23
|
+
export declare class RequestThrottledError extends RetryRequestError {
|
|
24
|
+
constructor(message?: string);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Thrown when a domain has rate-limited us for so long that no request has got through, and the crawl is
|
|
28
|
+
* abandoned rather than kept waiting.
|
|
29
|
+
*
|
|
30
|
+
* Waiting longer will not help: at this point the concurrency is too high for the domain, or it has blocked us.
|
|
31
|
+
* The affected requests are deliberately left in their queue, so re-running the crawl without purging storages
|
|
32
|
+
* resumes them once the domain recovers.
|
|
33
|
+
*/
|
|
34
|
+
export declare class PersistentRateLimitError extends CriticalError {
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Thrown when a requested session is not found in the referenced SessionPool.
|
|
38
|
+
*/
|
|
39
|
+
export declare class MissingSessionError extends Error {
|
|
40
|
+
constructor(sessionId?: string);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Settles the request as skipped rather than failed: no retry, no failure, and its storage writes are rolled back.
|
|
44
|
+
* Use {@link RestrictedCrawlingContext.skipRequest|`context.skipRequest()`} rather than throwing this directly.
|
|
45
|
+
* @internal
|
|
46
|
+
*/
|
|
47
|
+
export declare class ContextPipelineInterruptedError extends Error {
|
|
48
|
+
readonly reason: SkippedRequestReason;
|
|
49
|
+
readonly skipMessage?: string | undefined;
|
|
50
|
+
constructor(reason: SkippedRequestReason, skipMessage?: string | undefined);
|
|
51
|
+
}
|
|
52
|
+
export declare class ContextPipelineCleanupError extends CriticalError {
|
|
53
|
+
constructor(error: unknown, options?: ErrorOptions);
|
|
54
|
+
}
|
|
55
|
+
/** Wraps a failure of a context pipeline middleware, telling it apart from a {@link RequestHandlerError}. */
|
|
56
|
+
export declare class ContextPipelineInitializationError extends Error {
|
|
57
|
+
constructor(error: unknown, options?: ErrorOptions);
|
|
58
|
+
}
|
|
59
|
+
/** Wraps a failure of the context pipeline's final consumer (the request handler), telling it apart from a middleware failure. */
|
|
60
|
+
export declare class RequestHandlerError extends Error {
|
|
61
|
+
constructor(error: unknown, options?: ErrorOptions);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Thrown by crawlers when `skipNavigation` is used on a request.
|
|
65
|
+
* Subclasses can catch this error to skip their own navigation-dependent logic.
|
|
66
|
+
*/
|
|
67
|
+
export declare class NavigationSkippedError extends NonRetryableError {
|
|
68
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { CriticalError, NonRetryableError } from '@crawlee/core';
|
|
2
|
+
/**
|
|
3
|
+
* @ignore
|
|
4
|
+
*/
|
|
5
|
+
export class MissingRouteError extends CriticalError {
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Errors of `RetryRequestError` type will always be retried by the crawler.
|
|
9
|
+
*
|
|
10
|
+
* *This error overrides the `maxRequestRetries` option, i.e. the request can be retried indefinitely until it succeeds.*
|
|
11
|
+
*/
|
|
12
|
+
export class RetryRequestError extends Error {
|
|
13
|
+
constructor(message) {
|
|
14
|
+
super(message ?? "Request is being retried at the user's request");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Thrown when a domain has rate-limited us and the request should simply be attempted again later.
|
|
19
|
+
*
|
|
20
|
+
* The request is reclaimed without recording a failure: it costs neither a retry nor session reputation, because
|
|
21
|
+
* nothing about the request or the session was at fault. A {@link ThrottlingRequestManager} holds it back until
|
|
22
|
+
* the domain's backoff expires, so retries are paced rather than immediate.
|
|
23
|
+
*/
|
|
24
|
+
export class RequestThrottledError extends RetryRequestError {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message ?? 'Request is being retried later because its domain is rate-limiting us');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Thrown when a domain has rate-limited us for so long that no request has got through, and the crawl is
|
|
31
|
+
* abandoned rather than kept waiting.
|
|
32
|
+
*
|
|
33
|
+
* Waiting longer will not help: at this point the concurrency is too high for the domain, or it has blocked us.
|
|
34
|
+
* The affected requests are deliberately left in their queue, so re-running the crawl without purging storages
|
|
35
|
+
* resumes them once the domain recovers.
|
|
36
|
+
*/
|
|
37
|
+
export class PersistentRateLimitError extends CriticalError {
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Thrown when a requested session is not found in the referenced SessionPool.
|
|
41
|
+
*/
|
|
42
|
+
export class MissingSessionError extends Error {
|
|
43
|
+
constructor(sessionId) {
|
|
44
|
+
super(`The current SessionPool instance couldn't find a valid session${sessionId ? ` for the following id: ${sessionId}.` : '.'}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Settles the request as skipped rather than failed: no retry, no failure, and its storage writes are rolled back.
|
|
49
|
+
* Use {@link RestrictedCrawlingContext.skipRequest|`context.skipRequest()`} rather than throwing this directly.
|
|
50
|
+
* @internal
|
|
51
|
+
*/
|
|
52
|
+
export class ContextPipelineInterruptedError extends Error {
|
|
53
|
+
reason;
|
|
54
|
+
skipMessage;
|
|
55
|
+
constructor(reason, skipMessage) {
|
|
56
|
+
super(skipMessage ?? 'Request was skipped');
|
|
57
|
+
this.reason = reason;
|
|
58
|
+
this.skipMessage = skipMessage;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export class ContextPipelineCleanupError extends CriticalError {
|
|
62
|
+
constructor(error, options) {
|
|
63
|
+
super(undefined, { cause: error, ...options });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Wraps a failure of a context pipeline middleware, telling it apart from a {@link RequestHandlerError}. */
|
|
67
|
+
export class ContextPipelineInitializationError extends Error {
|
|
68
|
+
constructor(error, options) {
|
|
69
|
+
super(undefined, { cause: error, ...options });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Wraps a failure of the context pipeline's final consumer (the request handler), telling it apart from a middleware failure. */
|
|
73
|
+
export class RequestHandlerError extends Error {
|
|
74
|
+
constructor(error, options) {
|
|
75
|
+
super(undefined, { cause: error, ...options });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Thrown by crawlers when `skipNavigation` is used on a request.
|
|
80
|
+
* Subclasses can catch this error to skip their own navigation-dependent logic.
|
|
81
|
+
*/
|
|
82
|
+
export class NavigationSkippedError extends NonRetryableError {
|
|
83
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a `Retry-After` response header into a delay in milliseconds.
|
|
3
|
+
*
|
|
4
|
+
* The header holds either a non-negative number of seconds or an HTTP-date.
|
|
5
|
+
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After).
|
|
6
|
+
*
|
|
7
|
+
* @returns The delay in milliseconds, or `null` if the header is absent, unparseable, or already elapsed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function parseRetryAfterHeader(value?: string | null): number | null;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a `Retry-After` response header into a delay in milliseconds.
|
|
3
|
+
*
|
|
4
|
+
* The header holds either a non-negative number of seconds or an HTTP-date.
|
|
5
|
+
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After).
|
|
6
|
+
*
|
|
7
|
+
* @returns The delay in milliseconds, or `null` if the header is absent, unparseable, or already elapsed.
|
|
8
|
+
*/
|
|
9
|
+
export function parseRetryAfterHeader(value) {
|
|
10
|
+
if (!value) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
const trimmed = value.trim();
|
|
14
|
+
// Per the spec this is a `delay-seconds`: digits only, so a negative or fractional value is not one.
|
|
15
|
+
if (/^\d+$/.test(trimmed)) {
|
|
16
|
+
// `Retry-After: 0` names no future deadline, same as an HTTP-date that has already passed. Reporting it
|
|
17
|
+
// as a zero delay would leave the domain unthrottled while still counting as a rate-limit event, so the
|
|
18
|
+
// caller would defer the request for free and re-send it immediately.
|
|
19
|
+
const delayMs = Number(trimmed) * 1000;
|
|
20
|
+
return delayMs > 0 ? delayMs : null;
|
|
21
|
+
}
|
|
22
|
+
const date = Date.parse(trimmed);
|
|
23
|
+
if (!Number.isNaN(date)) {
|
|
24
|
+
const delayMs = date - Date.now();
|
|
25
|
+
return delayMs > 0 ? delayMs : null;
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
@@ -16,10 +16,16 @@ export declare const extendTimeoutKey: unique symbol;
|
|
|
16
16
|
* bail, so a request whose timeout already elapsed does not carry on after the crawler moved past it.
|
|
17
17
|
*/
|
|
18
18
|
export declare const timeoutExpiredKey: unique symbol;
|
|
19
|
+
/**
|
|
20
|
+
* Stops the internal request timeout's clock until the returned callback is called. Error handling has a timeout
|
|
21
|
+
* of its own, and must not be cut short (and handled again) by the request timeout.
|
|
22
|
+
*/
|
|
23
|
+
export declare const suspendTimeoutKey: unique symbol;
|
|
19
24
|
/** The slots the internal request timeout hangs on the in-flight crawling context. */
|
|
20
25
|
export interface RequestTimeoutContext {
|
|
21
26
|
[extendTimeoutKey]?: (extraMillis: number) => void;
|
|
22
27
|
[timeoutExpiredKey]?: () => boolean;
|
|
28
|
+
[suspendTimeoutKey]?: () => () => void;
|
|
23
29
|
[navigationDeadlineKey]?: number;
|
|
24
30
|
}
|
|
25
31
|
/**
|
|
@@ -17,6 +17,11 @@ export const extendTimeoutKey = Symbol('extendTimeout');
|
|
|
17
17
|
* bail, so a request whose timeout already elapsed does not carry on after the crawler moved past it.
|
|
18
18
|
*/
|
|
19
19
|
export const timeoutExpiredKey = Symbol('timeoutExpired');
|
|
20
|
+
/**
|
|
21
|
+
* Stops the internal request timeout's clock until the returned callback is called. Error handling has a timeout
|
|
22
|
+
* of its own, and must not be cut short (and handled again) by the request timeout.
|
|
23
|
+
*/
|
|
24
|
+
export const suspendTimeoutKey = Symbol('suspendTimeout');
|
|
20
25
|
/**
|
|
21
26
|
* Milliseconds left in the shared navigation window for `ctx`, lazily starting the window on first use.
|
|
22
27
|
* @internal
|
|
@@ -46,21 +51,41 @@ export async function raceWithTimeout(context, work, { timeoutMillis, requestId
|
|
|
46
51
|
let deadline = Date.now() + timeoutMillis;
|
|
47
52
|
let settled = false;
|
|
48
53
|
let firedByTimeout = false;
|
|
54
|
+
let suspendedAt;
|
|
49
55
|
const timeout = new Promise((_, reject) => {
|
|
50
56
|
const fire = () => {
|
|
51
57
|
settled = true;
|
|
52
58
|
firedByTimeout = true;
|
|
53
59
|
reject(new TimeoutError(`Request timed out after ${timeoutMillis / 1e3} seconds (${requestId}).`));
|
|
54
60
|
};
|
|
61
|
+
const schedule = () => {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
timer = setTimeout(fire, Math.max(deadline - Date.now(), 0));
|
|
64
|
+
};
|
|
55
65
|
timer = setTimeout(fire, timeoutMillis);
|
|
56
66
|
context[timeoutExpiredKey] = () => firedByTimeout;
|
|
57
67
|
context[extendTimeoutKey] = (extraMillis) => {
|
|
58
68
|
if (settled) {
|
|
59
69
|
return;
|
|
60
70
|
}
|
|
61
|
-
clearTimeout(timer);
|
|
62
71
|
deadline += extraMillis;
|
|
63
|
-
|
|
72
|
+
if (suspendedAt === undefined) {
|
|
73
|
+
schedule();
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
context[suspendTimeoutKey] = () => {
|
|
77
|
+
if (settled || suspendedAt !== undefined) {
|
|
78
|
+
return () => { };
|
|
79
|
+
}
|
|
80
|
+
clearTimeout(timer);
|
|
81
|
+
suspendedAt = Date.now();
|
|
82
|
+
return () => {
|
|
83
|
+
deadline += Date.now() - suspendedAt;
|
|
84
|
+
suspendedAt = undefined;
|
|
85
|
+
if (!settled) {
|
|
86
|
+
schedule();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
64
89
|
};
|
|
65
90
|
});
|
|
66
91
|
try {
|