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
Provenance
- Commit
3419113- Tree
8dd81b1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
06375ef
9 files changed+1326 added−173 removed
modified:source/core/Ky.ts+169 added-71 removed
28 unmodified lines29 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';30 import isRawNetworkError from '../utils/is-network-error.js';31 import {isHTTPError, isNetworkError, isTimeoutError} from '../utils/type-guards.js';32 import {33+ calculateRetryTimingDelay,34+ getRetryTimingHeader,35+} from './retry-timing.js';36+import {37 maxSafeTimeout,38 responseTypes,39 stop,40 RetryMarker,7 unmodified lines48 const maxErrorResponseBodySize = 10 * 1024 * 1024;49 const 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';50 const timedOutResponseData = Symbol('timedOutResponseData');51 52+type ErrorDataTimeout = {53+ milliseconds: number;54+ fromTotalTimeout: boolean;55+};56+57 const 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 lines264 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- }263-264- // Errors thrown by beforeRetry hooks must propagate unchanged.265- if (ky.#beforeRetryHookErrors.has(error)) {266- throw error;267- }268-269- 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- });280-281- // Only overwrite if the hook returns a valid Error instance.282- if (hookResult instanceof Error) {283- processedError = hookResult;284- }285- }286-287- throw processedError;268+ await ky.#throwProcessedError(error);269 } finally {270 const originalRequest = ky.#originalRequest;271 272 // Ignore cancellation errors from already-locked or already-consumed streams.20 unmodified lines293 294 const response = await result;295 296 if (type !== 'json') {316- return response[type]();297+ return ky.#raceBodyRead(async () => response[type](), response);298 }299 300+ 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+ }307+308+ return JSON.parse(text);309 }310 325- return JSON.parse(text);326- }311+ const jsonValue = initHookOptions.parseJson312+ ? await initHookOptions.parseJson(text, {request, response})313+ : JSON.parse(text);314 328- const jsonValue = initHookOptions.parseJson329- ? await initHookOptions.parseJson(text, {request: ky.#getResponseRequest(response), response})330- : JSON.parse(text);331-332- return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);315+ return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);316+ }, request);317 };318 }319 320 return result;11 unmodified lines332 333 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 lines501 if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {502 throw error;503 }504 522- // 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});507 526- // 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 }512 513 if (result === true) {532- // Force retry - skip all other validation and return delay514 return this.#calculateDelay();515 }535-536- // If undefined or any other value, fall through to default behavior516 }517 518 // Default timeout behavior519 if (isTimeoutError(error)) {8 unmodified lines528 if (!this.#options.retry.statusCodes.includes(error.response.status)) {529 throw error;530 }531 553- 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 }539 567- if (!Number.isFinite(after)) {568- return Math.min(this.#options.retry.maxRetryAfter, this.#calculateDelay());569- }570-571- after = Math.max(0, after);572-540 // Don't apply jitter when server provides explicit retry timing541 return Math.min(this.#options.retry.maxRetryAfter, after);542 }543 28 unmodified lines572 573 return response;574 }575 576+ 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+ }581+582+ // Errors thrown by beforeRetry hooks must propagate unchanged.583+ if (this.#beforeRetryHookErrors.has(error)) {584+ throw error;585+ }586+587+ 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+ });598+599+ // Only overwrite if the hook returns a valid Error instance.600+ if (hookResult instanceof Error) {601+ processedError = hookResult;602+ }603+ }604+605+ throw processedError;606+ }607+608 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+ }617+618 this.#throwIfTotalTimeoutExhausted();619 return undefined;620 }621 4 unmodified lines626 if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {627 return text;628 }629 630+ 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+ }636+637 this.#throwIfTotalTimeoutExhausted();638 return undefined;639 }640 641 return data;642 }643 635- #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 }653 654 if (remainingTotal <= 0) {655 throw new TimeoutError(this.request);656 }657 646- return Math.min(errorDataTimeout, remainingTotal);658+ return {659+ milliseconds: Math.min(errorDataTimeout, remainingTotal),660+ fromTotalTimeout: remainingTotal <= errorDataTimeout,661+ };662 }663 664+ #getBodyReadTimeout(): number | undefined {665+ const remainingTotal = this.#getRemainingTotalTimeout();666+ if (remainingTotal !== undefined) {667+ if (remainingTotal <= 0) {668+ throw new TimeoutError(this.request);669+ }670+671+ return this.#options.timeout === false672+ ? remainingTotal673+ : Math.min(this.#options.timeout, remainingTotal);674+ }675+676+ return this.#options.timeout === false ? undefined : this.#options.timeout;677+ }678+679+ // 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+ }688+689+ const bodyPromise = createBodyPromise();690+ if (timeoutMs === undefined) {691+ return bodyPromise;692+ }693+694+ 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+ ]);705+706+ 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+ }713+714+ return result;715+ }716+717+ async #raceWithTotalTimeout<T>(operation: () => Promise<T>, request: Request): Promise<T> {718+ const remainingTotal = this.#getRemainingTotalTimeout();719+ if (remainingTotal === undefined) {720+ return operation();721+ }722+723+ if (remainingTotal <= 0) {724+ await this.#throwProcessedError(new TimeoutError(request));725+ }726+727+ 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+ ]);739+740+ if (result === timedOutResponseData) {741+ await this.#throwProcessedError(new TimeoutError(request));742+ }743+744+ return result as T;745+ }746+747 #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 linesadded: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.2+const timestampThreshold = Date.parse('2024-01-01');3+const delayPattern = /^\d+$/;4+const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];5+6+// 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.7+const 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$/;8+const 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$/;9+const 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})$/;10+11+type RetryTimingHeader = {12+ value: string;13+ allowTimestamp: boolean;14+};15+16+type RetryTimingDateParts = {17+ year: number;18+ month: string;19+ day: string;20+ hours: string;21+ minutes: string;22+ seconds: string;23+};24+25+export const getRetryTimingHeader = (headers: Headers): RetryTimingHeader | undefined => {26+ const retryAfter = headers.get('Retry-After');27+ if (retryAfter !== null) {28+ return {value: retryAfter, allowTimestamp: false};29+ }30+31+ // 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+ }36+37+ const rateLimitRetryAfter = headers.get('X-RateLimit-Retry-After'); // Symfony-based services38+ if (rateLimitRetryAfter !== null) {39+ return {value: rateLimitRetryAfter, allowTimestamp: false};40+ }41+42+ 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+ }47+48+ return undefined;49+};50+51+const 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+ }65+66+ 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();70+71+ // 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+ }82+83+ return secondsNumber === 60 ? timestamp + 1000 : timestamp;84+};85+86+const getCapture = (match: RegExpExecArray, index: number): string => match[index]!;87+88+const 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+ }100+101+ 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;108+109+ // 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+ }130+131+ return timestamp;132+ }133+134+ 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+ }147+148+ return undefined;149+};150+151+export const calculateRetryTimingDelay = ({value, allowTimestamp}: RetryTimingHeader): number | undefined => {152+ if (delayPattern.test(value)) {153+ let delay = Number(value) * 1000;154+155+ // 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+ }162+163+ return Math.max(0, delay);164+ }165+166+ const timestamp = parseDate(value);167+ if (timestamp === undefined) {168+ return undefined;169+ }170+171+ 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 lines5 6 /**7 Error thrown when the response has a non-2xx status code and `throwHttpErrors` is enabled.8 9-The 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.9+The 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.10 11 The 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.12 13 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` and will not contain a `response` property.21 unmodified linesmodified:source/types/hooks.ts+1 added-1 removed
173 unmodified lines174 **Warning:** Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.175 176 The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.177 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 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`.179 180 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).181 182 **Modifying headers:**183 unmodified linesmodified:source/types/options.ts+6 added-4 removed
172 unmodified lines173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174 175 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.176 177- 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.178 179- 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.180 181+ If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.182+183 @example184 ```185 import ky from 'ky';186 187 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;197 198 /**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`.200 201 If set to `false`, there will be no per-attempt timeout.202 203 @default 10000273 unmodified linesmodified:source/types/retry.ts+6 added-4 removed
28 unmodified lines2930313233343536373839384041424344454645474849505129 unmodified lines8182838483858687888918 unmodified lines10810911011111011211311411511661 unmodified lines28 unmodified lines
/** The HTTP status codes allowed to retry.
`413 Payload Too Large` is only retried when the response includes a retry timing header.
@default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[];
/** The HTTP status codes allowed to retry with a `Retry-After` header. The retriable HTTP status codes that should respect retry timing headers. These status codes must also be included in `statusCodes`.
@default [413, 429, 503] */ afterStatusCodes?: number[];
/** If the `Retry-After` header is greater than `maxRetryAfter`, it will use `maxRetryAfter`. If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.
@default Infinity */ maxRetryAfter?: number;29 unmodified lines 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.
Note: Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected. Note: Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.
@default undefined (no jitter)
@example18 unmodified lines */ jitter?: boolean | ((delay: number) => number) | undefined;
/** Whether to retry when the request times out. Whether to retry when the request times out before a response is returned. Timeouts while reading a response body through Ky shortcut methods are not retried because the response has already been received.
@default false
@example61 unmodified linesmodified:test/main.ts+357 added-4 removed
780 unmodified lines781 782 t.is(requestCount, 0);783 });784 785-test('timeout option is cancelled when the promise is resolved', async t => {785+test.serial('timeout option is cancelled when the promise is resolved', async t => {786 const server = await createHttpTestServer(t);787 788 server.get('/', (request, response) => {789 response.end(request.method);790 });791 792+ const originalSetTimeout = globalThis.setTimeout;793+ const originalClearTimeout = globalThis.clearTimeout;794+ let requestTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;795+ let didClearRequestTimeout = false;796+797+ globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {798+ const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);799+ if (delayMs === 2000) {800+ requestTimeoutId = timeoutId;801+ }802+803+ return timeoutId;804+ }) as typeof globalThis.setTimeout;805+806+ globalThis.clearTimeout = (timeoutId => {807+ if (timeoutId === requestTimeoutId) {808+ didClearRequestTimeout = true;809+ }810+811+ originalClearTimeout(timeoutId);812+ }) as typeof globalThis.clearTimeout;813+814+ try {815+ await ky(server.url, {timeout: 2000});816+ } finally {817+ globalThis.setTimeout = originalSetTimeout;818+ globalThis.clearTimeout = originalClearTimeout;819+ }820+821+ t.truthy(requestTimeoutId);822+ t.true(didClearRequestTimeout);823+});824+825+test.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+ });830+831+ await request;832+833+ const originalSetTimeout = globalThis.setTimeout;834+ const originalClearTimeout = globalThis.clearTimeout;835+ let bodyTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;836+ let didClearBodyTimeout = false;837+838+ globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {839+ const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);840+ if (delayMs === 2000) {841+ bodyTimeoutId = timeoutId;842+ }843+844+ return timeoutId;845+ }) as typeof globalThis.setTimeout;846+847+ globalThis.clearTimeout = (timeoutId => {848+ if (timeoutId === bodyTimeoutId) {849+ didClearBodyTimeout = true;850+ }851+852+ originalClearTimeout(timeoutId);853+ }) as typeof globalThis.clearTimeout;854+855+ try {856+ t.is(await request.text(), 'ok');857+ } finally {858+ globalThis.setTimeout = originalSetTimeout;859+ globalThis.clearTimeout = originalClearTimeout;860+ }861+862+ t.truthy(bodyTimeoutId);863+ t.true(didClearBodyTimeout);864+});865+866+test('timeout bounds a never-ending successful response body', async t => {867+ let didStartBodyRead = false;868+869+ const customFetch: typeof fetch = async () => {870+ const response = new Response(undefined, {871+ status: 200,872+ headers: {'content-type': 'application/json'},873+ });874+875+ response.text = async () => {876+ didStartBodyRead = true;877+ return new Promise<string>(resolve => {878+ t.teardown(() => {879+ resolve('');880+ });881+ });882+ };883+884+ return response;885+ };886+887 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+});897 794- await ky(server.url, {timeout: 2000});898+test('totalTimeout bounds a never-ending successful response body', async t => {899+ let didStartBodyRead = false;900 796- 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+ };911 798- t.true(duration < 10);912+ return response;913+ };914+915+ 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 });926 927+test('beforeError hook receives totalTimeout exhausted before a shortcut body read starts', async t => {928+ let didReadBody = false;929+ let hookError: Error | undefined;930+931+ const customFetch: typeof fetch = async () => {932+ const response = new Response('ok');933+ response.text = async () => {934+ didReadBody = true;935+ return 'ok';936+ };937+938+ return response;939+ };940+941+ 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+ });955+956+ await response;957+ await delay(300);958+959+ await t.throwsAsync(response.text(), {960+ instanceOf: TimeoutError,961+ message: 'pre-read-timeout-beforeError',962+ });963+964+ t.false(didReadBody);965+ t.true(hookError instanceof TimeoutError);966+});967+968+test('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});974+975+ const body = new ReadableStream<Uint8Array>({976+ start(controller) {977+ controller.enqueue(new TextEncoder().encode('partial'));978+ },979+ });980+981+ return new Response(body, {status: 200});982+ };983+984+ await t.throwsAsync(ky('https://example.com', {985+ fetch: customFetch,986+ timeout: 50,987+ }).text(), {988+ instanceOf: TimeoutError,989+ });990+991+ t.true(didAbort);992+});993+994+test('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++;998+999+ const body = new ReadableStream<Uint8Array>({1000+ start(controller) {1001+ controller.enqueue(new TextEncoder().encode('partial'));1002+ },1003+ });1004+1005+ return new Response(body, {status: 200});1006+ };1007+1008+ 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+ });1019+1020+ t.is(requestCount, 1);1021+});1022+1023+test('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+ });1031+1032+ return new Response(body, {status: 200});1033+ };1034+1035+ 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+ });1051+1052+ t.true(hookError instanceof TimeoutError);1053+});1054+1055+test('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+ });1082+1083+ t.true(parseJsonCalled);1084+ t.true(hookError instanceof TimeoutError);1085+ t.true(Date.now() - start < 2000);1086+});1087+1088+test('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+ }));1094+1095+ 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+ });1105+1106+ t.true(schemaValidationCalled);1107+ t.true(Date.now() - start < 2000);1108+});1109+1110+test.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+ }1117+1118+ const testDelay = delayMs === 10_000 ? 0 : delayMs;1119+ return originalSetTimeout(handler, testDelay, ...arguments_);1120+ }) as typeof globalThis.setTimeout;1121+1122+ 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+ });1133+1134+ return new Response(body);1135+ },1136+ signal: abortController.signal,1137+ timeout: false,1138+ }).text();1139+1140+ 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+ }1150+1151+ t.deepEqual(scheduledDelays, []);1152+});1153+1154 test('normalizing retry options does not mutate the caller retry object', async t => {1155 const retry = {1156 methods: ['GET'],1157 };1699 unmodified linesmodified:test/retry.ts+603 added-80 removed
1+import process from 'node:process';2 import {setTimeout as delay} from 'node:timers/promises';2-import test from 'ava';3+import test, {type ExecutionContext} from 'ava';4 import ky, {5 NetworkError,6 TimeoutError,7 isKyError,6 unmodified lines14 const fixture = 'fixture';15 const defaultRetryCount = 2;16 const retryAfterOn500 = 2;17 const retryAfterOn413 = 2;18+const retryAfterTimestampText = '1704067200';19+const retryAfterTimestampScheduledDelay = 2_147_483_647;20+const httpDateDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];21+const httpDateLongDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];22+const httpDateMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];23 24+const formatHttpTime = (date: Date) => [25+ date.getUTCHours(),26+ date.getUTCMinutes(),27+ date.getUTCSeconds(),28+].map(value => value.toString().padStart(2, '0')).join(':');29+30+const formatAsctimeDate = (date: Date) => {31+ const day = date.getUTCDate().toString().padStart(2, ' ');32+33+ return `${httpDateDayNames[date.getUTCDay()]} ${httpDateMonths[date.getUTCMonth()]} ${day} ${formatHttpTime(date)} ${date.getUTCFullYear()}`;34+};35+36+const formatRfc850Date = (date: Date) => {37+ const day = date.getUTCDate().toString().padStart(2, '0');38+ const year = (date.getUTCFullYear() % 100).toString().padStart(2, '0');39+40+ return `${httpDateLongDayNames[date.getUTCDay()]}, ${day}-${httpDateMonths[date.getUTCMonth()]}-${year} ${formatHttpTime(date)} GMT`;41+};42+43+const withCapturedTimeouts = async (body: (scheduledDelays: number[]) => Promise<void>) => {44+ const originalSetTimeout = globalThis.setTimeout;45+ const scheduledDelays: number[] = [];46+47+ globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {48+ if (typeof delayMs === 'number') {49+ scheduledDelays.push(delayMs);50+ }51+52+ const testDelayMs = typeof delayMs === 'number' && delayMs > 1_000_000 ? 0 : delayMs;53+ return originalSetTimeout(handler, testDelayMs, ...arguments_);54+ }) as typeof globalThis.setTimeout;55+56+ try {57+ await body(scheduledDelays);58+ } finally {59+ globalThis.setTimeout = originalSetTimeout;60+ }61+};62+63+const createSingleRetryHeaderServer = async (t: ExecutionContext, headers: Record<string, string | number>) => {64+ let requestCount = 0;65+66+ const server = await createHttpTestServer(t);67+ server.get('/', (_request, response) => {68+ requestCount++;69+ if (requestCount === 2) {70+ response.end(fixture);71+ return;72+ }73+74+ response.writeHead(429, headers);75+ response.end('');76+ });77+78+ return {79+ server,80+ get requestCount() {81+ return requestCount;82+ },83+ };84+};85+86 test('network error', async t => {87 let requestCount = 0;88 89 const server = await createHttpTestServer(t);133 unmodified lines223 224 t.is(requestCount, 5);225 });226 159-test('RateLimit-Reset is treated the same as Retry-After', async t => {227+test.serial('Retry-After number is treated as delay seconds, not timestamp', async t => {228+ const retryServer = await createSingleRetryHeaderServer(t, {229+ 'Retry-After': retryAfterTimestampText,230+ });231+232+ await withCapturedTimeouts(async scheduledDelays => {233+ t.is(await ky(retryServer.server.url, {234+ retry: {235+ limit: 1,236+ },237+ }).text(), fixture);238+239+ t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));240+ });241+242+ t.is(retryServer.requestCount, 2);243+});244+245+test.serial('invalid Retry-After number 0x10 falls back to retry delay', async t => {246+ const retryServer = await createSingleRetryHeaderServer(t, {247+ 'Retry-After': '0x10',248+ });249+250+ 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);258+259+ t.true(scheduledDelays.includes(10));260+ });261+262+ t.is(retryServer.requestCount, 2);263+});264+265+test.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+ });269+270+ await withCapturedTimeouts(async scheduledDelays => {271+ t.is(await ky(retryServer.server.url, {272+ retry: {273+ limit: 1,274+ },275+ }).text(), fixture);276+277+ t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));278+ });279+280+ t.is(retryServer.requestCount, 2);281+});282+283+test.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+ });288+289+ await withCapturedTimeouts(async scheduledDelays => {290+ t.is(await ky(retryServer.server.url, {291+ retry: {292+ limit: 1,293+ },294+ }).text(), fixture);295+296+ t.true(scheduledDelays.includes(1000));297+ t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));298+ });299+300+ t.is(retryServer.requestCount, 2);301+});302+303+test.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+ });308+309+ await withCapturedTimeouts(async scheduledDelays => {310+ t.is(await ky(retryServer.server.url, {311+ retry: {312+ limit: 1,313+ delay: () => 23,314+ },315+ }).text(), fixture);316+317+ t.true(scheduledDelays.includes(23));318+ t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));319+ });320+321+ t.is(retryServer.requestCount, 2);322+});323+324+test.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+ });329+330+ await withCapturedTimeouts(async scheduledDelays => {331+ t.is(await ky(retryServer.server.url, {332+ retry: {333+ limit: 1,334+ delay: () => 31,335+ },336+ }).text(), fixture);337+338+ t.true(scheduledDelays.includes(31));339+ t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));340+ });341+342+ t.is(retryServer.requestCount, 2);343+});344+345+test.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+ });349+350+ await withCapturedTimeouts(async scheduledDelays => {351+ t.is(await ky(retryServer.server.url, {352+ retry: {353+ limit: 1,354+ delay: () => 29,355+ },356+ }).text(), fixture);357+358+ t.true(scheduledDelays.includes(29));359+ });360+361+ t.is(retryServer.requestCount, 2);362+});363+364+for (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+ });373+374+ await withCapturedTimeouts(async scheduledDelays => {375+ t.is(await ky(retryServer.server.url, {376+ retry: {377+ limit: 1,378+ delay: () => 13,379+ },380+ }).text(), fixture);381+382+ t.true(scheduledDelays.some(delay => delay > 1_000_000));383+ t.false(scheduledDelays.includes(13));384+ });385+386+ t.is(retryServer.requestCount, 2);387+ });388+}389+390+test.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+ });395+396+ 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);406+407+ 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+ }417+418+ t.is(retryServer.requestCount, 2);419+});420+421+test.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;432+433+ const retryServer = await createSingleRetryHeaderServer(t, {434+ 'Retry-After': retryAfterDate,435+ });436+437+ 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);447+448+ 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+ }455+456+ t.is(retryServer.requestCount, 2);457+});458+459+test.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);462+463+ const retryServer = await createSingleRetryHeaderServer(t, {464+ 'Retry-After': formatRfc850Date(retryAfterDate),465+ });466+467+ await withCapturedTimeouts(async scheduledDelays => {468+ t.is(await ky(retryServer.server.url, {469+ retry: {470+ limit: 1,471+ delay: () => 13,472+ },473+ }).text(), fixture);474+475+ t.true(scheduledDelays.some(delay => delay > 1_000_000));476+ t.false(scheduledDelays.includes(13));477+ });478+479+ t.is(retryServer.requestCount, 2);480+});481+482+test.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);485+486+ const retryServer = await createSingleRetryHeaderServer(t, {487+ 'Retry-After': formatRfc850Date(retryAfterDate),488+ });489+490+ 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);498+499+ t.true(scheduledDelays.includes(0));500+ t.false(scheduledDelays.includes(1));501+ t.false(scheduledDelays.includes(13));502+ });503+504+ t.is(retryServer.requestCount, 2);505+});506+507+test.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+ });511+512+ await withCapturedTimeouts(async scheduledDelays => {513+ t.is(await ky(retryServer.server.url, {514+ retry: {515+ limit: 1,516+ delay: () => 17,517+ },518+ }).text(), fixture);519+520+ t.true(scheduledDelays.includes(17));521+ });522+523+ t.is(retryServer.requestCount, 2);524+});525+526+test('RateLimit-Reset delay seconds are respected like Retry-After', async t => {527 let requestCount = 0;528 529 const server = await createHttpTestServer(t);530 server.get('/', (_request, response) => {21 unmodified lines552 553 t.is(requestCount, 3);554 });555 189-test('RateLimit-Reset with time since epoch', async t => {556+test.serial('RateLimit-Reset with time since epoch', async t => {557+ const now = Date.UTC(2026, 0, 1);558 let requestCount = 0;559 560 const server = await createHttpTestServer(t);561 server.get('/', (_request, response) => {1 unmodified line563 564 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 });572 573 response.end('');574 }575 });576 209- 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- });582 583+ 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+ }591+592 t.is(requestCount, 3);593 });594 595+test.serial('empty RateLimit-Reset falls back to retry delay', async t => {596+ const retryServer = await createSingleRetryHeaderServer(t, {597+ 'RateLimit-Reset': '',598+ });599+600+ await withCapturedTimeouts(async scheduledDelays => {601+ t.is(await ky(retryServer.server.url, {602+ retry: {603+ limit: 1,604+ delay: () => 37,605+ },606+ }).text(), fixture);607+608+ t.true(scheduledDelays.includes(37));609+ });610+611+ t.is(retryServer.requestCount, 2);612+});613+614+test.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+ });619+620+ await withCapturedTimeouts(async scheduledDelays => {621+ t.is(await ky(retryServer.server.url, {622+ retry: {623+ limit: 1,624+ delay: () => 41,625+ },626+ }).text(), fixture);627+628+ t.true(scheduledDelays.includes(41));629+ t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));630+ });631+632+ t.is(retryServer.requestCount, 2);633+});634+635+for (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+ });641+642+ 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);653+654+ 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+ }661+662+ t.is(retryServer.requestCount, 2);663+ });664+}665+666 test('respect 413 Retry-After', async t => {667 const startTime = Date.now();668 let requestCount = 0;669 15 unmodified lines685 t.true(timeElapsedInMs >= retryAfterOn413 * 1000);686 t.is(requestCount, retryAfterOn413 + 1);687 });688 243-test('respect 413 Retry-After with timestamp', async t => {689+test('respect 413 Retry-After with HTTP date', async t => {690 const startTime = Date.now();691 let requestCount = 0;692 693 const server = await createHttpTestServer(t, {bodyParser: false});53 unmodified lines747 t.true(timeElapsedInMs >= retryAfterOn500 * 1000);748 t.is(requestCount, retryAfterOn500 + 1);749 });750 751+test('custom `afterStatusCodes` does not retry statuses missing from `statusCodes`', async t => {752+ let requestCount = 0;753+754+ 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+ });762+763+ 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+});775+776 test('respect number of retries', async t => {777 let requestCount = 0;778 779 const server = await createHttpTestServer(t);109 unmodified lines889 890 t.is(requestCount, 5);891 });892 422-test('invalid Retry-After header falls back to retry delay', async t => {893+test.serial('invalid Retry-After header falls back to retry delay', async t => {894 let requestCount = 0;895 896 const server = await createHttpTestServer(t);897 server.get('/', (_request, response) => {8 unmodified lines906 907 response.end(fixture);908 });909 439- 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);919 452- t.is(result, fixture);920+ t.true(scheduledDelays.includes(50));921+ t.false(scheduledDelays.includes(10));922+ });923+924 t.is(requestCount, 2);925 });926 927+test.serial('invalid 413 Retry-After header falls back to retry delay', async t => {928+ let requestCount = 0;929+930+ 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+ }940+941+ response.end(fixture);942+ });943+944+ 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);953+954+ t.true(scheduledDelays.includes(50));955+ t.false(scheduledDelays.includes(10));956+ });957+958+ t.is(requestCount, 2);959+});960+961 test('retry - can provide retry as number', async t => {962 let requestCount = 0;963 964 const server = await createHttpTestServer(t);841 unmodified lines1806 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 lines1821 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 }1828 1325- // Don't retry on 4xx1829 if (status >= 400 && status < 500) {1830 return false;1831 }1832 }119 unmodified lines1952 t.is(timeoutError?.name, 'TimeoutError');1953 t.is(requestCount, 1);1954 });1955 1453-test('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- });1464-1465- 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- });1478-1479- t.is(timeoutError?.name, 'TimeoutError');1480- t.is(requestCount, 1);1481-});1482-1956 test('shouldRetry: precedence over retryOnTimeout', async t => {1957 let requestCount = 0;1958 1959 const server = await createHttpTestServer(t);27 unmodified lines1987 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 lines2126 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 lines2221 2222 test('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;2226 2227 const customFetch: typeof fetch = async () => {2228 requestCount++;2229 12 unmodified lines2242 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 );2266 1783- // `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 });2270 2271 test('totalTimeout bounds hanging HTTPError body reads when timeout is larger', async t => {2272 t.timeout(2000);17 unmodified lines2290 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 lines2301 name: 'TimeoutError',2302 },2303 );2304 1822- // `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 });2307 2308+test.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;2313+2314+ const customFetch: typeof fetch = async () => {2315+ requestCount++;2316+2317+ const body = new ReadableStream<Uint8Array>({2318+ start(controller) {2319+ controller.enqueue(new TextEncoder().encode('{"error":"partial"'));2320+ },2321+ });2322+2323+ return new Response(body, {2324+ status: 500,2325+ headers: {'content-type': 'application/json'},2326+ });2327+ };2328+2329+ globalThis.performance.now = () => {2330+ performanceNowCallCount++;2331+ return performanceNowCallCount < 4 ? 0 : 100;2332+ };2333+2334+ 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+ }2349+2350+ t.is(requestCount, 1);2351+ t.true(performanceNowCallCount >= 4);2352+});2353+2354 test('totalTimeout bounds hanging HTTPError parseJson when timeout is disabled', async t => {2355 t.timeout(2000);2356 let requestCount = 0;2357 8 unmodified lines2366 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 lines2380 name: 'TimeoutError',2381 },2382 );2383 1856- // `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 });2386 2387 test('totalTimeout smaller than timeout - effective timeout is capped', async t => {2388 let requestCount = 0;95 unmodified lines2484 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 lines2495 name: 'TimeoutError',2496 },2497 );2498 1972- // 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 });2501 2502 test('totalTimeout works with ky.create()', async t => {2503 let requestCount = 0;24 unmodified lines2528 let requestCount = 0;2529 2530 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 line2538 };2539 2540 const parent = ky.create({2541 fetch: customFetch,2015- totalTimeout: 100,2542+ totalTimeout: 1,2543 retry: {2544 limit: 3,2545 delay: () => 0,2546 },50 unmodified lines2597 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 lines2609 name: 'TimeoutError',2610 },2611 );2612 2086- // 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 });2615 2616 test('NetworkError wraps fetch network errors', async t => {2617 const error = await t.throwsAsync(240 unmodified linesmodified:readme.md+10 added-8 removed
292 unmodified lines293 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.294 295 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.296 297-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.297+`413 Payload Too Large` is only retried when the response includes a retry timing header.298 299-If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.299+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.300 301+If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.302+303 The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.304 To clamp the delay, set `backoffLimit` to 1000, for example.305 By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.306 307 The `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.308 309 The `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.310 309-**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.312 311-The `retryOnTimeout` option determines whether to retry when a request times out. By default, retries are not triggered following a [timeout](#timeout).313+The `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.314 315 The `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.316 317 **Note:** This is different from the `beforeRetry` hook:13 unmodified lines331 const 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 lines414 415 Type: `number | false`\416 Default: `10000`417 416-Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Cannot be greater than 2147483647. See also [`totalTimeout`](#totaltimeout).418+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`](#totaltimeout).419 420 If set to `false`, there will be no per-attempt timeout.421 422 ##### totalTimeout116 unmodified lines539 > Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.540 541 The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.542 541-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`.543+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`.544 545 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).546 547 **Modifying headers:**694 unmodified lines1242 ### HTTPError1243 1244 Exposed 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).1245 1244-It 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.1246+It 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.1247 1248 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`](#networkerror) instead of `HTTPError` and will not contain a `response` property.1249 1250 > [!NOTE]620 unmodified lines