Skip to content
Myr

Harden retry

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent be60db5 · Browse files · 14 files+878 added−86 removed
This commit

State

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

Diff stats

14 files+878 added−86 removed

  • tests:+612 added−1 removed
  • other:+266 added−85 removed

14 files+878 added−86 removed

modified:.github/security.md+3 added-1 removed
modified:source/core/Ky.ts+124 added-55 removed
46 unmodified lines
4748const 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');51const timedOutOperation = Symbol('timedOutOperation');5253type ErrorDataTimeout = {54 milliseconds: number;55 fromTotalTimeout: boolean;
13 unmodified lines
6970const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';7172const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {72 if (typeof retry !== 'object') {73 return retry;73 if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {74 return retry as RetryOptions | number;75 }7677 const clonedRetry = {...retry};7879 // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.77 return {78 ...retry,79 ...(retry.methods && {methods: [...retry.methods]}),80 ...(retry.statusCodes && {statusCodes: [...retry.statusCodes]}),81 ...(retry.afterStatusCodes && {afterStatusCodes: [...retry.afterStatusCodes]}),82 };80 if (Array.isArray(clonedRetry.methods)) {81 clonedRetry.methods = [...clonedRetry.methods];82 }8384 if (Array.isArray(clonedRetry.statusCodes)) {85 clonedRetry.statusCodes = [...clonedRetry.statusCodes];86 }8788 if (Array.isArray(clonedRetry.afterStatusCodes)) {89 clonedRetry.afterStatusCodes = [...clonedRetry.afterStatusCodes];90 }9192 return clonedRetry;93};9495const objectToString = Object.prototype.toString;96const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;
93 unmodified lines
190191 // Delay the fetch so that body method shortcuts can set the Accept header192 await Promise.resolve();193 const beforeRequestResponse = await ky.#runBeforeRequestHooks();194 if (beforeRequestResponse !== undefined) {195 ky.#retryLimit = normalizeRetryOptions(ky.#options.retry).limit;196 }197198 let response = beforeRequestResponse ?? await ky.#retry(async () => ky.#fetch());199 let responseFromHook = beforeRequestResponse !== undefined200 || ky.#consumeReturnedResponseFromBeforeRetryHook();201
120 unmodified lines
322 }323324 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;325 const request = ky.#getResponseRequest(response);312 return ky.#raceWithTotalTimeout(async () => {326 const parsedResult = await ky.#raceWithTotalTimeout(async () => {327 if (text === '') {328 if (schema !== undefined) {329 return validateJsonWithSchema(undefined, schema);330 }
5 unmodified lines
336 ? await initHookOptions.parseJson(text, {request, response})337 : JSON.parse(text);338339 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);326 }, request);340 });341342 if (parsedResult === timedOutOperation) {343 await ky.#throwProcessedError(new TimeoutError(request));344 }345346 return parsedResult;347 };348 }349350 return result;
11 unmodified lines
362363 public request: Request;364 #abortController?: AbortController;365 #retryCount = 0;366 #retryLimit: number;367 readonly #input: Input;368 readonly #options: InternalOptions;369 #originalRequest?: Request;370 readonly #userProvidedAbortSignal?: AbortSignal;
23 unmodified lines
394 totalTimeout: options.totalTimeout ?? false,395 fetch: options.fetch ?? globalThis.fetch.bind(globalThis),396 context: options.context ?? {},397 };398 this.#retryLimit = this.#options.retry.limit;399400 if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {401 throw new TypeError('`input` must be a string, URL, or Request');402 }
96 unmodified lines
499 // Ky's internal scheduling and user hook time before the first fetch attempt.500 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;501 }502481 #calculateDelay(): number {482 const retryDelay = this.#options.retry.delay(this.#retryCount + 1);503 #calculateDelay(retry: InternalOptions['retry']): number {504 const retryDelay = retry.delay(this.#retryCount + 1);505506 let jitteredDelay = retryDelay;485 if (this.#options.retry.jitter === true) {507 if (retry.jitter === true) {508 jitteredDelay = Math.random() * retryDelay;487 } else if (typeof this.#options.retry.jitter === 'function') {488 jitteredDelay = this.#options.retry.jitter(retryDelay);509 } else if (typeof retry.jitter === 'function') {510 jitteredDelay = retry.jitter(retryDelay);511512 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {513 jitteredDelay = retryDelay;514 }515 }516495 return Math.min(this.#options.retry.backoffLimit, jitteredDelay);517 return Math.min(retry.backoffLimit, jitteredDelay);518 }519520 async #calculateRetryDelay(error: unknown) {499 if (this.#retryCount >= this.#options.retry.limit) {521 const retry = normalizeRetryOptions(this.#options.retry);522 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {523 throw error;524 }525526 // Wrap non-Error throws to ensure consistent error handling527 const errorObject = error instanceof Error ? error : new NonError(error);528529 // Handle forced retry from afterResponse hook - skip method check and shouldRetry530 if (errorObject instanceof ForceRetryError) {508 return errorObject.customDelay ?? this.#calculateDelay();531 return errorObject.customDelay ?? this.#calculateDelay(retry);532 }533534 // Check if method is retriable for non-forced retries512 if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {535 if (!retry.methods.includes(this.request.method.toLowerCase())) {536 throw error;537 }538516 if (this.#options.retry.shouldRetry !== undefined) {517 const result = await this.#options.retry.shouldRetry({error: errorObject, retryCount: this.#retryCount + 1});539 const {shouldRetry} = retry;540 if (shouldRetry !== undefined) {541 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));542 if (result === timedOutOperation) {543 throw new TimeoutError(this.request);544 }545546 // Only exact booleans override the default retry checks.547 if (result === false) {548 throw error;549 }550551 if (result === true) {525 return this.#calculateDelay();552 return this.#calculateDelay(retry);553 }554 }555556 // Default timeout behavior557 if (isTimeoutError(error)) {531 if (!this.#options.retry.retryOnTimeout) {558 if (!retry.retryOnTimeout) {559 throw error;560 }561535 return this.#calculateDelay();562 return this.#calculateDelay(retry);563 }564565 if (isHTTPError(error)) {539 if (!this.#options.retry.statusCodes.includes(error.response.status)) {566 if (!retry.statusCodes.includes(error.response.status)) {567 throw error;568 }569570 const retryTimingHeader = getRetryTimingHeader(error.response.headers);544 if (retryTimingHeader && this.#options.retry.afterStatusCodes.includes(error.response.status)) {571 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {572 const after = calculateRetryTimingDelay(retryTimingHeader);573 if (after === undefined) {574 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.548 return this.#calculateDelay();575 return this.#calculateDelay(retry);576 }577578 // Don't apply jitter when server provides explicit retry timing552 return Math.min(this.#options.retry.maxRetryAfter, after);579 return Math.min(retry.maxRetryAfter, after);580 }581582 if (error.response.status === 413) {583 throw error;584 }585559 return this.#calculateDelay();586 return this.#calculateDelay(retry);587 }588589 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.590 if (!isNetworkError(error)) {591 throw error;592 }593567 return this.#calculateDelay();594 return this.#calculateDelay(retry);595 }596597 #decorateResponse(response: Response): Response {598 const request = this.#getResponseRequest(response);
152 unmodified lines
751752 return result;753 }754728 async #raceWithTotalTimeout<T>(operation: () => Promise<T>, request: Request): Promise<T> {755 async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOutOperation> {756 const remainingTotal = this.#getRemainingTotalTimeout();757 if (remainingTotal === undefined) {758 return operation();759 }760761 if (remainingTotal <= 0) {735 await this.#throwProcessedError(new TimeoutError(request));762 this.#abortController?.abort();763 return timedOutOperation;764 }765738 const operationPromise = operation();739 const result = await Promise.race<T | typeof timedOutResponseData>([740 operationPromise,741 new Promise<typeof timedOutResponseData>(resolve => {742 const timeoutId = setTimeout(() => {743 resolve(timedOutResponseData);766 let timeoutId: ReturnType<typeof setTimeout> | undefined;767 try {768 const timeoutPromise = new Promise<typeof timedOutOperation>(resolve => {769 timeoutId = setTimeout(() => {770 resolve(timedOutOperation);771 }, remainingTotal);745 void operationPromise.finally(() => {746 clearTimeout(timeoutId);747 }).catch(() => undefined);748 }),749 ]);772 });773 const operationResult = Promise.resolve()774 .then(operation)775 .then(value => ({status: 'fulfilled', value} as const))776 .catch((error: unknown) => ({status: 'rejected', error} as const));777 const result = await Promise.race([operationResult, timeoutPromise]);778 const remainingAfterOperation = this.#getRemainingTotalTimeout();779 const didTimeOut = result === timedOutOperation || (remainingAfterOperation !== undefined && remainingAfterOperation <= 0);780 if (didTimeOut) {781 this.#abortController?.abort();782751 if (result === timedOutResponseData) {752 await this.#throwProcessedError(new TimeoutError(request));753 }783 if (result === timedOutOperation) {784 void operationResult.then(result => {785 if (result.status === 'fulfilled') {786 this.#cancelReturnedBody(result.value);787 }788 });789 } else if (result.status === 'fulfilled') {790 this.#cancelReturnedBody(result.value);791 }792755 return result as T;793 return timedOutOperation;794 }795796 if (result.status === 'rejected') {797 throw result.error;798 }799800 return result.value;801 } finally {802 clearTimeout(timeoutId);803 }804 }805806 #isJsonContentType(contentType: string): boolean {807 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.
99 unmodified lines
907 // Ignore cancellation failures from already-locked or already-consumed streams.908 this.#cancelBody(response.body ?? undefined);909 }910911 #cancelReturnedBody(value: unknown): void {912 if (isResponseInstance(value)) {913 this.#cancelResponseBody(value);914 } else if (isRequestInstance(value)) {915 this.#cancelBody(value.body ?? undefined);916 }917 }918919 #createManagedSignal(): AbortSignal {920 return this.#userProvidedAbortSignal921 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])922 : this.#abortController!.signal;
8 unmodified lines
931932 async #runBeforeRequestHooks(): Promise<Response | undefined> {933 for (const hook of this.#options.hooks.beforeRequest) {934 // eslint-disable-next-line no-await-in-loop879 const result = await hook({935 const result = await this.#raceWithTotalTimeout(async () => hook({936 request: this.request,937 options: this.#getNormalizedOptions(),938 retryCount: 0,883 });939 }));940941 if (result === timedOutOperation) {942 throw new TimeoutError(this.request);943 }944945 if (isRequestInstance(result)) {946 this.#assignRequest(result);947 } else if (isResponseInstance(result)) {948 return result;
12 unmodified lines
961962 let modifiedResponse;963 try {964 // eslint-disable-next-line no-await-in-loop905 modifiedResponse = await hook({965 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({966 request: this.request,967 options: this.#getNormalizedOptions(),968 response: hookResponse,969 retryCount: this.#retryCount,910 });970 }));971972 if (modifiedResponse === timedOutOperation) {973 throw new TimeoutError(this.request);974 }975 } catch (error) {976 // Cancel both responses to prevent memory leaks when hook throws977 if (hookResponse !== response) {978 this.#cancelResponseBody(hookResponse);
77 unmodified lines
1056 this.#assignRequest(customRequest);1057 }10581059 for (const hook of this.#options.hooks.beforeRetry) {996 let hookResult: Awaited<ReturnType<typeof hook>>;1060 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOutOperation;1061 try {1062 // eslint-disable-next-line no-await-in-loop999 hookResult = await hook({1063 hookResult = await this.#raceWithTotalTimeout(async () => hook({1064 request: this.request,1065 options: this.#getNormalizedOptions(),1066 error: error as Error,1067 retryCount: this.#retryCount + 1,1004 });1068 }));1069 } catch (hookError) {1070 // Preserve the original request error path (`throw error`) so beforeError hooks can still run.1071 if (hookError instanceof Error && hookError !== error) {1072 this.#beforeRetryHookErrors.add(hookError);
1 unmodified line
10741075 throw hookError;1076 }10771078 if (hookResult === timedOutOperation) {1079 throw new TimeoutError(this.request);1080 }10811082 if (isRequestInstance(hookResult)) {1083 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`1084 // is used as-is rather than being sanitized or otherwise rewritten by Ky.1085 this.#assignRequest(hookResult);
33 unmodified lines
1119 this.request = new globalThis.Request(this.request, {signal: this.#options.signal});1120 }11211122 const nonRequestOptions = findUnknownOptions(this.#options);1123 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;1055 const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;1124 const retryRequest = this.#retryLimit > 0 ? this.request.clone() : undefined;1125 const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);11261127 // Cloning is done here to prepare in advance for retries.1128 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()
92 unmodified lines
modified:source/errors/HTTPError.ts+2 added-2 removed
14 unmodified lines
15export class HTTPError<T = unknown> extends KyError {16 override name = 'HTTPError' as const;17 response: KyResponse<T>;18 request: KyRequest;19 options: NormalizedOptions;19 options: Readonly<NormalizedOptions>;20 data: T | string | undefined;2122 constructor(response: Response, request: Request, options: NormalizedOptions) {22 constructor(response: Response, request: Request, options: Readonly<NormalizedOptions>) {23 const code = (response.status || response.status === 0) ? response.status : '';24 const title = response.statusText ?? '';25 const status = `${code} ${title}`.trim();26 const reason = status ? `status code ${status}` : 'an unknown error';
8 unmodified lines
modified:source/types/hooks.ts+4 added-4 removed
27 unmodified lines
28export type InitHook = (options: Options) => void;2930export type BeforeRequestState = {31 request: KyRequest;32 options: NormalizedOptions;32 options: Readonly<NormalizedOptions>;3334 /**35 The number of retries attempted. Always `0`, since `beforeRequest` hooks run once before retry handling begins.36 */
3 unmodified lines
40export type BeforeRequestHook = (state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;4142export type BeforeRetryState = {43 request: KyRequest;44 options: NormalizedOptions;44 options: Readonly<NormalizedOptions>;45 error: Error;4647 /**48 The number of retries attempted. Always `>= 1`, since this hook is only called during retries, not on the initial request.
4 unmodified lines
53export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;5455export type BeforeErrorState = {56 request: KyRequest;57 options: NormalizedOptions;57 options: Readonly<NormalizedOptions>;5859 // `Error` (not `KyError`) because this receives all errors, including non-Ky ones.60 error: Error;61
9 unmodified lines
71export type BeforeErrorHook = (state: BeforeErrorState) => Error | Promise<Error>;7273export type AfterResponseState = {74 request: KyRequest;75 options: NormalizedOptions;75 options: Readonly<NormalizedOptions>;76 response: KyResponse;7778 /**79 The number of retries attempted. `0` for the initial request, increments with each retry.
286 unmodified lines
modified:source/types/options.ts+18 added-11 removed
170 unmodified lines
171 Controls retry behavior. Each field is documented in the `RetryOptions` type.172173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174175 `retry.limit`, including numeric shorthand, must be a finite, non-negative integer.176177 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.178179 `413 Payload Too Large` is only retried when the response includes a retry timing header.180
27 unmodified lines
208209 /**210 Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.211212 `beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.213214 If set to `false` or not specified, there is no overall timeout.215216 @default false217
229 unmodified lines
447 */448 headers?: KyHeadersInit;449}450451type NormalizedRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;452453export type InternalOptions = Required<454 Omit<Options, 'hooks' | 'retry' | 'context' | 'throwHttpErrors'>,449'fetch' | 'prefix' | 'timeout' | 'totalTimeout'455 'fetch' | 'prefix' | 'timeout' | 'totalTimeout'456> & {457 headers: Required<Headers>;458 hooks: Required<Hooks>;453 retry: Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;459 retry: NormalizedRetryOptions;460 prefix: string;461 context: Record<string, unknown>;462 throwHttpErrors: boolean | ((status: number) => boolean);463};464465/**466Normalized options passed to the `fetch` call and hooks.467*/462export interface NormalizedOptions extends RequestInit { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.468export interface NormalizedOptions extends Readonly<RequestInit> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.469 // Extended from `RequestInit`, but ensured to be set (not optional).464 method: NonNullable<RequestInit['method']>;465 credentials?: NonNullable<RequestInit['credentials']>;470 readonly method: NonNullable<RequestInit['method']>;471 readonly credentials?: NonNullable<RequestInit['credentials']>;472 readonly headers: Headers;473474 // Extended from custom `KyOptions`, but ensured to be set (not optional).468 retry: RetryOptions;469 baseUrl?: Options['baseUrl'];470 prefix: string;471 onDownloadProgress: Options['onDownloadProgress'];472 onUploadProgress: Options['onUploadProgress'];473 context: Record<string, unknown>;475 readonly retry: NormalizedRetryOptions;476 readonly baseUrl?: Options['baseUrl'];477 readonly prefix: string;478 readonly onDownloadProgress?: NonNullable<Options['onDownloadProgress']>;479 readonly onUploadProgress?: NonNullable<Options['onUploadProgress']>;480 readonly context: Record<string, unknown>;481}482483export type {RetryOptions, ShouldRetryState} from './retry.js';
modified:source/types/retry.ts+1 added
modified:source/utils/normalize.ts+53 added-11 removed
1import {requestMethods} from '../core/constants.js';2import type {RetryOptions} from '../types/retry.js';3import type {HttpMethod, RequestHttpMethod} from '../types/options.js';3import type {HttpMethod, InternalOptions, RequestHttpMethod} from '../types/options.js';45export const normalizeRequestMethod = (input: string): string =>6 requestMethods.includes(input as RequestHttpMethod) ? input.toUpperCase() : input;7
1 unmodified line
910const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];1112const retryAfterStatusCodes = [413, 429, 503];13const invalidRetryLimitErrorMessage = '`retry.limit` must be a finite, non-negative integer';1414type InternalRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;15type InternalRetryOptions = InternalOptions['retry'];1617const defaultRetryOptions: InternalRetryOptions = {18 limit: 2,19 methods: retryMethods,
5 unmodified lines
25 jitter: undefined,26 retryOnTimeout: false,27};2829const getDefaultRetryOptions = (): InternalRetryOptions => ({30 ...defaultRetryOptions,31 methods: [...defaultRetryOptions.methods],32 statusCodes: [...defaultRetryOptions.statusCodes],33 afterStatusCodes: [...defaultRetryOptions.afterStatusCodes],34});3536/**37Normalizes an omitted retry limit or validates a supplied one.38*/39const normalizeRetryLimit = (retryLimit: unknown): number => {40 if (retryLimit === undefined) {41 return defaultRetryOptions.limit;42 }4344 if (typeof retryLimit !== 'number' || !Number.isInteger(retryLimit) || retryLimit < 0) {45 throw new TypeError(invalidRetryLimitErrorMessage);46 }4748 return retryLimit;49};5051export const normalizeRetryOptions = (retry: number | RetryOptions = {}): InternalRetryOptions => {52 if (typeof retry === 'number') {53 return {31 ...defaultRetryOptions,32 limit: retry,54 ...getDefaultRetryOptions(),55 limit: normalizeRetryLimit(retry),56 };57 }5836 if (retry.methods && !Array.isArray(retry.methods)) {59 if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {60 throw new TypeError('`retry` must be a number or an object');61 }6263 const normalizedRetry = Object.fromEntries(Object.entries(retry).filter(([, value]) => value !== undefined)) as RetryOptions;64 const retryLimit = normalizeRetryLimit(normalizedRetry.limit);6566 if (normalizedRetry.methods !== undefined && !Array.isArray(normalizedRetry.methods)) {67 throw new Error('retry.methods must be an array');68 }6940 if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {70 if (normalizedRetry.statusCodes !== undefined && !Array.isArray(normalizedRetry.statusCodes)) {71 throw new Error('retry.statusCodes must be an array');72 }7344 const normalizedRetry = Object.fromEntries(Object.entries({45 ...retry,46 methods: retry.methods?.map(method => method.toLowerCase()),47 }).filter(([, value]) => value !== undefined)) as RetryOptions;74 if (normalizedRetry.afterStatusCodes !== undefined && !Array.isArray(normalizedRetry.afterStatusCodes)) {75 throw new Error('retry.afterStatusCodes must be an array');76 }7778 if (normalizedRetry.methods !== undefined) {79 normalizedRetry.methods = normalizedRetry.methods.map(method => method.toLowerCase());80 }8182 if (normalizedRetry.statusCodes !== undefined) {83 normalizedRetry.statusCodes = [...normalizedRetry.statusCodes];84 }8586 if (normalizedRetry.afterStatusCodes !== undefined) {87 normalizedRetry.afterStatusCodes = [...normalizedRetry.afterStatusCodes];88 }8990 return {50 ...defaultRetryOptions,91 ...getDefaultRetryOptions(),92 ...normalizedRetry,93 limit: retryLimit,94 };95};
modified:test/hooks.ts+184 added
747 unmodified lines
748 t.true(error instanceof TimeoutError);749 t.is(fetchCallCount, 0);750});751752test('totalTimeout bounds a never-ending beforeRequest hook', async t => {753 let markHookStarted: () => void;754 const hookStarted = new Promise<void>(resolve => {755 markHookStarted = resolve;756 });757 const neverSettlingPromise = new Promise<never>(() => {758 void 0;759 });760761 const request = ky('https://example.com', {762 fetch: async () => new Response('ok'),763 totalTimeout: 500,764 hooks: {765 beforeRequest: [766 async () => {767 markHookStarted();768 await neverSettlingPromise;769 },770 ],771 },772 }).text();773774 await hookStarted;775776 const result = await Promise.race([777 request.catch((error: unknown) => error),778 delay(2000).then(() => 'still pending'),779 ]);780781 t.true(result instanceof TimeoutError);782});783784test.serial('totalTimeout rejects a hook result produced after the deadline', async t => {785 const originalPerformanceNow = globalThis.performance.now;786 let currentTime = 0;787 let didCancelBody = false;788 globalThis.performance.now = () => currentTime;789790 t.teardown(() => {791 globalThis.performance.now = originalPerformanceNow;792 });793794 await t.throwsAsync(795 ky('https://example.com', {796 totalTimeout: 500,797 hooks: {798 beforeRequest: [799 () => {800 currentTime = 501;801 return new Response(new ReadableStream({802 cancel() {803 didCancelBody = true;804 },805 }));806 },807 ],808 },809 }),810 {811 instanceOf: TimeoutError,812 },813 );814815 await delay(0);816 t.true(didCancelBody);817});818819test.serial('totalTimeout takes precedence over a hook error produced after the deadline', async t => {820 const originalPerformanceNow = globalThis.performance.now;821 let currentTime = 0;822 globalThis.performance.now = () => currentTime;823824 t.teardown(() => {825 globalThis.performance.now = originalPerformanceNow;826 });827828 await t.throwsAsync(829 ky('https://example.com', {830 totalTimeout: 500,831 hooks: {832 beforeRequest: [833 () => {834 currentTime = 501;835 throw new Error('late hook error');836 },837 ],838 },839 }),840 {841 instanceOf: TimeoutError,842 },843 );844});845846test('totalTimeout bounds a never-ending afterResponse hook', async t => {847 let markHookStarted: () => void;848 let didAbort = false;849 const hookStarted = new Promise<void>(resolve => {850 markHookStarted = resolve;851 });852 const neverSettlingPromise = new Promise<never>(() => {853 void 0;854 });855856 const request = ky('https://example.com', {857 async fetch(request) {858 request.signal.addEventListener('abort', () => {859 didAbort = true;860 }, {once: true});861862 return new Response('ok');863 },864 totalTimeout: 500,865 hooks: {866 afterResponse: [867 async () => {868 markHookStarted();869 await neverSettlingPromise;870 },871 ],872 },873 }).text();874875 await hookStarted;876877 const result = await Promise.race([878 request.catch((error: unknown) => error),879 delay(2000).then(() => 'still pending'),880 ]);881882 t.true(result instanceof TimeoutError);883 t.true(didAbort);884});885886test('beforeRequest hook runs only once and does not run again on retry', async t => {887 let fetchCallCount = 0;888 let beforeRequestCallCount = 0;889 const beforeRequestRetryCounts: number[] = [];
322 unmodified lines
1212 t.is(beforeRetryCallCount, 1);1213 t.is(fetchCallCount, 1);1214});12151216test('totalTimeout bounds a never-ending beforeRetry hook', async t => {1217 let markHookStarted: () => void;1218 let beforeErrorCallCount = 0;1219 const hookStarted = new Promise<void>(resolve => {1220 markHookStarted = resolve;1221 });1222 const neverSettlingPromise = new Promise<never>(() => {1223 void 0;1224 });12251226 const request = ky('https://example.com', {1227 fetch: async () => new Response('error', {status: 500}),1228 totalTimeout: 500,1229 retry: {1230 limit: 1,1231 delay: () => 0,1232 },1233 hooks: {1234 beforeRetry: [1235 async () => {1236 markHookStarted();1237 await neverSettlingPromise;1238 },1239 ],1240 beforeError: [1241 ({error}) => {1242 beforeErrorCallCount++;1243 return error;1244 },1245 ],1246 },1247 }).text();12481249 await hookStarted;12501251 const result = await Promise.race([1252 request.catch((error: unknown) => error),1253 delay(2000).then(() => 'still pending'),1254 ]);12551256 t.true(result instanceof TimeoutError);1257 t.is(beforeErrorCallCount, 1);1258});12591260test('catches beforeRetry thrown errors', async t => {1261 let requestCount = 0;1262 let beforeErrorHookCalled = false;1263
524 unmodified lines
1788 t.false('searchParams' in options);1789 t.false('timeout' in options);1790 t.false('throwHttpErrors' in options);1791 t.false('fetch' in options);1792 t.false(Object.hasOwn(options, 'onDownloadProgress'));1793 t.false(Object.hasOwn(options, 'onUploadProgress'));17941795 // Verify options object is frozen (can't add/modify properties)1796 t.throws(() => {1797 // @ts-expect-error - Testing freeze behavior1798 options.newProperty = 'test';1799 });18001801 t.throws(() => {1802 Object.assign(options, {retry: options.retry});1803 });18041805 // Verify nested objects like headers are still mutable1806 t.notThrows(() => {1807 options.headers.set('X-Test', 'value');1808 });
3672 unmodified lines
modified:test/main.ts+1 added-1 removed
914 unmodified lines
915 const start = Date.now();916 await t.throwsAsync(ky('https://example.com', {917 fetch: customFetch,918 timeout: false,919 totalTimeout: 50,919 totalTimeout: 500,920 }).text(), {921 instanceOf: TimeoutError,922 });923 t.true(didStartBodyRead);
1933 unmodified lines
modified:test/retry.ts+417 added
793 unmodified lines
794 );795 t.is(requestCount, 4);796});797798test('rejects invalid retry limits', t => {799 for (const limit of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1.5]) {800 t.throws(() => {801 void ky('https://example.com', {802 retry: {803 limit,804 },805 });806 }, {807 instanceOf: TypeError,808 message: '`retry.limit` must be a finite, non-negative integer',809 });810811 t.throws(() => {812 void ky('https://example.com', {retry: limit});813 }, {814 instanceOf: TypeError,815 message: '`retry.limit` must be a finite, non-negative integer',816 });817 }818});819820test('rejects non-number retry limits', t => {821 for (const limit of ['NaN', true, null]) {822 t.throws(() => {823 void ky('https://example.com', {824 retry: {825 limit: limit as never,826 },827 });828 }, {829 instanceOf: TypeError,830 message: '`retry.limit` must be a finite, non-negative integer',831 });832 }833});834835test('does not enable retries after sending an uncloned request body', async t => {836 let requestCount = 0;837838 await t.throwsAsync(839 ky('https://example.com', {840 method: 'put',841 body: 'body',842 async fetch(input) {843 requestCount++;844 await (input as Request).text();845 return new Response(null, {status: 500});846 },847 retry: {848 limit: 0,849 methods: ['put'],850 },851 hooks: {852 afterResponse: [({options}) => {853 options.retry.limit = 1;854 }],855 },856 }).text(),857 {858 message: /status code 500/,859 },860 );861862 t.is(requestCount, 1);863});864865test('allows response hooks to disable retries', async t => {866 let requestCount = 0;867868 await t.throwsAsync(869 ky('https://example.com', {870 async fetch() {871 requestCount++;872 return new Response(null, {status: 500});873 },874 retry: {875 limit: 1,876 delay: () => 0,877 },878 hooks: {879 afterResponse: [({options}) => {880 options.retry.limit = 0;881 }],882 },883 }).text(),884 {885 message: /status code 500/,886 },887 );888889 t.is(requestCount, 1);890});891892test('uses the retry limit set by a beforeRequest hook that returns a response', async t => {893 let requestCount = 0;894895 const response = await ky('https://example.com', {896 async fetch() {897 requestCount++;898 return new Response('ok');899 },900 retry: {901 limit: 0,902 delay: () => 0,903 },904 hooks: {905 beforeRequest: [({options}) => {906 options.retry.limit = 1;907 return new Response(null, {status: 500});908 }],909 afterResponse: [({response, retryCount}) => {910 if (retryCount === 0 && response.status === 500) {911 return ky.retry();912 }913 }],914 },915 }).text();916917 t.is(response, 'ok');918 t.is(requestCount, 1);919});920921test('uses the normalized retry limit when cloning request bodies', async t => {922 let requestCount = 0;923924 await t.throwsAsync(925 ky('https://example.com', {926 method: 'put',927 body: 'body',928 async fetch(input) {929 requestCount++;930 await (input as Request).text();931 return new Response(null, {status: 500});932 },933 retry: {934 limit: 1,935 methods: ['put'],936 delay: () => 0,937 },938 hooks: {939 init: [options => {940 options.retry = {941 limit: undefined,942 methods: ['put'],943 delay: () => 0,944 };945 }],946 },947 }).text(),948 {949 message: /status code 500/,950 },951 );952953 t.is(requestCount, 3);954});955956test('rejects invalid retry option values', t => {957 for (const retry of [true, 'NaN', []]) {958 t.throws(() => {959 void ky('https://example.com', {retry: retry as never});960 }, {961 instanceOf: TypeError,962 message: '`retry` must be a number or an object',963 });964965 t.throws(() => {966 void ky('https://example.com', {967 retry: retry as never,968 hooks: {969 init: [() => undefined],970 },971 });972 }, {973 instanceOf: TypeError,974 message: '`retry` must be a number or an object',975 });976 }977});978979test('init hooks can sanitize retry options before validation', async t => {980 let requestCount = 0;981982 await t.throwsAsync(983 ky('https://example.com', {984 async fetch() {985 requestCount++;986 return new Response(null, {status: 500});987 },988 retry: {989 limit: Number.NaN,990 },991 hooks: {992 init: [options => {993 options.retry = 0;994 }],995 },996 }).text(),997 );998 t.is(requestCount, 1);999});10001001test('respect retry methods', async t => {1002 let requestCount = 0;10031004 const server = await createHttpTestServer(t);
449 unmodified lines
1454 methods: 'get',1455 },1456 });1457 });14581459 t.throws(() => {1460 void ky(server.url, {1461 retry: {1462 // @ts-expect-error1463 methods: 'get',1464 },1465 hooks: {1466 init: [() => undefined],1467 },1468 });1469 });1470});14711472test('throws when retry.statusCodes is not an array', async t => {1473 const server = await createHttpTestServer(t);
5 unmodified lines
1479 statusCodes: 403,1480 },1481 });1482 });14831484 t.throws(() => {1485 void ky(server.url, {1486 retry: {1487 // @ts-expect-error1488 statusCodes: 403,1489 },1490 hooks: {1491 init: [() => undefined],1492 },1493 });1494 });1495});14961497test('throws when retry.afterStatusCodes is not an array', async t => {1498 const server = await createHttpTestServer(t);14991500 t.throws(() => {1501 void ky(server.url, {1502 retry: {1503 // @ts-expect-error1504 afterStatusCodes: 503,1505 },1506 });1507 });15081509 t.throws(() => {1510 void ky(server.url, {1511 retry: {1512 // @ts-expect-error1513 afterStatusCodes: 503,1514 },1515 hooks: {1516 init: [() => undefined],1517 },1518 });1519 });1520});15211522test('throws when retry array options are falsy non-arrays', t => {1523 for (const [key, value] of [1524 ['methods', 0],1525 ['statusCodes', false],1526 ['afterStatusCodes', null],1527 ] as const) {1528 const retry = {[key]: value};15291530 t.throws(() => {1531 void ky('https://example.com', {1532 retry: retry as never,1533 });1534 });15351536 t.throws(() => {1537 void ky('https://example.com', {1538 retry: retry as never,1539 hooks: {1540 init: [() => undefined],1541 },1542 });1543 });1544 }1545});15461547test('request hooks cannot mutate default retry status codes', async t => {1548 await ky('https://example.com', {1549 async fetch() {1550 return new Response('ok');1551 },1552 hooks: {1553 beforeRequest: [({options}) => {1554 options.retry.statusCodes!.push(418);1555 }],1556 },1557 }).text();15581559 let requestCount = 0;1560 await t.throwsAsync(1561 ky('https://example.com', {1562 async fetch() {1563 requestCount++;1564 return new Response(null, {status: 418});1565 },1566 }).text(),1567 {1568 message: /status code 418/,1569 },1570 );15711572 t.is(requestCount, 1);1573});15741575test('request hooks cannot mutate custom retry arrays', async t => {1576 const retry = {1577 limit: 1,1578 statusCodes: [500],1579 afterStatusCodes: [500],1580 delay: () => 0,1581 };15821583 await ky('https://example.com', {1584 retry,1585 async fetch() {1586 return new Response('ok');1587 },1588 hooks: {1589 beforeRequest: [({options}) => {1590 options.retry.statusCodes.push(418);1591 options.retry.afterStatusCodes.push(418);1592 }],1593 },1594 }).text();15951596 t.deepEqual(retry.statusCodes, [500]);1597 t.deepEqual(retry.afterStatusCodes, [500]);15981599 let requestCount = 0;1600 await t.throwsAsync(1601 ky('https://example.com', {1602 retry,1603 async fetch() {1604 requestCount++;1605 return new Response(null, {status: 418});1606 },1607 }).text(),1608 {1609 message: /status code 418/,1610 },1611 );16121613 t.is(requestCount, 1);1614});16151616test('validates retry array mutations from response hooks', async t => {1617 await t.throwsAsync(1618 ky('https://example.com', {1619 async fetch() {1620 return new Response(null, {status: 500});1621 },1622 hooks: {1623 afterResponse: [({options}) => {1624 options.retry.statusCodes = null as never;1625 }],1626 },1627 }).text(),1628 {1629 message: 'retry.statusCodes must be an array',1630 },1631 );1632});16331634test('validates retry array mutations before sending the request', async t => {1635 let requestCount = 0;16361637 await t.throwsAsync(1638 ky('https://example.com', {1639 async fetch() {1640 requestCount++;1641 return new Response('ok');1642 },1643 hooks: {1644 beforeRequest: [({options}) => {1645 options.retry.statusCodes = null as never;1646 }],1647 },1648 }).text(),1649 {1650 message: 'retry.statusCodes must be an array',1651 },1652 );16531654 t.is(requestCount, 0);1655});16561657test('retry options ignore undefined overrides and keep defaults', async t => {1658 let requestCount = 0;16591660 const server = await createHttpTestServer(t);
446 unmodified lines
2107 // At most 1-2 attempts fit within the 500ms totalTimeout (each takes ~300ms)2108 t.true(requestCount >= 1 && requestCount <= 2);2109});21102111test('totalTimeout bounds a never-ending shouldRetry callback', async t => {2112 let markCallbackStarted: () => void;2113 const callbackStarted = new Promise<void>(resolve => {2114 markCallbackStarted = resolve;2115 });2116 const neverSettlingPromise = new Promise<never>(() => {2117 void 0;2118 });21192120 const request = ky('https://example.com', {2121 fetch: async () => new Response('error', {status: 500}),2122 totalTimeout: 500,2123 retry: {2124 async shouldRetry() {2125 markCallbackStarted();2126 await neverSettlingPromise;2127 },2128 },2129 }).text();21302131 await callbackStarted;21322133 const result = await Promise.race([2134 request.catch((error: unknown) => error),2135 delay(2000).then(() => 'still pending'),2136 ]);21372138 t.true(result instanceof TimeoutError);2139});21402141test('shouldRetry: returns false - prevents retry', async t => {2142 let requestCount = 0;21432144 const server = await createHttpTestServer(t);
1130 unmodified lines
added:test-d/normalized-options.ts+56 added
1import {expectTypeOf} from 'expect-type';2import type {3 BeforeRequestState,4 HTTPError,5 NormalizedOptions,6 Options,7 RetryOptions,8} from 'ky';910declare module 'ky' {11 interface Options { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- Declaration merging requires an interface.12 customOption?: string;13 }1415 interface NormalizedOptions { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- Declaration merging requires an interface.16 customOption?: string;17 }18}1920type ExpectedNormalizedRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;21type ExpectedProgressCallbacks = {22 readonly onDownloadProgress?: NonNullable<Options['onDownloadProgress']>;23 readonly onUploadProgress?: NonNullable<Options['onUploadProgress']>;24};2526declare const options: NormalizedOptions;27declare const beforeRequestState: BeforeRequestState;28declare const httpError: HTTPError;29const contextKey = 'test';3031expectTypeOf(options.headers).toEqualTypeOf<Headers>();32expectTypeOf(options.retry).branded.toEqualTypeOf<ExpectedNormalizedRetryOptions>();33expectTypeOf<Readonly<Pick<NormalizedOptions, keyof ExpectedProgressCallbacks>>>().branded.toEqualTypeOf<ExpectedProgressCallbacks>();3435options.headers.set('x-test', 'value');36options.context[contextKey] = true;37options.retry.limit = 0;38options.retry.statusCodes.push(500);3940// @ts-expect-error - The normalized options object is frozen.41options.method = 'POST';4243// @ts-expect-error - Inherited request options are frozen too.44options.cache = 'no-store';4546// @ts-expect-error - The normalized options object is frozen.47options.context = {};4849// @ts-expect-error - The normalized options object is frozen.50options.retry = {...options.retry};5152// @ts-expect-error - Module-augmented options passed to hooks are frozen too.53beforeRequestState.options.customOption = 'value';5455// @ts-expect-error - Module-augmented options attached to errors are frozen too.56httpError.options.customOption = 'value';
modified:package.json+1 added-1 removed
20 unmodified lines
21 "engines": {22 "node": ">=22"23 },24 "scripts": {25 "test": "xo && npm run build && ava",25 "test": "xo && npm run build && tsc --project tsconfig.test.json && ava",26 "debug": "PWDEBUG=1 ava --timeout=2m",27 "release": "np",28 "build": "del-cli distribution && tsc --project tsconfig.dist.json",29 "prepare": "npm run build"
70 unmodified lines
modified:readme.md+4 added
290 unmodified lines
291Controls retry behavior. Each field is documented individually below.292293If `retry` is a number, it will be used as `limit` and other defaults will remain in place.294295`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.296297Network 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.298299`413 Payload Too Large` is only retried when the response includes a retry timing header.300
126 unmodified lines
427Default: `false`428429Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.430431`beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.432433If set to `false` or not specified, there is no overall timeout.434435```js436import ky from 'ky';
1438 unmodified lines
added:tsconfig.test.json+10 added
1{2 "extends": "./tsconfig.json",3 "compilerOptions": {4 "noEmit": true,5 "rootDir": "."6 },7 "include": [8 "test-d"9 ]10}