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

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 +378 -369
  27. package/internals/basic-crawler.js +1449 -862
  28. package/internals/cookie_utils.d.ts +40 -0
  29. package/internals/cookie_utils.js +122 -0
  30. package/internals/crawler-run.d.ts +76 -0
  31. package/internals/crawler-run.js +142 -0
  32. package/internals/crawlers/context_pipeline.d.ts +75 -0
  33. package/internals/crawlers/context_pipeline.js +109 -0
  34. package/internals/crawlers/crawler_commons.d.ts +216 -0
  35. package/internals/crawlers/crawler_commons.js +1 -0
  36. package/internals/crawlers/error_snapshotter.d.ts +29 -0
  37. package/internals/crawlers/error_snapshotter.js +116 -0
  38. package/internals/crawlers/error_tracker.d.ts +51 -0
  39. package/internals/crawlers/error_tracker.js +316 -0
  40. package/internals/crawlers/index.d.ts +4 -0
  41. package/internals/crawlers/index.js +3 -0
  42. package/internals/crawlers/internals/types.d.ts +7 -0
  43. package/internals/crawlers/internals/types.js +1 -0
  44. package/internals/crawlers/statistics.d.ts +316 -0
  45. package/internals/crawlers/statistics.js +525 -0
  46. package/internals/crawling_request.d.ts +86 -0
  47. package/internals/crawling_request.js +127 -0
  48. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  49. package/internals/enqueue_links/enqueue_links.js +76 -0
  50. package/internals/enqueue_links/index.d.ts +3 -0
  51. package/internals/enqueue_links/index.js +3 -0
  52. package/internals/enqueue_links/shared.d.ts +106 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +68 -0
  55. package/internals/errors.js +83 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +54 -0
  59. package/internals/request-timeout.js +98 -0
  60. package/internals/router.d.ts +299 -0
  61. package/internals/router.js +312 -0
  62. package/internals/send-request.d.ts +4 -4
  63. package/internals/send-request.js +4 -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
@@ -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
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The shared navigation-window deadline (epoch millis), stored on the in-flight context so the pre- and
3
+ * post-navigation hooks and the navigation itself all draw from one budget - and so `context.extendTimeout`
4
+ * can push the whole window, not just the current step.
5
+ * @internal
6
+ */
7
+ export declare const navigationDeadlineKey: unique symbol;
8
+ /**
9
+ * Lets `context.extendTimeout` push back the internal request timeout as well. That timeout is a bare timer
10
+ * rather than an `addTimeoutToPromise` frame, so `extendTimeout` from `@apify/timeout` cannot reach it on its own.
11
+ */
12
+ export declare const extendTimeoutKey: unique symbol;
13
+ /**
14
+ * Returns `true` once the internal request timeout has fired for this request. It cannot cancel work stuck
15
+ * somewhere we do not control, but the phases we do run (e.g. the request handler) check this at their start and
16
+ * bail, so a request whose timeout already elapsed does not carry on after the crawler moved past it.
17
+ */
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;
24
+ /** The slots the internal request timeout hangs on the in-flight crawling context. */
25
+ export interface RequestTimeoutContext {
26
+ [extendTimeoutKey]?: (extraMillis: number) => void;
27
+ [timeoutExpiredKey]?: () => boolean;
28
+ [suspendTimeoutKey]?: () => () => void;
29
+ [navigationDeadlineKey]?: number;
30
+ }
31
+ /**
32
+ * Milliseconds left in the shared navigation window for `ctx`, lazily starting the window on first use.
33
+ * @internal
34
+ */
35
+ export declare function remainingNavigationWindowMillis(ctx: object, windowMillis: number): number;
36
+ /**
37
+ * Races `work` against a `timeoutMillis` timeout, so a request stuck in a phase that has no timeout of its own
38
+ * (anything that is not the navigation, a navigation hook or the request handler) still fails instead of stalling
39
+ * the crawler.
40
+ *
41
+ * This is a bare timer, not an `addTimeoutToPromise` frame: nested `addTimeoutToPromise` calls share one
42
+ * `AbortController`, so wrapping the request in one would let the request handler timing out abort this outer
43
+ * context too, cancelling the error handling that follows it.
44
+ *
45
+ * `Promise.race` attaches a handler to both sides, so a late rejection from `work` cannot go unhandled. The losing
46
+ * side is not cancelled - by definition it is stuck somewhere we do not control - but the phases we do run check
47
+ * {@link timeoutExpiredKey} at their start and bail, so a request whose timeout already fired does not carry
48
+ * on (e.g. run the handler) after the crawler has moved past it. `context.extendTimeout` pushes the deadline back
49
+ * via {@link extendTimeoutKey}.
50
+ */
51
+ export declare function raceWithTimeout(context: RequestTimeoutContext, work: Promise<void>, { timeoutMillis, requestId }: {
52
+ timeoutMillis: number;
53
+ requestId?: string;
54
+ }): Promise<void>;
@@ -0,0 +1,98 @@
1
+ import { TimeoutError } from '@apify/timeout';
2
+ /**
3
+ * The shared navigation-window deadline (epoch millis), stored on the in-flight context so the pre- and
4
+ * post-navigation hooks and the navigation itself all draw from one budget - and so `context.extendTimeout`
5
+ * can push the whole window, not just the current step.
6
+ * @internal
7
+ */
8
+ export const navigationDeadlineKey = Symbol('navigationDeadline');
9
+ /**
10
+ * Lets `context.extendTimeout` push back the internal request timeout as well. That timeout is a bare timer
11
+ * rather than an `addTimeoutToPromise` frame, so `extendTimeout` from `@apify/timeout` cannot reach it on its own.
12
+ */
13
+ export const extendTimeoutKey = Symbol('extendTimeout');
14
+ /**
15
+ * Returns `true` once the internal request timeout has fired for this request. It cannot cancel work stuck
16
+ * somewhere we do not control, but the phases we do run (e.g. the request handler) check this at their start and
17
+ * bail, so a request whose timeout already elapsed does not carry on after the crawler moved past it.
18
+ */
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');
25
+ /**
26
+ * Milliseconds left in the shared navigation window for `ctx`, lazily starting the window on first use.
27
+ * @internal
28
+ */
29
+ export function remainingNavigationWindowMillis(ctx, windowMillis) {
30
+ const store = ctx;
31
+ store[navigationDeadlineKey] ??= Date.now() + windowMillis;
32
+ return store[navigationDeadlineKey] - Date.now();
33
+ }
34
+ /**
35
+ * Races `work` against a `timeoutMillis` timeout, so a request stuck in a phase that has no timeout of its own
36
+ * (anything that is not the navigation, a navigation hook or the request handler) still fails instead of stalling
37
+ * the crawler.
38
+ *
39
+ * This is a bare timer, not an `addTimeoutToPromise` frame: nested `addTimeoutToPromise` calls share one
40
+ * `AbortController`, so wrapping the request in one would let the request handler timing out abort this outer
41
+ * context too, cancelling the error handling that follows it.
42
+ *
43
+ * `Promise.race` attaches a handler to both sides, so a late rejection from `work` cannot go unhandled. The losing
44
+ * side is not cancelled - by definition it is stuck somewhere we do not control - but the phases we do run check
45
+ * {@link timeoutExpiredKey} at their start and bail, so a request whose timeout already fired does not carry
46
+ * on (e.g. run the handler) after the crawler has moved past it. `context.extendTimeout` pushes the deadline back
47
+ * via {@link extendTimeoutKey}.
48
+ */
49
+ export async function raceWithTimeout(context, work, { timeoutMillis, requestId }) {
50
+ let timer;
51
+ let deadline = Date.now() + timeoutMillis;
52
+ let settled = false;
53
+ let firedByTimeout = false;
54
+ let suspendedAt;
55
+ const timeout = new Promise((_, reject) => {
56
+ const fire = () => {
57
+ settled = true;
58
+ firedByTimeout = true;
59
+ reject(new TimeoutError(`Request timed out after ${timeoutMillis / 1e3} seconds (${requestId}).`));
60
+ };
61
+ const schedule = () => {
62
+ clearTimeout(timer);
63
+ timer = setTimeout(fire, Math.max(deadline - Date.now(), 0));
64
+ };
65
+ timer = setTimeout(fire, timeoutMillis);
66
+ context[timeoutExpiredKey] = () => firedByTimeout;
67
+ context[extendTimeoutKey] = (extraMillis) => {
68
+ if (settled) {
69
+ return;
70
+ }
71
+ deadline += extraMillis;
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
+ };
89
+ };
90
+ });
91
+ try {
92
+ await Promise.race([work, timeout]);
93
+ }
94
+ finally {
95
+ settled = true;
96
+ clearTimeout(timer);
97
+ }
98
+ }