Add `retryOnTimeout` and `shouldRetry` options (#767)
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 081c924 · Browse files · 9 files·+779 added−37 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+779 added−37 removed
- tests:+537 added−10 removed
- other:+242 added−27 removed
Provenance
- Commit
f0fdbd4- Tree
83013f1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
081c924
9 files changed+779 added−37 removed
modified:source/core/Ky.ts+62 added-21 removed
1 import {HTTPError} from '../errors/HTTPError.js';2+import {NonError} from '../errors/NonError.js';3 import type {4 Input,5 InternalOptions,6 NormalizedOptions,147 unmodified lines154 return searchParams;155 }156 157 public request: Request;157- readonly #abortController?: AbortController;158+ #abortController?: AbortController;159 #retryCount = 0;160 // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202161 #input: Input;162 readonly #options: InternalOptions;163 #originalRequest?: Request;164+ readonly #userProvidedAbortSignal?: AbortSignal;165 #cachedNormalizedOptions?: NormalizedOptions;166 167 // eslint-disable-next-line complexity168 constructor(input: Input, options: Options = {}) {36 unmodified lines205 this.#input = this.#options.prefixUrl + this.#input;206 }207 208 if (supportsAbortController && supportsAbortSignal) {207- const originalSignal = this.#options.signal ?? (this.#input as Request).signal;209+ this.#userProvidedAbortSignal = this.#options.signal ?? (this.#input as Request).signal;210 this.#abortController = new globalThis.AbortController();209- this.#options.signal = originalSignal ? AbortSignal.any([originalSignal, this.#abortController.signal]) : this.#abortController.signal;211+ this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;212 }213 214 if (supportsRequestStreams) {215 // @ts-expect-error - Types are outdated.48 unmodified lines264 }265 }266 }267 268+ #calculateDelay(): number {269+ const retryDelay = this.#options.retry.delay(this.#retryCount);270+271+ let jitteredDelay = retryDelay;272+ if (this.#options.retry.jitter === true) {273+ jitteredDelay = Math.random() * retryDelay;274+ } else if (typeof this.#options.retry.jitter === 'function') {275+ jitteredDelay = this.#options.retry.jitter(retryDelay);276+277+ if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {278+ jitteredDelay = retryDelay;279+ }280+ }281+282+ return Math.min(this.#options.retry.backoffLimit, jitteredDelay);283+ }284+266- #calculateRetryDelay(error: unknown) {285+ async #calculateRetryDelay(error: unknown) {286 this.#retryCount++;287 269- if (this.#retryCount > this.#options.retry.limit || isTimeoutError(error)) {288+ if (this.#retryCount > this.#options.retry.limit) {289 throw error;290 }291 292+ // Wrap non-Error throws to ensure consistent error handling293+ const errorObject = error instanceof Error ? error : new NonError(error);294+295+ // User-provided shouldRetry function takes precedence over all other checks296+ if (this.#options.retry.shouldRetry !== undefined) {297+ const result = await this.#options.retry.shouldRetry({error: errorObject, retryCount: this.#retryCount});298+299+ // Strict boolean checking - only exact true/false are handled specially300+ if (result === false) {301+ throw error;302+ }303+304+ if (result === true) {305+ // Force retry - skip all other validation and return delay306+ return this.#calculateDelay();307+ }308+309+ // If undefined or any other value, fall through to default behavior310+ }311+312+ // Default timeout behavior313+ if (isTimeoutError(error) && !this.#options.retry.retryOnTimeout) {314+ throw error;315+ }316+317 if (isHTTPError(error)) {318 if (!this.#options.retry.statusCodes.includes(error.response.status)) {319 throw error;320 }11 unmodified lines332 after -= Date.now();333 }334 335 const max = this.#options.retry.maxRetryAfter ?? after;336+ // Don't apply jitter when server provides explicit retry timing337 return after < max ? after : max;338 }339 340 if (error.response.status === 413) {341 throw error;342 }343 }344 300- const retryDelay = this.#options.retry.delay(this.#retryCount);301-302- let jitteredDelay = retryDelay;303- if (this.#options.retry.jitter === true) {304- jitteredDelay = Math.random() * retryDelay;305- } else if (typeof this.#options.retry.jitter === 'function') {306- jitteredDelay = this.#options.retry.jitter(retryDelay);307-308- if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {309- jitteredDelay = retryDelay;310- }311- }312-313- return Math.min(this.#options.retry.backoffLimit, jitteredDelay);345+ return this.#calculateDelay();346 }347 348 #decorateResponse(response: Response): Response {349 if (this.#options.parseJson) {6 unmodified lines356 async #retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | void> {357 try {358 return await function_();359 } catch (error) {328- const ms = Math.min(this.#calculateRetryDelay(error), maxSafeTimeout);360+ const ms = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);361 if (this.#retryCount < 1) {362 throw error;363 }364 333- await delay(ms, {signal: this.#options.signal});365+ // Only use user-provided signal for delay, not our internal abortController366+ await delay(ms, this.#userProvidedAbortSignal ? {signal: this.#userProvidedAbortSignal} : {});367 368 for (const hook of this.#options.hooks.beforeRetry) {369 // eslint-disable-next-line no-await-in-loop370 const hookResult = await hook({13 unmodified lines384 }385 }386 387 async #fetch(): Promise<Response> {388+ // Reset abortController if it was aborted (happens on timeout retry)389+ if (this.#abortController?.signal.aborted) {390+ this.#abortController = new globalThis.AbortController();391+ this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;392+ // Recreate request with new signal393+ this.request = new globalThis.Request(this.request, {signal: this.#options.signal});394+ }395+396 for (const hook of this.#options.hooks.beforeRequest) {397 // eslint-disable-next-line no-await-in-loop398 const result = await hook(399 this.request,36 unmodified linesadded:source/errors/NonError.ts+28 added
12345678910111213141516171819202122232425262728/**Wrapper for non-Error values that were thrown.
In JavaScript, any value can be thrown (not just Error instances). This class wraps such values to ensure consistent error handling.*/export class NonError extends Error { override name = 'NonError'; readonly value: unknown;
constructor(value: unknown) { let message = 'Non-error value was thrown';
// Intentionally minimal as this error is just an edge-case. try { if (typeof value === 'string') { message = value; } else if (value && typeof value === 'object' && 'message' in value && typeof value.message === 'string') { message = value.message; } } catch { // Use default message if accessing properties throws }
super(message);
this.value = value; }}modified:source/types/options.ts+2 added-2 removed
295 unmodified lines296 'fetch' | 'prefixUrl' | 'timeout'297 > & {298 headers: Required<Headers>;299 hooks: Required<Hooks>;300- retry: Required<RetryOptions>;300+ retry: Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;301 prefixUrl: string;302 };303 304 /**10 unmodified lines315 onDownloadProgress: Options['onDownloadProgress'];316 onUploadProgress: Options['onUploadProgress'];317 }318 319-export type {RetryOptions} from './retry.js';319+export type {RetryOptions, ShouldRetryState} from './retry.js';modified:source/types/retry.ts+77 added
1234567891011121314151683 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169export type ShouldRetryState = { /** The error that caused the request to fail. */ error: Error;
/** The number of retries attempted. Starts at 1 for the first retry. */ retryCount: number;};
export type RetryOptions = { /** The number of times to retry failed requests.
83 unmodified lines }).json(); ``` */ jitter?: boolean | ((delay: number) => number) | undefined;
/** Whether to retry when the request times out.
@default false
@example ``` import ky from 'ky';
const json = await ky('https://example.com', { retry: { limit: 3, retryOnTimeout: true } }).json(); ``` */ retryOnTimeout?: boolean;
/** A function to determine whether a retry should be attempted.
This function takes precedence over all other retry checks and is called first, before any other retry validation.
**Note:** This is different from the `beforeRetry` hook: - `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made) - `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request
Should return: - `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations) - `false` to prevent a retry (no retry will occur) - `undefined` to use the default retry logic (`retryOnTimeout`, status codes, etc.)
@example ``` import ky, {HTTPError} from 'ky';
const json = await ky('https://example.com', { retry: { limit: 3, shouldRetry: ({error, retryCount}) => { // Retry on specific business logic errors from API if (error instanceof HTTPError) { const status = error.response.status;
// Retry on 429 (rate limit) but only for first 2 attempts if (status === 429 && retryCount <= 2) { return true; }
// Don't retry on 4xx errors except rate limits if (status >= 400 && status < 500) { return false; } }
// Use default retry logic for other errors return undefined; } } }).json(); ``` */ shouldRetry?: (state: ShouldRetryState) => boolean | undefined | Promise<boolean | undefined>;};modified:source/utils/normalize.ts+5 added-2 removed
9 unmodified lines1011121314151416171819202122232425262725282930313216 unmodified lines9 unmodified linesconst retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
const retryAfterStatusCodes = [413, 429, 503];
type InternalRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;
const defaultRetryOptions: Required<RetryOptions> = {const defaultRetryOptions: InternalRetryOptions = { limit: 2, methods: retryMethods, statusCodes: retryStatusCodes, afterStatusCodes: retryAfterStatusCodes, maxRetryAfter: Number.POSITIVE_INFINITY, backoffLimit: Number.POSITIVE_INFINITY, delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000, jitter: undefined, retryOnTimeout: false,};
export const normalizeRetryOptions = (retry: number | RetryOptions = {}): Required<RetryOptions> => {export const normalizeRetryOptions = (retry: number | RetryOptions = {}): InternalRetryOptions => { if (typeof retry === 'number') { return { ...defaultRetryOptions, limit: retry,16 unmodified linesmodified:source/index.ts+4 added
39 unmodified lines40 Input,41 Options,42 NormalizedOptions,43 RetryOptions,44+ ShouldRetryState,45 SearchParamsOption,46 Progress,47 } from './types/options.js';48 14 unmodified lines63 export type {KyResponse} from './types/response.js';64 export {HTTPError} from './errors/HTTPError.js';65 export {TimeoutError} from './errors/TimeoutError.js';66 export {isKyError, isHTTPError, isTimeoutError} from './utils/type-guards.js';67+68+// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least.69+// export {NonError} from './errors/NonError.js';modified:test/helpers/with-performance.ts+2 added-2 removed
7 unmodified lines8 test: () => Promise<void>;9 };10 11 // We allow the tests to take more time on CI than locally, to reduce flakiness12-// Node.js 24 has higher overhead on CI (~400-450ms), so we increase the tolerance12+// Node.js 22+ has higher overhead on CI (~400-650ms), so we increase the tolerance13 const nodeVersion = Number(process.versions.node.split('.')[0]);14-const allowedOffset = process.env.CI ? (nodeVersion >= 24 ? 500 : 300) : 200;14+const allowedOffset = process.env.CI ? (nodeVersion >= 22 ? 700 : 300) : 200;15 16 export async function withPerformance({17 expectedDuration,18 t,12 unmodified linesmodified:test/retry.ts+535 added-8 removed
1+import {setTimeout as delay} from 'node:timers/promises';2 import test from 'ava';3 import ky from '../source/index.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5 import {withPerformance} from './helpers/with-performance.js';690 unmodified lines696 697 t.is(requestCount, 4);698 699 // Full jitter should produce delays between 0 and the computed delay699- // Add 20% tolerance for system overhead700- t.true(delays[0] >= 0 && delays[0] <= 360);701- t.true(delays[1] >= 0 && delays[1] <= 720);702- t.true(delays[2] >= 0 && delays[2] <= 1440);700+ // Add 50% tolerance for system overhead and CI variability701+ t.true(delays[0] >= 0 && delays[0] <= 450);702+ t.true(delays[1] >= 0 && delays[1] <= 900);703+ t.true(delays[2] >= 0 && delays[2] <= 1800);704 705 await server.close();706 });707 71 unmodified lines779 780 // With backoffLimit of 500, all delays should be <= 500ms781 // Even though the computed delays would be 300, 600, 1200782 // After jitter and backoffLimit, they should all be <= 500782- // Add 20% tolerance for system overhead783- t.true(delays[0] >= 0 && delays[0] <= 600);784- t.true(delays[1] >= 0 && delays[1] <= 600);785- t.true(delays[2] >= 0 && delays[2] <= 600);783+ // Add 50% tolerance for system overhead and CI variability784+ t.true(delays[0] >= 0 && delays[0] <= 750);785+ t.true(delays[1] >= 0 && delays[1] <= 750);786+ t.true(delays[2] >= 0 && delays[2] <= 750);787 788 await server.close();789 });790 72 unmodified lines863 t.true(timeElapsedInMs >= 2000);864 865 await server.close();866 });867+868+test('retryOnTimeout: false (default) - does not retry on timeout', async t => {869+ let requestCount = 0;870+871+ const server = await createHttpTestServer();872+ server.get('/', async (_request, response) => {873+ requestCount++;874+ // Delay longer than timeout to trigger timeout875+ await delay(1000);876+ response.end(fixture);877+ });878+879+ await t.throwsAsync(880+ ky(server.url, {881+ timeout: 500,882+ retry: {883+ limit: 3,884+ },885+ }).text(),886+ {887+ name: 'TimeoutError',888+ },889+ );890+891+ t.is(requestCount, 1); // Should not retry892+893+ await server.close();894+});895+896+test('retryOnTimeout: true - retries on timeout', async t => {897+ let requestCount = 0;898+899+ const server = await createHttpTestServer();900+ server.get('/', async (_request, response) => {901+ requestCount++;902+ if (requestCount <= 2) {903+ // Delay longer than timeout to trigger timeout904+ await delay(1000);905+ response.end(fixture);906+ } else {907+ response.end(fixture);908+ }909+ });910+911+ const result = await ky(server.url, {912+ timeout: 500,913+ retry: {914+ limit: 3,915+ retryOnTimeout: true,916+ },917+ }).text();918+919+ t.is(result, fixture);920+ t.is(requestCount, 3); // Initial + 2 retries921+922+ await server.close();923+});924+925+test('retryOnTimeout: true - respects retry limit on timeout', async t => {926+ let requestCount = 0;927+928+ const server = await createHttpTestServer();929+ server.get('/', async (_request, response) => {930+ requestCount++;931+ // Always timeout932+ await delay(2000);933+ });934+935+ await t.throwsAsync(936+ ky(server.url, {937+ timeout: 500,938+ retry: {939+ limit: 2,940+ retryOnTimeout: true,941+ },942+ }).text(),943+ {944+ name: 'TimeoutError',945+ },946+ );947+948+ t.is(requestCount, 3); // Initial + 2 retries949+950+ await server.close();951+});952+953+test('shouldRetry: returns true - forces retry bypassing all checks', async t => {954+ let requestCount = 0;955+956+ const server = await createHttpTestServer();957+ server.get('/', async (_request, response) => {958+ requestCount++;959+ if (requestCount <= 2) {960+ // Delay longer than timeout to trigger timeout961+ await delay(1000);962+ response.end(fixture);963+ } else {964+ response.end(fixture);965+ }966+ });967+968+ const result = await ky(server.url, {969+ timeout: 500,970+ retry: {971+ limit: 3,972+ retryOnTimeout: false, // Disabled973+ shouldRetry: () => true, // But shouldRetry forces retry974+ },975+ }).text();976+977+ t.is(result, fixture);978+ t.is(requestCount, 3);979+980+ await server.close();981+});982+983+test('shouldRetry: returns false - prevents retry', async t => {984+ let requestCount = 0;985+986+ const server = await createHttpTestServer();987+ server.get('/', (_request, response) => {988+ requestCount++;989+ response.sendStatus(500); // Normally retriable990+ });991+992+ await t.throwsAsync(993+ ky(server.url, {994+ retry: {995+ limit: 3,996+ shouldRetry: () => false, // Prevent all retries997+ },998+ }).text(),999+ {1000+ message: /Internal Server Error/,1001+ },1002+ );1003+1004+ t.is(requestCount, 1); // No retries1005+1006+ await server.close();1007+});1008+1009+test('shouldRetry: returns undefined - uses default retry logic', async t => {1010+ let requestCount = 0;1011+1012+ const server = await createHttpTestServer();1013+ server.get('/', (_request, response) => {1014+ requestCount++;1015+ if (requestCount <= 2) {1016+ response.sendStatus(500); // Retriable1017+ } else {1018+ response.end(fixture);1019+ }1020+ });1021+1022+ const result = await ky(server.url, {1023+ retry: {1024+ limit: 3,1025+ shouldRetry: () => undefined, // Fall through to default1026+ },1027+ }).text();1028+1029+ t.is(result, fixture);1030+ t.is(requestCount, 3); // Default retry behavior1031+1032+ await server.close();1033+});1034+1035+test('shouldRetry: receives correct state object', async t => {1036+ let requestCount = 0;1037+ const states: Array<{errorName: string; retryCount: number}> = [];1038+1039+ const server = await createHttpTestServer();1040+ server.get('/', (_request, response) => {1041+ requestCount++;1042+ if (requestCount <= 2) {1043+ response.sendStatus(500);1044+ } else {1045+ response.end(fixture);1046+ }1047+ });1048+1049+ await ky(server.url, {1050+ retry: {1051+ limit: 3,1052+ shouldRetry({error, retryCount}) {1053+ states.push({errorName: error.name, retryCount});1054+ return undefined; // Use default logic1055+ },1056+ },1057+ }).text();1058+1059+ t.is(states.length, 2);1060+ t.is(states[0].errorName, 'HTTPError');1061+ t.is(states[0].retryCount, 1); // First retry1062+ t.is(states[1].errorName, 'HTTPError');1063+ t.is(states[1].retryCount, 2); // Second retry1064+1065+ await server.close();1066+});1067+1068+test('shouldRetry: custom business logic with HTTPError', async t => {1069+ let requestCount = 0;1070+1071+ const server = await createHttpTestServer();1072+ server.get('/', (_request, response) => {1073+ requestCount++;1074+ if (requestCount === 1) {1075+ response.sendStatus(429); // Rate limit1076+ } else if (requestCount === 2) {1077+ response.sendStatus(500); // Server error1078+ } else {1079+ response.end(fixture);1080+ }1081+ });1082+1083+ const result = await ky(server.url, {1084+ retry: {1085+ limit: 3,1086+ async shouldRetry({error, retryCount}) {1087+ const {HTTPError} = await import('../source/index.js');1088+ if (error instanceof HTTPError) {1089+ const {status} = error.response;1090+ // Retry on 429 but only first attempt1091+ if (status === 429 && retryCount <= 1) {1092+ return true;1093+ }1094+1095+ // Don't retry on 4xx1096+ if (status >= 400 && status < 500) {1097+ return false;1098+ }1099+ }1100+1101+ return undefined;1102+ },1103+ },1104+ }).text();1105+1106+ t.is(result, fixture);1107+ t.is(requestCount, 3);1108+1109+ await server.close();1110+});1111+1112+test('shouldRetry: error propagates if shouldRetry throws', async t => {1113+ const server = await createHttpTestServer();1114+ server.get('/', (_request, response) => {1115+ response.sendStatus(500);1116+ });1117+1118+ await t.throwsAsync(1119+ ky(server.url, {1120+ retry: {1121+ limit: 3,1122+ shouldRetry() {1123+ throw new Error('shouldRetry failed');1124+ },1125+ },1126+ }).text(),1127+ {1128+ message: 'shouldRetry failed',1129+ },1130+ );1131+1132+ await server.close();1133+});1134+1135+test('shouldRetry: works with TimeoutError', async t => {1136+ let requestCount = 0;1137+1138+ const server = await createHttpTestServer();1139+ server.get('/', async (_request, response) => {1140+ requestCount++;1141+ if (requestCount <= 2) {1142+ // Delay longer than timeout to trigger timeout1143+ await delay(1000);1144+ response.end(fixture);1145+ } else {1146+ response.end(fixture);1147+ }1148+ });1149+1150+ const result = await ky(server.url, {1151+ timeout: 500,1152+ retry: {1153+ limit: 3,1154+ async shouldRetry({error}) {1155+ const {TimeoutError} = await import('../source/index.js');1156+ return error instanceof TimeoutError;1157+ },1158+ },1159+ }).text();1160+1161+ t.is(result, fixture);1162+ t.is(requestCount, 3);1163+1164+ await server.close();1165+});1166+1167+test('shouldRetry: precedence over retryOnTimeout', async t => {1168+ let requestCount = 0;1169+1170+ const server = await createHttpTestServer();1171+ server.get('/', async (_request, response) => {1172+ requestCount++;1173+ // Delay longer than timeout to trigger timeout1174+ await delay(1000);1175+ response.end(fixture);1176+ });1177+1178+ await t.throwsAsync(1179+ ky(server.url, {1180+ timeout: 500,1181+ retry: {1182+ limit: 3,1183+ retryOnTimeout: true, // Would retry1184+ shouldRetry: () => false, // But shouldRetry prevents it1185+ },1186+ }).text(),1187+ {1188+ name: 'TimeoutError',1189+ },1190+ );1191+1192+ t.is(requestCount, 1); // No retries1193+1194+ await server.close();1195+});1196+1197+test('shouldRetry: works with synchronous function', async t => {1198+ let requestCount = 0;1199+1200+ const server = await createHttpTestServer();1201+ server.get('/', (_request, response) => {1202+ requestCount++;1203+ if (requestCount <= 2) {1204+ response.sendStatus(500);1205+ } else {1206+ response.end(fixture);1207+ }1208+ });1209+1210+ const result = await ky(server.url, {1211+ retry: {1212+ limit: 3,1213+ shouldRetry: () => true, // Sync function returning true1214+ },1215+ }).text();1216+1217+ t.is(result, fixture);1218+ t.is(requestCount, 3);1219+1220+ await server.close();1221+});1222+1223+test('shouldRetry: non-boolean return values fall through to default logic', async t => {1224+ let requestCount = 0;1225+1226+ const server = await createHttpTestServer();1227+ server.get('/', (_request, response) => {1228+ requestCount++;1229+ if (requestCount <= 2) {1230+ response.sendStatus(500); // Retriable by default1231+ } else {1232+ response.end(fixture);1233+ }1234+ });1235+1236+ // Test with various non-boolean return values - all should fall through1237+ const result = await ky(server.url, {1238+ retry: {1239+ limit: 3,1240+ shouldRetry: () => 42 as any, // Non-boolean (number) falls through1241+ },1242+ }).text();1243+1244+ t.is(result, fixture);1245+ t.is(requestCount, 3); // Should retry using default logic1246+1247+ await server.close();1248+});1249+1250+test('shouldRetry: receives proper Error instance even for HTTPError', async t => {1251+ const server = await createHttpTestServer();1252+ server.get('/', (_request, response) => {1253+ response.sendStatus(404);1254+ });1255+1256+ let receivedError: Error | undefined;1257+1258+ await t.throwsAsync(1259+ ky(server.url, {1260+ retry: {1261+ limit: 1,1262+ shouldRetry({error}) {1263+ receivedError = error;1264+ // Verify it's a proper Error instance1265+ t.true(error instanceof Error);1266+ t.is(error.name, 'HTTPError');1267+ return false;1268+ },1269+ },1270+ }).text(),1271+ );1272+1273+ // Ensure shouldRetry was called1274+ t.truthy(receivedError);1275+1276+ await server.close();1277+});1278+1279+test('shouldRetry: combines with default status code logic when returning undefined', async t => {1280+ let requestCount = 0;1281+ const capturedStatuses: number[] = [];1282+1283+ const server = await createHttpTestServer();1284+ server.get('/', (_request, response) => {1285+ requestCount++;1286+ if (requestCount === 1) {1287+ response.sendStatus(500); // Retriable1288+ } else if (requestCount === 2) {1289+ response.sendStatus(404); // Not retriable1290+ } else {1291+ response.end(fixture);1292+ }1293+ });1294+1295+ await t.throwsAsync(1296+ ky(server.url, {1297+ retry: {1298+ limit: 3,1299+ async shouldRetry({error}) {1300+ const {HTTPError} = await import('../source/index.js');1301+ if (error instanceof HTTPError) {1302+ capturedStatuses.push(error.response.status);1303+ }1304+1305+ return undefined; // Fall through to default logic1306+ },1307+ },1308+ }).text(),1309+ {1310+ message: /Not Found/,1311+ },1312+ );1313+1314+ // Should retry on 500, then fail on 4041315+ t.is(requestCount, 2);1316+ t.deepEqual(capturedStatuses, [500, 404]);1317+1318+ await server.close();1319+});1320+1321+test('shouldRetry: retryCount starts at 1 for first retry', async t => {1322+ const retryCounts: number[] = [];1323+1324+ const server = await createHttpTestServer();1325+ server.get('/', (_request, response) => {1326+ response.sendStatus(500);1327+ });1328+1329+ await t.throwsAsync(1330+ ky(server.url, {1331+ retry: {1332+ limit: 3,1333+ shouldRetry({retryCount}) {1334+ retryCounts.push(retryCount);1335+ return retryCount < 3; // Stop at 3rd retry1336+ },1337+ },1338+ }).text(),1339+ );1340+1341+ t.deepEqual(retryCounts, [1, 2, 3]);1342+1343+ await server.close();1344+});1345+1346+test('shouldRetry: handles Promise return value correctly', async t => {1347+ let requestCount = 0;1348+1349+ const server = await createHttpTestServer();1350+ server.get('/', (_request, response) => {1351+ requestCount++;1352+ if (requestCount <= 2) {1353+ response.sendStatus(500);1354+ } else {1355+ response.end(fixture);1356+ }1357+ });1358+1359+ const result = await ky(server.url, {1360+ retry: {1361+ limit: 3,1362+ shouldRetry: async () => true,1363+ },1364+ }).text();1365+1366+ t.is(result, fixture);1367+ t.is(requestCount, 3);1368+1369+ await server.close();1370+});1371+1372+test('shouldRetry: error propagates if shouldRetry returns rejected Promise', async t => {1373+ const server = await createHttpTestServer();1374+ server.get('/', (_request, response) => {1375+ response.sendStatus(500);1376+ });1377+1378+ await t.throwsAsync(1379+ ky(server.url, {1380+ retry: {1381+ limit: 3,1382+ // eslint-disable-next-line @typescript-eslint/promise-function-async1383+ shouldRetry: () => Promise.reject(new Error('shouldRetry Promise rejected')),1384+ },1385+ }).text(),1386+ {1387+ message: 'shouldRetry Promise rejected',1388+ },1389+ );1390+1391+ await server.close();1392+});modified:readme.md+64 added-2 removed
204 unmodified lines205 - `maxRetryAfter`: `undefined`206 - `backoffLimit`: `undefined`207 - `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`208 - `jitter`: `undefined`209+- `retryOnTimeout`: `false`210+- `shouldRetry`: `undefined`211 210-An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.212+An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, `maxRetryAfter`, `backoffLimit`, `delay`, `jitter`, `retryOnTimeout`, and `shouldRetry` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, backoff limit, delay calculation function, retry jitter, timeout retry behavior, and custom retry logic.213 214 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.215 216 If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, 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.9 unmodified lines226 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.227 228 **Note:** Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.229 228-Retries are not triggered following a [timeout](#timeout).230+The `retryOnTimeout` option determines whether to retry when a request times out. By default, retries are not triggered following a [timeout](#timeout).231 232+The `shouldRetry` option provides custom retry logic that **takes precedence over all other retry checks**. This function is called first, before any other retry validation.233+234+**Note:** This is different from the `beforeRetry` hook:235+- `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made)236+- `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request237+238+The function receives a state object with the error and retry count (starts at 1 for the first retry), and should return:239+- `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations)240+- `false` to prevent a retry (no retry will occur)241+- `undefined` to use the default retry logic (`retryOnTimeout`, status codes, etc.)242+243+**General example**244+245 ```js246 import ky from 'ky';247 248 const json = await ky('https://example.com', {5 unmodified lines254 }255 }).json();256 ```257 258+**Retrying on timeout:**259+260 ```js261 import ky from 'ky';262 263 const json = await ky('https://example.com', {264+ timeout: 5000,265 retry: {266+ limit: 3,267+ retryOnTimeout: true268+ }269+}).json();270+```271+272+**Using jitter to prevent thundering herd:**273+274+```js275+import ky from 'ky';276+277+const json = await ky('https://example.com', {278+ retry: {279 limit: 5,280 281 // Full jitter (randomizes delay between 0 and computed value)282 jitter: true6 unmodified lines289 }290 }).json();291 ```292 293+**Custom retry logic:**294+295+```js296+import ky, {HTTPError} from 'ky';297+298+const json = await ky('https://example.com', {299+ retry: {300+ limit: 3,301+ shouldRetry: ({error, retryCount}) => {302+ // Retry on specific business logic errors from API303+ if (error instanceof HTTPError) {304+ const status = error.response.status;305+306+ // Retry on 429 (rate limit) but only for first 2 attempts307+ if (status === 429 && retryCount <= 2) {308+ return true;309+ }310+311+ // Don't retry on 4xx errors except rate limits312+ if (status >= 400 && status < 500) {313+ return false;314+ }315+ }316+317+ // Use default retry logic for other errors318+ return undefined;319+ }320+ }321+}).json();322+```323+324 > [!NOTE]325 > Chromium-based browsers automatically retry `408 Request Timeout` responses at the network layer for keep-alive connections. This means requests may be retried by both the browser and ky. If you want to avoid duplicate retries, you can either set `keepalive: false` in your request options (though this may impact performance for multiple requests) or remove `408` from the retry status codes.326 327 ##### timeout722 unmodified lines