Skip to content
Myr

Improve `Retry-After` handling (#874)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by GitHub · parent 06375ef · Browse files · 9 files+1326 added−173 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+1326 added−173 removed

  • tests:+960 added−84 removed
  • other:+366 added−89 removed

9 files+1326 added−173 removed

modified:source/core/Ky.ts+169 added-71 removed
28 unmodified lines
29import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';30import isRawNetworkError from '../utils/is-network-error.js';31import {isHTTPError, isNetworkError, isTimeoutError} from '../utils/type-guards.js';32import {33 calculateRetryTimingDelay,34 getRetryTimingHeader,35} from './retry-timing.js';36import {37 maxSafeTimeout,38 responseTypes,39 stop,40 RetryMarker,
7 unmodified lines
48const maxErrorResponseBodySize = 10 * 1024 * 1024;49const prefixUrlRenamedErrorMessage = 'The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl';50const timedOutResponseData = Symbol('timedOutResponseData');5152type ErrorDataTimeout = {53 milliseconds: number;54 fromTotalTimeout: boolean;55};5657const createTextDecoder = (contentType: string): TextDecoder => {58 const match = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(contentType);59 const charset = match?.[1] ?? match?.[2];60 if (charset) {
203 unmodified lines
264 const result = (async () => {265 try {266 return await function_();267 } catch (error: unknown) {259 // Non-Error throws (e.g., thrown strings) pass through unchanged260 if (!(error instanceof Error)) {261 throw error;262 }263264 // Errors thrown by beforeRetry hooks must propagate unchanged.265 if (ky.#beforeRetryHookErrors.has(error)) {266 throw error;267 }268269 let processedError: Error = error;270 for (const hook of ky.#options.hooks.beforeError) {271 // `request` is the current failing request. `options` intentionally remains the272 // stable normalized Ky options snapshot for the same reason as `HTTPError` above.273 // eslint-disable-next-line no-await-in-loop274 const hookResult: unknown = await hook({275 request: ky.request,276 options: ky.#getNormalizedOptions(),277 error: processedError,278 retryCount: ky.#retryCount,279 });280281 // Only overwrite if the hook returns a valid Error instance.282 if (hookResult instanceof Error) {283 processedError = hookResult;284 }285 }286287 throw processedError;268 await ky.#throwProcessedError(error);269 } finally {270 const originalRequest = ky.#originalRequest;271272 // Ignore cancellation errors from already-locked or already-consumed streams.
20 unmodified lines
293294 const response = await result;295296 if (type !== 'json') {316 return response[type]();297 return ky.#raceBodyRead(async () => response[type](), response);298 }299300 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;301 const request = ky.#getResponseRequest(response);319 const text = await response.text();320 if (text === '') {321 if (schema !== undefined) {322 return validateJsonWithSchema(undefined, schema);302 return ky.#raceWithTotalTimeout(async () => {303 if (text === '') {304 if (schema !== undefined) {305 return validateJsonWithSchema(undefined, schema);306 }307308 return JSON.parse(text);309 }310325 return JSON.parse(text);326 }311 const jsonValue = initHookOptions.parseJson312 ? await initHookOptions.parseJson(text, {request, response})313 : JSON.parse(text);314328 const jsonValue = initHookOptions.parseJson329 ? await initHookOptions.parseJson(text, {request: ky.#getResponseRequest(response), response})330 : JSON.parse(text);331332 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);315 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);316 }, request);317 };318 }319320 return result;
11 unmodified lines
332333 public request: Request;334 #abortController?: AbortController;335 #retryCount = 0;352 // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202353 #input: Input;336 readonly #input: Input;337 readonly #options: InternalOptions;338 #originalRequest?: Request;339 readonly #userProvidedAbortSignal?: AbortSignal;340 readonly #beforeRetryHookErrors = new WeakSet<Error>();
160 unmodified lines
501 if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {502 throw error;503 }504522 // User-provided shouldRetry function takes precedence over default checks (retryOnTimeout, status codes, etc.)505 if (this.#options.retry.shouldRetry !== undefined) {506 const result = await this.#options.retry.shouldRetry({error: errorObject, retryCount: this.#retryCount + 1});507526 // Strict boolean checking - only exact true/false are handled specially508 // Only exact booleans override the default retry checks.509 if (result === false) {510 throw error;511 }512513 if (result === true) {532 // Force retry - skip all other validation and return delay514 return this.#calculateDelay();515 }535536 // If undefined or any other value, fall through to default behavior516 }517518 // Default timeout behavior519 if (isTimeoutError(error)) {
8 unmodified lines
528 if (!this.#options.retry.statusCodes.includes(error.response.status)) {529 throw error;530 }531553 const retryAfter = error.response.headers.get('Retry-After')554 ?? error.response.headers.get('RateLimit-Reset')555 ?? error.response.headers.get('X-RateLimit-Retry-After') // Symfony-based services556 ?? error.response.headers.get('X-RateLimit-Reset') // GitHub557 ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter558 if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) {559 let after = Number(retryAfter) * 1000;560 if (Number.isNaN(after)) {561 after = Date.parse(retryAfter) - Date.now();562 } else if (after >= Date.parse('2024-01-01')) {563 // A large number is treated as a timestamp (fixed threshold protects against clock skew)564 after -= Date.now();532 const retryTimingHeader = getRetryTimingHeader(error.response.headers);533 if (retryTimingHeader && this.#options.retry.afterStatusCodes.includes(error.response.status)) {534 const after = calculateRetryTimingDelay(retryTimingHeader);535 if (after === undefined) {536 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.537 return this.#calculateDelay();538 }539567 if (!Number.isFinite(after)) {568 return Math.min(this.#options.retry.maxRetryAfter, this.#calculateDelay());569 }570571 after = Math.max(0, after);572540 // Don't apply jitter when server provides explicit retry timing541 return Math.min(this.#options.retry.maxRetryAfter, after);542 }543
28 unmodified lines
572573 return response;574 }575576 async #throwProcessedError(error: unknown): Promise<never> {577 // Non-Error throws (e.g., thrown strings) pass through unchanged578 if (!(error instanceof Error)) {579 throw error;580 }581582 // Errors thrown by beforeRetry hooks must propagate unchanged.583 if (this.#beforeRetryHookErrors.has(error)) {584 throw error;585 }586587 let processedError: Error = error;588 for (const hook of this.#options.hooks.beforeError) {589 // `request` is the current failing request. `options` intentionally remains the590 // stable normalized Ky options snapshot for the same reason as `HTTPError` above.591 // eslint-disable-next-line no-await-in-loop592 const hookResult: unknown = await hook({593 request: this.request,594 options: this.#getNormalizedOptions(),595 error: processedError,596 retryCount: this.#retryCount,597 });598599 // Only overwrite if the hook returns a valid Error instance.600 if (hookResult instanceof Error) {601 processedError = hookResult;602 }603 }604605 throw processedError;606 }607608 async #getResponseData(response: Response): Promise<unknown> {609 // Even with request timeouts disabled, bound error-body reads so retries and error propagation610 // cannot be stalled indefinitely by never-ending response streams.611 const readTimeout = this.#getErrorDataTimeout();612 const text = await this.#readResponseText(response, this.#getErrorDataTimeout());612 const text = await this.#readResponseText(response, readTimeout.milliseconds);613 if (text === timedOutResponseData) {614 if (readTimeout.fromTotalTimeout) {615 throw new TimeoutError(this.request);616 }617618 this.#throwIfTotalTimeoutExhausted();619 return undefined;620 }621
4 unmodified lines
626 if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {627 return text;628 }629630 const parseTimeout = this.#getErrorDataTimeout();626 const data = await this.#parseJson(text, response, this.#getErrorDataTimeout(), this.#getResponseRequest(response));631 const data = await this.#parseJson(text, response, parseTimeout.milliseconds, this.#getResponseRequest(response));632 if (data === timedOutResponseData) {633 if (parseTimeout.fromTotalTimeout) {634 throw new TimeoutError(this.request);635 }636637 this.#throwIfTotalTimeoutExhausted();638 return undefined;639 }640641 return data;642 }643635 #getErrorDataTimeout(): number {644 #getErrorDataTimeout(): ErrorDataTimeout {645 const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;646 const remainingTotal = this.#getRemainingTotalTimeout();647 if (remainingTotal === undefined) {639 return errorDataTimeout;648 return {649 milliseconds: errorDataTimeout,650 fromTotalTimeout: false,651 };652 }653654 if (remainingTotal <= 0) {655 throw new TimeoutError(this.request);656 }657646 return Math.min(errorDataTimeout, remainingTotal);658 return {659 milliseconds: Math.min(errorDataTimeout, remainingTotal),660 fromTotalTimeout: remainingTotal <= errorDataTimeout,661 };662 }663664 #getBodyReadTimeout(): number | undefined {665 const remainingTotal = this.#getRemainingTotalTimeout();666 if (remainingTotal !== undefined) {667 if (remainingTotal <= 0) {668 throw new TimeoutError(this.request);669 }670671 return this.#options.timeout === false672 ? remainingTotal673 : Math.min(this.#options.timeout, remainingTotal);674 }675676 return this.#options.timeout === false ? undefined : this.#options.timeout;677 }678679 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -680 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.681 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {682 let timeoutMs: number | undefined;683 try {684 timeoutMs = this.#getBodyReadTimeout();685 } catch (error: unknown) {686 await this.#throwProcessedError(error);687 }688689 const bodyPromise = createBodyPromise();690 if (timeoutMs === undefined) {691 return bodyPromise;692 }693694 const result = await Promise.race([695 bodyPromise,696 new Promise<typeof timedOutResponseData>(resolve => {697 const timeoutId = setTimeout(() => {698 resolve(timedOutResponseData);699 }, timeoutMs);700 void bodyPromise.finally(() => {701 clearTimeout(timeoutId);702 }).catch(() => undefined);703 }),704 ]);705706 if (result === timedOutResponseData) {707 // The stream is locked by the native body method's own reader by this point, so708 // `response.body.cancel()` would reject as "already locked". Aborting the request's709 // signal is what actually interrupts the underlying network read.710 this.#abortController?.abort();711 await this.#throwProcessedError(new TimeoutError(this.#getResponseRequest(response)));712 }713714 return result;715 }716717 async #raceWithTotalTimeout<T>(operation: () => Promise<T>, request: Request): Promise<T> {718 const remainingTotal = this.#getRemainingTotalTimeout();719 if (remainingTotal === undefined) {720 return operation();721 }722723 if (remainingTotal <= 0) {724 await this.#throwProcessedError(new TimeoutError(request));725 }726727 const operationPromise = operation();728 const result = await Promise.race<T | typeof timedOutResponseData>([729 operationPromise,730 new Promise<typeof timedOutResponseData>(resolve => {731 const timeoutId = setTimeout(() => {732 resolve(timedOutResponseData);733 }, remainingTotal);734 void operationPromise.finally(() => {735 clearTimeout(timeoutId);736 }).catch(() => undefined);737 }),738 ]);739740 if (result === timedOutResponseData) {741 await this.#throwProcessedError(new TimeoutError(request));742 }743744 return result as T;745 }746747 #isJsonContentType(contentType: string): boolean {748 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.749 const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();750 return /\/(?:.*[.+-])?json$/.test(mimeType);
390 unmodified lines
added:source/core/retry-timing.ts+173 added
1// Older epoch-second values are indistinguishable from ordinary delay seconds, so timestamp compatibility only applies to current-era reset headers.2const timestampThreshold = Date.parse('2024-01-01');3const delayPattern = /^\d+$/;4const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];56// HTTP-date parsing is limited to IMF-fixdate and the two obsolete HTTP-date formats. Other date-like strings intentionally fall back to the normal retry delay.7const imfDatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;8const rfc850DatePattern = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;9const asctimeDatePattern = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}:\d{2}:\d{2}) (\d{4})$/;1011type RetryTimingHeader = {12 value: string;13 allowTimestamp: boolean;14};1516type RetryTimingDateParts = {17 year: number;18 month: string;19 day: string;20 hours: string;21 minutes: string;22 seconds: string;23};2425export const getRetryTimingHeader = (headers: Headers): RetryTimingHeader | undefined => {26 const retryAfter = headers.get('Retry-After');27 if (retryAfter !== null) {28 return {value: retryAfter, allowTimestamp: false};29 }3031 // Retry-After is authoritative when present. Only missing Retry-After falls through to rate-limit headers.32 const rateLimitReset = headers.get('RateLimit-Reset');33 if (rateLimitReset !== null) {34 return {value: rateLimitReset, allowTimestamp: true};35 }3637 const rateLimitRetryAfter = headers.get('X-RateLimit-Retry-After'); // Symfony-based services38 if (rateLimitRetryAfter !== null) {39 return {value: rateLimitRetryAfter, allowTimestamp: false};40 }4142 const rateLimitResetAlias = headers.get('X-RateLimit-Reset') // GitHub43 ?? headers.get('X-Rate-Limit-Reset'); // Twitter44 if (rateLimitResetAlias !== null) {45 return {value: rateLimitResetAlias, allowTimestamp: true};46 }4748 return undefined;49};5051const createTimestamp = ({year, month, day, hours, minutes, seconds}: RetryTimingDateParts): number | undefined => {52 const monthIndex = months.indexOf(month);53 const dayNumber = Number(day);54 const hoursNumber = Number(hours);55 const minutesNumber = Number(minutes);56 const secondsNumber = Number(seconds);57 if (58 monthIndex === -159 || hoursNumber > 2360 || minutesNumber > 5961 || secondsNumber > 6062 ) {63 return undefined;64 }6566 const normalizedSeconds = Math.min(secondsNumber, 59);67 const date = new Date(Date.UTC(year, monthIndex, dayNumber, hoursNumber, minutesNumber, normalizedSeconds));68 date.setUTCFullYear(year);69 const timestamp = date.getTime();7071 // Date.UTC normalizes overflow, so round-trip the parts to reject invalid dates. A leap second is represented by parsing 60 as 59 and adding one second.72 if (73 date.getUTCFullYear() !== year74 || date.getUTCMonth() !== monthIndex75 || date.getUTCDate() !== dayNumber76 || date.getUTCHours() !== hoursNumber77 || date.getUTCMinutes() !== minutesNumber78 || date.getUTCSeconds() !== normalizedSeconds79 ) {80 return undefined;81 }8283 return secondsNumber === 60 ? timestamp + 1000 : timestamp;84};8586const getCapture = (match: RegExpExecArray, index: number): string => match[index]!;8788const parseDate = (value: string): number | undefined => {89 const imfDate = imfDatePattern.exec(value);90 if (imfDate) {91 return createTimestamp({92 year: Number(getCapture(imfDate, 3)),93 month: getCapture(imfDate, 2),94 day: getCapture(imfDate, 1),95 hours: getCapture(imfDate, 4),96 minutes: getCapture(imfDate, 5),97 seconds: getCapture(imfDate, 6),98 });99 }100101 const rfc850Date = rfc850DatePattern.exec(value);102 if (rfc850Date) {103 const now = new Date();104 const twoDigitYear = Number(getCapture(rfc850Date, 3));105 const currentCenturyYear = (Math.floor(now.getUTCFullYear() / 100) * 100) + twoDigitYear;106 const fiftyYearsFromNow = Date.UTC(now.getUTCFullYear() + 50, now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());107 let timestamp: number | undefined;108109 // RFC 9110 maps two-digit years to the latest matching century that is not more than 50 years in the future.110 for (const year of [111 currentCenturyYear - 100,112 currentCenturyYear,113 currentCenturyYear + 100,114 ]) {115 const candidateTimestamp = createTimestamp({116 year,117 month: getCapture(rfc850Date, 2),118 day: getCapture(rfc850Date, 1),119 hours: getCapture(rfc850Date, 4),120 minutes: getCapture(rfc850Date, 5),121 seconds: getCapture(rfc850Date, 6),122 });123 if (124 candidateTimestamp !== undefined125 && candidateTimestamp <= fiftyYearsFromNow126 ) {127 timestamp = candidateTimestamp;128 }129 }130131 return timestamp;132 }133134 const asctimeDate = asctimeDatePattern.exec(value);135 if (asctimeDate) {136 const time = getCapture(asctimeDate, 4);137 const [hours, minutes, seconds] = time.split(':') as [string, string, string];138 return createTimestamp({139 year: Number(getCapture(asctimeDate, 5)),140 month: getCapture(asctimeDate, 2),141 day: getCapture(asctimeDate, 3).trim(),142 hours,143 minutes,144 seconds,145 });146 }147148 return undefined;149};150151export const calculateRetryTimingDelay = ({value, allowTimestamp}: RetryTimingHeader): number | undefined => {152 if (delayPattern.test(value)) {153 let delay = Number(value) * 1000;154155 // Standard Retry-After numbers are delay seconds. Timestamp compatibility only applies to reset headers.156 if (157 allowTimestamp158 && delay >= timestampThreshold159 ) {160 delay -= Date.now();161 }162163 return Math.max(0, delay);164 }165166 const timestamp = parseDate(value);167 if (timestamp === undefined) {168 return undefined;169 }170171 const delay = timestamp - Date.now();172 return Number.isFinite(delay) ? Math.max(0, delay) : undefined;173};
modified:source/errors/HTTPError.ts+1 added-1 removed
4 unmodified lines
56/**7Error thrown when the response has a non-2xx status code and `throwHttpErrors` is enabled.89The error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request), and a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the `parseJson` option if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty or parsing fails, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` population is bounded by the request timeout and a 10 MiB response body size limit. The `data` property is populated before `beforeError` hooks run, so hooks can access it.9The error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request), and a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the `parseJson` option if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty, unreadable, too large, parsing fails, or the error-data read/parse timeout is reached, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` body reads and async JSON parsing are bounded by the request timeout (or 10 seconds when `timeout` is disabled), any remaining `totalTimeout` budget, and a 10 MiB response body size limit. If `totalTimeout` expires while populating `error.data`, Ky throws `TimeoutError` instead of `HTTPError`. The `data` property is populated before `beforeError` hooks run, so hooks can access it.1011The response body is automatically consumed when populating `error.data`, so `error.response.json()` and other body methods will not work. Use `error.data` instead. The `error.response` object is still available for headers, status, etc.1213Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError` and will not contain a `response` property.
21 unmodified lines
modified:source/types/hooks.ts+1 added-1 removed
173 unmodified lines
174 **Warning:** Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.175176 The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.177178 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body will be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.178 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.179180 You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).181182 **Modifying headers:**
183 unmodified lines
modified:source/types/options.ts+6 added-4 removed
172 unmodified lines
173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174175 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.176177 If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, delay, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.177 `413 Payload Too Large` is only retried when the response includes a retry timing header.178179 If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.179 When the response status is contained in both `statusCodes` and `afterStatusCodes`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as current-era Unix timestamps. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.180181 If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.182183 @example184 ```185 import ky from 'ky';186187 const json = await ky('https://example.com', {188 retry: {189 limit: 10,190 methods: ['get'],189 statusCodes: [413]191 statusCodes: [500]192 }193 }).json();194 ```195 */196 retry?: RetryOptions | number;197198 /**197 Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Cannot be greater than 2147483647. See also `totalTimeout`.199 Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Cannot be greater than 2147483647. See also `totalTimeout`.200201 If set to `false`, there will be no per-attempt timeout.202203 @default 10000
273 unmodified lines
modified:source/types/retry.ts+6 added-4 removed
modified:test/main.ts+357 added-4 removed
780 unmodified lines
781782 t.is(requestCount, 0);783});784785test('timeout option is cancelled when the promise is resolved', async t => {785test.serial('timeout option is cancelled when the promise is resolved', async t => {786 const server = await createHttpTestServer(t);787788 server.get('/', (request, response) => {789 response.end(request.method);790 });791792 const originalSetTimeout = globalThis.setTimeout;793 const originalClearTimeout = globalThis.clearTimeout;794 let requestTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;795 let didClearRequestTimeout = false;796797 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {798 const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);799 if (delayMs === 2000) {800 requestTimeoutId = timeoutId;801 }802803 return timeoutId;804 }) as typeof globalThis.setTimeout;805806 globalThis.clearTimeout = (timeoutId => {807 if (timeoutId === requestTimeoutId) {808 didClearRequestTimeout = true;809 }810811 originalClearTimeout(timeoutId);812 }) as typeof globalThis.clearTimeout;813814 try {815 await ky(server.url, {timeout: 2000});816 } finally {817 globalThis.setTimeout = originalSetTimeout;818 globalThis.clearTimeout = originalClearTimeout;819 }820821 t.truthy(requestTimeoutId);822 t.true(didClearRequestTimeout);823});824825test.serial('timeout option is cancelled when a shortcut body read is resolved', async t => {826 const request = ky('https://example.com', {827 fetch: async () => new Response('ok'),828 timeout: 2000,829 });830831 await request;832833 const originalSetTimeout = globalThis.setTimeout;834 const originalClearTimeout = globalThis.clearTimeout;835 let bodyTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;836 let didClearBodyTimeout = false;837838 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {839 const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);840 if (delayMs === 2000) {841 bodyTimeoutId = timeoutId;842 }843844 return timeoutId;845 }) as typeof globalThis.setTimeout;846847 globalThis.clearTimeout = (timeoutId => {848 if (timeoutId === bodyTimeoutId) {849 didClearBodyTimeout = true;850 }851852 originalClearTimeout(timeoutId);853 }) as typeof globalThis.clearTimeout;854855 try {856 t.is(await request.text(), 'ok');857 } finally {858 globalThis.setTimeout = originalSetTimeout;859 globalThis.clearTimeout = originalClearTimeout;860 }861862 t.truthy(bodyTimeoutId);863 t.true(didClearBodyTimeout);864});865866test('timeout bounds a never-ending successful response body', async t => {867 let didStartBodyRead = false;868869 const customFetch: typeof fetch = async () => {870 const response = new Response(undefined, {871 status: 200,872 headers: {'content-type': 'application/json'},873 });874875 response.text = async () => {876 didStartBodyRead = true;877 return new Promise<string>(resolve => {878 t.teardown(() => {879 resolve('');880 });881 });882 };883884 return response;885 };886887 const start = Date.now();888 await t.throwsAsync(ky('https://example.com', {889 fetch: customFetch,890 timeout: 50,891 }).json(), {892 instanceOf: TimeoutError,893 });894 t.true(didStartBodyRead);895 t.true(Date.now() - start < 2000);896});897794 await ky(server.url, {timeout: 2000});898test('totalTimeout bounds a never-ending successful response body', async t => {899 let didStartBodyRead = false;900796 const duration = start - Date.now();901 const customFetch: typeof fetch = async () => {902 const response = new Response(undefined, {status: 200});903 response.text = async () => {904 didStartBodyRead = true;905 return new Promise<string>(resolve => {906 t.teardown(() => {907 resolve('');908 });909 });910 };911798 t.true(duration < 10);912 return response;913 };914915 const start = Date.now();916 await t.throwsAsync(ky('https://example.com', {917 fetch: customFetch,918 timeout: false,919 totalTimeout: 50,920 }).text(), {921 instanceOf: TimeoutError,922 });923 t.true(didStartBodyRead);924 t.true(Date.now() - start < 2000);925});926927test('beforeError hook receives totalTimeout exhausted before a shortcut body read starts', async t => {928 let didReadBody = false;929 let hookError: Error | undefined;930931 const customFetch: typeof fetch = async () => {932 const response = new Response('ok');933 response.text = async () => {934 didReadBody = true;935 return 'ok';936 };937938 return response;939 };940941 const response = ky('https://example.com', {942 fetch: customFetch,943 timeout: false,944 totalTimeout: 250,945 hooks: {946 beforeError: [947 ({error}) => {948 hookError = error;949 error.message = 'pre-read-timeout-beforeError';950 return error;951 },952 ],953 },954 });955956 await response;957 await delay(300);958959 await t.throwsAsync(response.text(), {960 instanceOf: TimeoutError,961 message: 'pre-read-timeout-beforeError',962 });963964 t.false(didReadBody);965 t.true(hookError instanceof TimeoutError);966});967968test('timeout aborts a never-ending successful response body read', async t => {969 let didAbort = false;970 const customFetch: typeof fetch = async request => {971 request.signal.addEventListener('abort', () => {972 didAbort = true;973 }, {once: true});974975 const body = new ReadableStream<Uint8Array>({976 start(controller) {977 controller.enqueue(new TextEncoder().encode('partial'));978 },979 });980981 return new Response(body, {status: 200});982 };983984 await t.throwsAsync(ky('https://example.com', {985 fetch: customFetch,986 timeout: 50,987 }).text(), {988 instanceOf: TimeoutError,989 });990991 t.true(didAbort);992});993994test('timeout does not retry a never-ending successful response body read', async t => {995 let requestCount = 0;996 const customFetch: typeof fetch = async () => {997 requestCount++;998999 const body = new ReadableStream<Uint8Array>({1000 start(controller) {1001 controller.enqueue(new TextEncoder().encode('partial'));1002 },1003 });10041005 return new Response(body, {status: 200});1006 };10071008 await t.throwsAsync(ky('https://example.com', {1009 fetch: customFetch,1010 timeout: 50,1011 retry: {1012 limit: 2,1013 delay: () => 0,1014 retryOnTimeout: true,1015 },1016 }).text(), {1017 instanceOf: TimeoutError,1018 });10191020 t.is(requestCount, 1);1021});10221023test('beforeError hook receives successful response body TimeoutError', async t => {1024 let hookError: Error | undefined;1025 const customFetch: typeof fetch = async () => {1026 const body = new ReadableStream<Uint8Array>({1027 start(controller) {1028 controller.enqueue(new TextEncoder().encode('partial'));1029 },1030 });10311032 return new Response(body, {status: 200});1033 };10341035 await t.throwsAsync(ky('https://example.com', {1036 fetch: customFetch,1037 timeout: 50,1038 hooks: {1039 beforeError: [1040 ({error}) => {1041 hookError = error;1042 error.message = 'body-timeout-beforeError';1043 return error;1044 },1045 ],1046 },1047 }).text(), {1048 instanceOf: TimeoutError,1049 message: 'body-timeout-beforeError',1050 });10511052 t.true(hookError instanceof TimeoutError);1053});10541055test('totalTimeout bounds hanging parseJson on successful response shortcut', async t => {1056 let parseJsonCalled = false;1057 let hookError: Error | undefined;1058 const start = Date.now();1059 await t.throwsAsync(ky('https://example.com', {1060 fetch: async () => new Response('{"value":1}', {1061 headers: {'content-type': 'application/json'},1062 }),1063 timeout: false,1064 totalTimeout: 250,1065 parseJson: async () => new Promise<never>(() => {1066 parseJsonCalled = true;1067 // Intentionally never settles1068 }),1069 hooks: {1070 beforeError: [1071 ({error}) => {1072 hookError = error;1073 error.message = 'parse-timeout-beforeError';1074 return error;1075 },1076 ],1077 },1078 }).json(), {1079 instanceOf: TimeoutError,1080 message: 'parse-timeout-beforeError',1081 });10821083 t.true(parseJsonCalled);1084 t.true(hookError instanceof TimeoutError);1085 t.true(Date.now() - start < 2000);1086});10871088test('totalTimeout bounds hanging schema validation on successful response shortcut', async t => {1089 let schemaValidationCalled = false;1090 const schema = createSchema(async () => new Promise<never>(() => {1091 schemaValidationCalled = true;1092 // Intentionally never settles1093 }));10941095 const start = Date.now();1096 await t.throwsAsync(ky('https://example.com', {1097 fetch: async () => new Response('{"value":1}', {1098 headers: {'content-type': 'application/json'},1099 }),1100 timeout: false,1101 totalTimeout: 250,1102 }).json(schema), {1103 instanceOf: TimeoutError,1104 });11051106 t.true(schemaValidationCalled);1107 t.true(Date.now() - start < 2000);1108});11091110test.serial('timeout false does not apply a successful response body timeout', async t => {1111 const originalSetTimeout = globalThis.setTimeout;1112 const scheduledDelays: number[] = [];1113 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {1114 if (delayMs === 10_000) {1115 scheduledDelays.push(delayMs);1116 }11171118 const testDelay = delayMs === 10_000 ? 0 : delayMs;1119 return originalSetTimeout(handler, testDelay, ...arguments_);1120 }) as typeof globalThis.setTimeout;11211122 const abortController = new AbortController();1123 const request = ky('https://example.com', {1124 async fetch(request) {1125 const body = new ReadableStream<Uint8Array>({1126 start(controller) {1127 controller.enqueue(new TextEncoder().encode('partial'));1128 request.signal.addEventListener('abort', () => {1129 controller.error(new DOMException('Aborted', 'AbortError'));1130 }, {once: true});1131 },1132 });11331134 return new Response(body);1135 },1136 signal: abortController.signal,1137 timeout: false,1138 }).text();11391140 try {1141 t.is(await Promise.race([1142 request.then(() => 'settled').catch(() => 'settled'),1143 delay(50).then(() => 'pending'),1144 ]), 'pending');1145 } finally {1146 abortController.abort();1147 await request.catch(() => undefined);1148 globalThis.setTimeout = originalSetTimeout;1149 }11501151 t.deepEqual(scheduledDelays, []);1152});11531154test('normalizing retry options does not mutate the caller retry object', async t => {1155 const retry = {1156 methods: ['GET'],1157 };
1699 unmodified lines
modified:test/retry.ts+603 added-80 removed
1import process from 'node:process';2import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';3import test, {type ExecutionContext} from 'ava';4import ky, {5 NetworkError,6 TimeoutError,7 isKyError,
6 unmodified lines
14const fixture = 'fixture';15const defaultRetryCount = 2;16const retryAfterOn500 = 2;17const retryAfterOn413 = 2;18const retryAfterTimestampText = '1704067200';19const retryAfterTimestampScheduledDelay = 2_147_483_647;20const httpDateDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];21const httpDateLongDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];22const httpDateMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];2324const formatHttpTime = (date: Date) => [25 date.getUTCHours(),26 date.getUTCMinutes(),27 date.getUTCSeconds(),28].map(value => value.toString().padStart(2, '0')).join(':');2930const formatAsctimeDate = (date: Date) => {31 const day = date.getUTCDate().toString().padStart(2, ' ');3233 return `${httpDateDayNames[date.getUTCDay()]} ${httpDateMonths[date.getUTCMonth()]} ${day} ${formatHttpTime(date)} ${date.getUTCFullYear()}`;34};3536const formatRfc850Date = (date: Date) => {37 const day = date.getUTCDate().toString().padStart(2, '0');38 const year = (date.getUTCFullYear() % 100).toString().padStart(2, '0');3940 return `${httpDateLongDayNames[date.getUTCDay()]}, ${day}-${httpDateMonths[date.getUTCMonth()]}-${year} ${formatHttpTime(date)} GMT`;41};4243const withCapturedTimeouts = async (body: (scheduledDelays: number[]) => Promise<void>) => {44 const originalSetTimeout = globalThis.setTimeout;45 const scheduledDelays: number[] = [];4647 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {48 if (typeof delayMs === 'number') {49 scheduledDelays.push(delayMs);50 }5152 const testDelayMs = typeof delayMs === 'number' && delayMs > 1_000_000 ? 0 : delayMs;53 return originalSetTimeout(handler, testDelayMs, ...arguments_);54 }) as typeof globalThis.setTimeout;5556 try {57 await body(scheduledDelays);58 } finally {59 globalThis.setTimeout = originalSetTimeout;60 }61};6263const createSingleRetryHeaderServer = async (t: ExecutionContext, headers: Record<string, string | number>) => {64 let requestCount = 0;6566 const server = await createHttpTestServer(t);67 server.get('/', (_request, response) => {68 requestCount++;69 if (requestCount === 2) {70 response.end(fixture);71 return;72 }7374 response.writeHead(429, headers);75 response.end('');76 });7778 return {79 server,80 get requestCount() {81 return requestCount;82 },83 };84};8586test('network error', async t => {87 let requestCount = 0;8889 const server = await createHttpTestServer(t);
133 unmodified lines
223224 t.is(requestCount, 5);225});226159test('RateLimit-Reset is treated the same as Retry-After', async t => {227test.serial('Retry-After number is treated as delay seconds, not timestamp', async t => {228 const retryServer = await createSingleRetryHeaderServer(t, {229 'Retry-After': retryAfterTimestampText,230 });231232 await withCapturedTimeouts(async scheduledDelays => {233 t.is(await ky(retryServer.server.url, {234 retry: {235 limit: 1,236 },237 }).text(), fixture);238239 t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));240 });241242 t.is(retryServer.requestCount, 2);243});244245test.serial('invalid Retry-After number 0x10 falls back to retry delay', async t => {246 const retryServer = await createSingleRetryHeaderServer(t, {247 'Retry-After': '0x10',248 });249250 await withCapturedTimeouts(async scheduledDelays => {251 t.is(await ky(retryServer.server.url, {252 timeout: false,253 retry: {254 limit: 1,255 delay: () => 10,256 },257 }).text(), fixture);258259 t.true(scheduledDelays.includes(10));260 });261262 t.is(retryServer.requestCount, 2);263});264265test.serial('X-RateLimit-Retry-After number is treated as delay seconds, not timestamp', async t => {266 const retryServer = await createSingleRetryHeaderServer(t, {267 'X-RateLimit-Retry-After': retryAfterTimestampText,268 });269270 await withCapturedTimeouts(async scheduledDelays => {271 t.is(await ky(retryServer.server.url, {272 retry: {273 limit: 1,274 },275 }).text(), fixture);276277 t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));278 });279280 t.is(retryServer.requestCount, 2);281});282283test.serial('Retry-After takes precedence over RateLimit-Reset', async t => {284 const retryServer = await createSingleRetryHeaderServer(t, {285 'Retry-After': '1',286 'RateLimit-Reset': retryAfterTimestampText,287 });288289 await withCapturedTimeouts(async scheduledDelays => {290 t.is(await ky(retryServer.server.url, {291 retry: {292 limit: 1,293 },294 }).text(), fixture);295296 t.true(scheduledDelays.includes(1000));297 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));298 });299300 t.is(retryServer.requestCount, 2);301});302303test.serial('invalid Retry-After does not fall back to RateLimit-Reset', async t => {304 const retryServer = await createSingleRetryHeaderServer(t, {305 'Retry-After': '1e3',306 'RateLimit-Reset': retryAfterTimestampText,307 });308309 await withCapturedTimeouts(async scheduledDelays => {310 t.is(await ky(retryServer.server.url, {311 retry: {312 limit: 1,313 delay: () => 23,314 },315 }).text(), fixture);316317 t.true(scheduledDelays.includes(23));318 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));319 });320321 t.is(retryServer.requestCount, 2);322});323324test.serial('empty Retry-After does not fall back to RateLimit-Reset', async t => {325 const retryServer = await createSingleRetryHeaderServer(t, {326 'Retry-After': '',327 'RateLimit-Reset': retryAfterTimestampText,328 });329330 await withCapturedTimeouts(async scheduledDelays => {331 t.is(await ky(retryServer.server.url, {332 retry: {333 limit: 1,334 delay: () => 31,335 },336 }).text(), fixture);337338 t.true(scheduledDelays.includes(31));339 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));340 });341342 t.is(retryServer.requestCount, 2);343});344345test.serial('non-standard Retry-After date falls back to retry delay', async t => {346 const retryServer = await createSingleRetryHeaderServer(t, {347 'Retry-After': 'Sun Nov 06 1994 08:49:37 GMT',348 });349350 await withCapturedTimeouts(async scheduledDelays => {351 t.is(await ky(retryServer.server.url, {352 retry: {353 limit: 1,354 delay: () => 29,355 },356 }).text(), fixture);357358 t.true(scheduledDelays.includes(29));359 });360361 t.is(retryServer.requestCount, 2);362});363364for (const [dateFormat, formatDate] of [365 ['RFC 850', formatRfc850Date],366 ['asctime', formatAsctimeDate],367] as const) {368 test.serial(`Retry-After supports obsolete HTTP-date format: ${dateFormat}`, async t => {369 const retryAfterDate = formatDate(new Date(Date.now() + 2_000_000));370 const retryServer = await createSingleRetryHeaderServer(t, {371 'Retry-After': retryAfterDate,372 });373374 await withCapturedTimeouts(async scheduledDelays => {375 t.is(await ky(retryServer.server.url, {376 retry: {377 limit: 1,378 delay: () => 13,379 },380 }).text(), fixture);381382 t.true(scheduledDelays.some(delay => delay > 1_000_000));383 t.false(scheduledDelays.includes(13));384 });385386 t.is(retryServer.requestCount, 2);387 });388}389390test.serial('Retry-After asctime HTTP-date is parsed as GMT', async t => {391 const retryAfterDate = formatAsctimeDate(new Date(Date.now() + 2_000_000));392 const retryServer = await createSingleRetryHeaderServer(t, {393 'Retry-After': retryAfterDate,394 });395396 const timeZone = process.env.TZ;397 try {398 process.env.TZ = 'Pacific/Kiritimati';399 await withCapturedTimeouts(async scheduledDelays => {400 t.is(await ky(retryServer.server.url, {401 retry: {402 limit: 1,403 delay: () => 13,404 },405 }).text(), fixture);406407 t.true(scheduledDelays.some(delay => delay > 1_000_000));408 t.false(scheduledDelays.includes(13));409 });410 } finally {411 if (timeZone === undefined) {412 delete process.env.TZ;413 } else {414 process.env.TZ = timeZone;415 }416 }417418 t.is(retryServer.requestCount, 2);419});420421test.serial('Retry-After HTTP-date supports a leap second', async t => {422 const now = Date.now();423 const retryAfterInstant = new Date(now + 2_000_000);424 retryAfterInstant.setUTCSeconds(59, 0);425 const day = retryAfterInstant.getUTCDate().toString().padStart(2, '0');426 const hours = retryAfterInstant.getUTCHours().toString().padStart(2, '0');427 const minutes = retryAfterInstant.getUTCMinutes().toString().padStart(2, '0');428 const dayName = httpDateDayNames[retryAfterInstant.getUTCDay()];429 const month = httpDateMonths[retryAfterInstant.getUTCMonth()];430 const retryAfterDate = `${dayName}, ${day} ${month} ${retryAfterInstant.getUTCFullYear()} ${hours}:${minutes}:60 GMT`;431 const expectedDelay = retryAfterInstant.getTime() + 1000 - now;432433 const retryServer = await createSingleRetryHeaderServer(t, {434 'Retry-After': retryAfterDate,435 });436437 const dateNow = Date.now;438 try {439 Date.now = () => now;440 await withCapturedTimeouts(async scheduledDelays => {441 t.is(await ky(retryServer.server.url, {442 retry: {443 limit: 1,444 delay: () => 13,445 },446 }).text(), fixture);447448 t.true(scheduledDelays.includes(expectedDelay));449 t.false(scheduledDelays.includes(expectedDelay - 1000));450 t.false(scheduledDelays.includes(13));451 });452 } finally {453 Date.now = dateNow;454 }455456 t.is(retryServer.requestCount, 2);457});458459test.serial('Retry-After RFC 850 HTTP-date applies the two-digit year rule', async t => {460 const retryAfterDate = new Date(Date.now() + 2000);461 retryAfterDate.setUTCFullYear(retryAfterDate.getUTCFullYear() + 49);462463 const retryServer = await createSingleRetryHeaderServer(t, {464 'Retry-After': formatRfc850Date(retryAfterDate),465 });466467 await withCapturedTimeouts(async scheduledDelays => {468 t.is(await ky(retryServer.server.url, {469 retry: {470 limit: 1,471 delay: () => 13,472 },473 }).text(), fixture);474475 t.true(scheduledDelays.some(delay => delay > 1_000_000));476 t.false(scheduledDelays.includes(13));477 });478479 t.is(retryServer.requestCount, 2);480});481482test.serial('Retry-After RFC 850 HTTP-date more than 50 years in the future is interpreted as past', async t => {483 const retryAfterDate = new Date(Date.now() + 2000);484 retryAfterDate.setUTCFullYear(retryAfterDate.getUTCFullYear() + 51);485486 const retryServer = await createSingleRetryHeaderServer(t, {487 'Retry-After': formatRfc850Date(retryAfterDate),488 });489490 await withCapturedTimeouts(async scheduledDelays => {491 t.is(await ky(retryServer.server.url, {492 retry: {493 limit: 1,494 delay: () => 13,495 maxRetryAfter: 1,496 },497 }).text(), fixture);498499 t.true(scheduledDelays.includes(0));500 t.false(scheduledDelays.includes(1));501 t.false(scheduledDelays.includes(13));502 });503504 t.is(retryServer.requestCount, 2);505});506507test.serial('invalid Retry-After HTTP-date components fall back to retry delay', async t => {508 const retryServer = await createSingleRetryHeaderServer(t, {509 'Retry-After': 'Sun, 32 Dec 2030 25:99:99 GMT',510 });511512 await withCapturedTimeouts(async scheduledDelays => {513 t.is(await ky(retryServer.server.url, {514 retry: {515 limit: 1,516 delay: () => 17,517 },518 }).text(), fixture);519520 t.true(scheduledDelays.includes(17));521 });522523 t.is(retryServer.requestCount, 2);524});525526test('RateLimit-Reset delay seconds are respected like Retry-After', async t => {527 let requestCount = 0;528529 const server = await createHttpTestServer(t);530 server.get('/', (_request, response) => {
21 unmodified lines
552553 t.is(requestCount, 3);554});555189test('RateLimit-Reset with time since epoch', async t => {556test.serial('RateLimit-Reset with time since epoch', async t => {557 const now = Date.UTC(2026, 0, 1);558 let requestCount = 0;559560 const server = await createHttpTestServer(t);561 server.get('/', (_request, response) => {
1 unmodified line
563564 if (requestCount === defaultRetryCount + 1) {565 response.end(fixture);566 } else {199 const twoSecondsByDelta = 2;200 const oneSecondByEpoch = (Date.now() / 1000) + 1;567 const oneSecondByDelta = 1;568 const threeSecondsByEpoch = (now / 1000) + 3;569 response.writeHead(429, {202 'RateLimit-Reset': (requestCount < 2) ? twoSecondsByDelta : oneSecondByEpoch,570 'RateLimit-Reset': (requestCount < 2) ? oneSecondByDelta : threeSecondsByEpoch,571 });572573 response.end('');574 }575 });576209 await withPerformance({210 t,211 expectedDuration: 2000 + 1000,212 async test() {577 const dateNow = Date.now;578 try {579 Date.now = () => now;580 await withCapturedTimeouts(async scheduledDelays => {581 t.is(await ky(server.url).text(), fixture);214 },215 });582583 t.true(scheduledDelays.includes(1000));584 t.true(scheduledDelays.includes(3000));585 t.true(scheduledDelays.indexOf(1000) < scheduledDelays.indexOf(3000));586 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));587 });588 } finally {589 Date.now = dateNow;590 }591592 t.is(requestCount, 3);593});594595test.serial('empty RateLimit-Reset falls back to retry delay', async t => {596 const retryServer = await createSingleRetryHeaderServer(t, {597 'RateLimit-Reset': '',598 });599600 await withCapturedTimeouts(async scheduledDelays => {601 t.is(await ky(retryServer.server.url, {602 retry: {603 limit: 1,604 delay: () => 37,605 },606 }).text(), fixture);607608 t.true(scheduledDelays.includes(37));609 });610611 t.is(retryServer.requestCount, 2);612});613614test.serial('empty RateLimit-Reset does not fall back to lower-priority reset alias', async t => {615 const retryServer = await createSingleRetryHeaderServer(t, {616 'RateLimit-Reset': '',617 'X-RateLimit-Reset': retryAfterTimestampText,618 });619620 await withCapturedTimeouts(async scheduledDelays => {621 t.is(await ky(retryServer.server.url, {622 retry: {623 limit: 1,624 delay: () => 41,625 },626 }).text(), fixture);627628 t.true(scheduledDelays.includes(41));629 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));630 });631632 t.is(retryServer.requestCount, 2);633});634635for (const rateLimitResetHeader of ['X-RateLimit-Reset', 'X-Rate-Limit-Reset']) {636 test.serial(`${rateLimitResetHeader} supports time since epoch`, async t => {637 const now = Date.UTC(2026, 0, 1);638 const retryServer = await createSingleRetryHeaderServer(t, {639 [rateLimitResetHeader]: (now / 1000) + 2,640 });641642 const dateNow = Date.now;643 try {644 Date.now = () => now;645 await withCapturedTimeouts(async scheduledDelays => {646 t.is(await ky(retryServer.server.url, {647 retry: {648 limit: 1,649 delay: () => 7,650 maxRetryAfter: 3500,651 },652 }).text(), fixture);653654 t.true(scheduledDelays.includes(2000));655 t.false(scheduledDelays.includes(3500));656 t.false(scheduledDelays.includes(7));657 });658 } finally {659 Date.now = dateNow;660 }661662 t.is(retryServer.requestCount, 2);663 });664}665666test('respect 413 Retry-After', async t => {667 const startTime = Date.now();668 let requestCount = 0;669
15 unmodified lines
685 t.true(timeElapsedInMs >= retryAfterOn413 * 1000);686 t.is(requestCount, retryAfterOn413 + 1);687});688243test('respect 413 Retry-After with timestamp', async t => {689test('respect 413 Retry-After with HTTP date', async t => {690 const startTime = Date.now();691 let requestCount = 0;692693 const server = await createHttpTestServer(t, {bodyParser: false});
53 unmodified lines
747 t.true(timeElapsedInMs >= retryAfterOn500 * 1000);748 t.is(requestCount, retryAfterOn500 + 1);749});750751test('custom `afterStatusCodes` does not retry statuses missing from `statusCodes`', async t => {752 let requestCount = 0;753754 const server = await createHttpTestServer(t);755 server.get('/', (_request, response) => {756 requestCount++;757 response.writeHead(400, {758 'Retry-After': 1,759 });760 response.end('');761 });762763 await t.throwsAsync(764 ky(server.url, {765 retry: {766 afterStatusCodes: [400],767 },768 }).text(),769 {770 message: /Bad Request/,771 },772 );773 t.is(requestCount, 1);774});775776test('respect number of retries', async t => {777 let requestCount = 0;778779 const server = await createHttpTestServer(t);
109 unmodified lines
889890 t.is(requestCount, 5);891});892422test('invalid Retry-After header falls back to retry delay', async t => {893test.serial('invalid Retry-After header falls back to retry delay', async t => {894 let requestCount = 0;895896 const server = await createHttpTestServer(t);897 server.get('/', (_request, response) => {
8 unmodified lines
906907 response.end(fixture);908 });909439 const result = await Promise.race([440 ky(server.url, {910 await withCapturedTimeouts(async scheduledDelays => {911 t.is(await ky(server.url, {912 timeout: false,913 retry: {914 limit: 1,444 delay: () => 10,915 delay: () => 50,916 maxRetryAfter: 10,917 },446 }).text(),447 delay(2000).then(() => {448 throw new Error('Retry took too long');449 }),450 ]);918 }).text(), fixture);919452 t.is(result, fixture);920 t.true(scheduledDelays.includes(50));921 t.false(scheduledDelays.includes(10));922 });923924 t.is(requestCount, 2);925});926927test.serial('invalid 413 Retry-After header falls back to retry delay', async t => {928 let requestCount = 0;929930 const server = await createHttpTestServer(t);931 server.get('/', (_request, response) => {932 requestCount++;933 if (requestCount === 1) {934 response.writeHead(413, {935 'Retry-After': 'not-a-valid-value',936 });937 response.end('');938 return;939 }940941 response.end(fixture);942 });943944 await withCapturedTimeouts(async scheduledDelays => {945 t.is(await ky(server.url, {946 timeout: false,947 retry: {948 limit: 1,949 delay: () => 50,950 maxRetryAfter: 10,951 },952 }).text(), fixture);953954 t.true(scheduledDelays.includes(50));955 t.false(scheduledDelays.includes(10));956 });957958 t.is(requestCount, 2);959});960961test('retry - can provide retry as number', async t => {962 let requestCount = 0;963964 const server = await createHttpTestServer(t);
841 unmodified lines
1806 const server = await createHttpTestServer(t);1807 server.get('/', (_request, response) => {1808 requestCount++;1809 if (requestCount === 1) {1305 response.sendStatus(429); // Rate limit1810 response.sendStatus(400);1811 } else if (requestCount === 2) {1307 response.sendStatus(500); // Server error1812 response.sendStatus(500);1813 } else {1814 response.end(fixture);1815 }1816 });
4 unmodified lines
1821 async shouldRetry({error, retryCount}) {1822 const {HTTPError} = await import('../source/index.js');1823 if (error instanceof HTTPError) {1824 const {status} = error.response;1320 // Retry on 429 but only first attempt1321 if (status === 429 && retryCount <= 1) {1825 if (status === 400 && retryCount <= 1) {1826 return true;1827 }18281325 // Don't retry on 4xx1829 if (status >= 400 && status < 500) {1830 return false;1831 }1832 }
119 unmodified lines
1952 t.is(timeoutError?.name, 'TimeoutError');1953 t.is(requestCount, 1);1954});19551453test('Retry-After timestamp delay is bounded by totalTimeout budget', async t => {1454 let requestCount = 0;1455 const server = await createHttpTestServer(t);1456 server.get('/', (_request, response) => {1457 requestCount++;1458 const timestamp = Math.ceil(Date.now() / 1000) + 5;1459 response.writeHead(429, {1460 'Retry-After': timestamp,1461 });1462 response.end('');1463 });14641465 let timeoutError: Error | undefined;1466 await withPerformance({1467 t,1468 expectedDuration: 1000,1469 async test() {1470 timeoutError = await t.throwsAsync(ky(server.url, {1471 totalTimeout: 1000,1472 retry: {1473 limit: 15,1474 },1475 }).text());1476 },1477 });14781479 t.is(timeoutError?.name, 'TimeoutError');1480 t.is(requestCount, 1);1481});14821956test('shouldRetry: precedence over retryOnTimeout', async t => {1957 let requestCount = 0;19581959 const server = await createHttpTestServer(t);
27 unmodified lines
1987 const server = await createHttpTestServer(t);1988 server.get('/', (_request, response) => {1989 requestCount++;1990 if (requestCount <= 2) {1518 response.sendStatus(500);1991 response.sendStatus(400);1992 } else {1993 response.end(fixture);1994 }1995 });
130 unmodified lines
2126 const server = await createHttpTestServer(t);2127 server.get('/', (_request, response) => {2128 requestCount++;2129 if (requestCount <= 2) {1657 response.sendStatus(500);2130 response.sendStatus(400);2131 } else {2132 response.end(fixture);2133 }2134 });
86 unmodified lines
22212222test('totalTimeout bounds hanging HTTPError body reads when timeout is disabled', async t => {2223 t.timeout(2000);2224 let requestCount = 0;2225 let hookError: Error | undefined;22262227 const customFetch: typeof fetch = async () => {2228 requestCount++;2229
12 unmodified lines
2242 await t.throwsAsync(2243 ky('https://example.com', {2244 fetch: customFetch,2245 timeout: false,1772 totalTimeout: 50,2246 totalTimeout: 250,2247 retry: {2248 limit: 5,2249 delay: () => 0,2250 },2251 hooks: {2252 beforeError: [2253 ({error}) => {2254 hookError = error;2255 error.message = 'http-error-body-timeout-beforeError';2256 return error;2257 },2258 ],2259 },2260 }).text(),2261 {2262 name: 'TimeoutError',2263 message: 'http-error-body-timeout-beforeError',2264 },2265 );22661783 // `totalTimeout` starts when the Ky pipeline is created, so very slow CI can exhaust the1784 // budget before the first fetch attempt begins.1785 t.true(requestCount >= 0 && requestCount <= 1);2267 t.is(requestCount, 1);2268 t.true(hookError instanceof TimeoutError);2269});22702271test('totalTimeout bounds hanging HTTPError body reads when timeout is larger', async t => {2272 t.timeout(2000);
17 unmodified lines
2290 await t.throwsAsync(2291 ky('https://example.com', {2292 fetch: customFetch,2293 timeout: 1000,1811 totalTimeout: 50,2294 totalTimeout: 250,2295 retry: {2296 limit: 5,2297 delay: () => 0,2298 },
2 unmodified lines
2301 name: 'TimeoutError',2302 },2303 );23041822 // `totalTimeout` starts when the Ky pipeline is created, so very slow CI can exhaust the budget before the first fetch attempt begins.1823 t.true(requestCount >= 0 && requestCount <= 1);2305 t.is(requestCount, 1);2306});23072308test.serial('totalTimeout is rechecked after per-attempt HTTPError body timeout', async t => {2309 t.timeout(2000);2310 const originalPerformanceNow = globalThis.performance.now;2311 let performanceNowCallCount = 0;2312 let requestCount = 0;23132314 const customFetch: typeof fetch = async () => {2315 requestCount++;23162317 const body = new ReadableStream<Uint8Array>({2318 start(controller) {2319 controller.enqueue(new TextEncoder().encode('{"error":"partial"'));2320 },2321 });23222323 return new Response(body, {2324 status: 500,2325 headers: {'content-type': 'application/json'},2326 });2327 };23282329 globalThis.performance.now = () => {2330 performanceNowCallCount++;2331 return performanceNowCallCount < 4 ? 0 : 100;2332 };23332334 try {2335 await t.throwsAsync(2336 ky('https://example.com', {2337 fetch: customFetch,2338 timeout: 50,2339 totalTimeout: 51,2340 retry: 0,2341 }).text(),2342 {2343 name: 'TimeoutError',2344 },2345 );2346 } finally {2347 globalThis.performance.now = originalPerformanceNow;2348 }23492350 t.is(requestCount, 1);2351 t.true(performanceNowCallCount >= 4);2352});23532354test('totalTimeout bounds hanging HTTPError parseJson when timeout is disabled', async t => {2355 t.timeout(2000);2356 let requestCount = 0;2357
8 unmodified lines
2366 await t.throwsAsync(2367 ky('https://example.com', {2368 fetch: customFetch,2369 timeout: false,1842 totalTimeout: 50,2370 totalTimeout: 250,2371 parseJson: async () => new Promise<never>(() => {2372 // Intentionally never settles2373 }),2374 retry: {
5 unmodified lines
2380 name: 'TimeoutError',2381 },2382 );23831856 // `totalTimeout` starts when the Ky pipeline is created, so very slow CI can exhaust the budget before the first fetch attempt begins.1857 t.true(requestCount >= 0 && requestCount <= 1);2384 t.is(requestCount, 1);2385});23862387test('totalTimeout smaller than timeout - effective timeout is capped', async t => {2388 let requestCount = 0;
95 unmodified lines
2484 await t.throwsAsync(2485 ky('https://example.com', {2486 fetch: customFetch,2487 timeout: 300,1961 totalTimeout: 500,2488 totalTimeout: 800,2489 retry: {2490 limit: 10,2491 delay: () => 0,2492 },
2 unmodified lines
2495 name: 'TimeoutError',2496 },2497 );24981972 // Each attempt takes ~200ms. Within 500ms totalTimeout, at most 2-3 attempts fit.1973 t.true(requestCount >= 2 && requestCount <= 3);2499 t.true(requestCount >= 2 && requestCount < 10, `Expected totalTimeout to allow retries but cap below the retry limit, got ${requestCount}`);2500});25012502test('totalTimeout works with ky.create()', async t => {2503 let requestCount = 0;
24 unmodified lines
2528 let requestCount = 0;25292530 const customFetch: typeof fetch = async () => {2531 requestCount++;2532 await delay(10);2533 if (requestCount <= 2) {2534 return new Response('', {status: 500});2535 }2536
1 unmodified line
2538 };25392540 const parent = ky.create({2541 fetch: customFetch,2015 totalTimeout: 100,2542 totalTimeout: 1,2543 retry: {2544 limit: 3,2545 delay: () => 0,2546 },
50 unmodified lines
2597 await t.throwsAsync(2598 ky('https://example.com', {2599 fetch: customFetch,2600 timeout: 100,2074 totalTimeout: 1000,2601 totalTimeout: 2000,2602 retry: {2603 limit: 30,2604 retryOnTimeout: true,2605 delay: () => 0,
3 unmodified lines
2609 name: 'TimeoutError',2610 },2611 );26122086 // Each attempt times out at ~100ms, so many attempts fit within the 1000ms totalTimeout.2087 // The exact count is timing-dependent (slow CI runs fewer), so we only assert the invariant:2088 // it retried at least once, and totalTimeout stopped it well before the retry limit.2089 t.true(requestCount >= 2, `Expected at least 2 attempts, got ${requestCount}`);2090 t.true(requestCount < 30, `Expected totalTimeout to cap below the retry limit, got ${requestCount}`);2613 t.true(requestCount >= 2 && requestCount < 30, `Expected retryOnTimeout to retry but totalTimeout to cap below the retry limit, got ${requestCount}`);2614});26152616test('NetworkError wraps fetch network errors', async t => {2617 const error = await t.throwsAsync(
240 unmodified lines
modified:readme.md+10 added-8 removed
292 unmodified lines
293If `retry` is a number, it will be used as `limit` and other defaults will remain in place.294295Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.296297If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, delay, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.297`413 Payload Too Large` is only retried when the response includes a retry timing header.298299If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.299When the response status is contained in both `statusCodes` and `afterStatusCodes`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as current-era Unix timestamps. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.300301If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.302303The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.304To clamp the delay, set `backoffLimit` to 1000, for example.305By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.306307The `delay` option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at `1`, and must return the delay in milliseconds.308309The `jitter` option adds random jitter to retry delays to prevent thundering herd problems. When many clients retry simultaneously (e.g., after hitting a rate limit), they can overwhelm the server again. Jitter adds randomness to break this synchronization. Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay. Alternatively, pass a function to implement custom jitter strategies.310309**Note:** Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.311**Note:** Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.312311The `retryOnTimeout` option determines whether to retry when a request times out. By default, retries are not triggered following a [timeout](#timeout).313The `retryOnTimeout` option determines whether to retry when a request times out before a response is returned. By default, retries are not triggered following a [timeout](#timeout). Timeouts while reading a response body through Ky shortcut methods are not retried because the response has already been received.314315The `shouldRetry` option provides custom retry logic that **takes precedence over the default retry checks** (`retryOnTimeout`, status code checks, etc.) for retriable methods. It is only called after the retry limit and method checks pass.316317**Note:** This is different from the `beforeRetry` hook:
13 unmodified lines
331const json = await ky('https://example.com', {332 retry: {333 limit: 10,334 methods: ['get'],333 statusCodes: [413],335 statusCodes: [500],336 backoffLimit: 3000337 }338}).json();339```
74 unmodified lines
414415Type: `number | false`\416Default: `10000`417416Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Cannot be greater than 2147483647. See also [`totalTimeout`](#totaltimeout).418Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Cannot be greater than 2147483647. See also [`totalTimeout`](#totaltimeout).419420If set to `false`, there will be no per-attempt timeout.421422##### totalTimeout
116 unmodified lines
539> Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.540541The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.542541If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body will be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.543If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.544545You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).546547**Modifying headers:**
694 unmodified lines
1242### HTTPError12431244Exposed for `instanceof` checks. The error has a `response` property with the [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response), `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request), and `options` property with normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request).12451244It also has a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the [`parseJson` option](#parsejson) if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty or parsing fails, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` population is bounded by the request timeout and a 10 MiB response body size limit. The `data` property is populated before [`beforeError`](#hooks) hooks run, so hooks can access it.1246It also has a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the [`parseJson` option](#parsejson) if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty, unreadable, too large, parsing fails, or the error-data read/parse timeout is reached, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` body reads and async JSON parsing are bounded by the request timeout (or 10 seconds when `timeout` is disabled), any remaining `totalTimeout` budget, and a 10 MiB response body size limit. If `totalTimeout` expires while populating `error.data`, Ky throws `TimeoutError` instead of `HTTPError`. The `data` property is populated before [`beforeError`](#hooks) hooks run, so hooks can access it.12471248Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of [`NetworkError`](#networkerror) instead of `HTTPError` and will not contain a `response` property.12491250> [!NOTE]
620 unmodified lines