Skip to content
Myr

resilience.ts

This file

Path

test/resilience.ts

1,121 lines · 33.5 KiB · TypeScript

Last changed by

Fix CISindre Sorhusbefore adoptiond9ddb03

History of this file

Take it

1import {once} from 'node:events';2import {setTimeout as delay} from 'node:timers/promises';3import test from 'ava';4import ky, {5	HTTPError,6	NetworkError,7	TimeoutError,8	type Options,9} from '../source/index.js';10import {createHttpTestServer} from './helpers/create-http-test-server.js';1112/*13Scenarios adapted from the HTTP resilience comparison at https://fetchkit.org/http-resilience/1415Every cancellation and deadline test checks the same contract:16- The caller settles promptly, not when the wait would have ended.17- Nothing reaches the transport after the cancellation.18- A hung attempt sees its signal aborted.19- The next request on the same instance still works.20*/2122const url = 'https://example.com/resource';2324type Step =25	| {status?: number; body?: string; headers?: HeadersInit}26	| 'hang'27	| Error;2829// A fetch that serves `steps` in order, records what each attempt sent, and fails loudly on an unexpected attempt. Every call counts as an attempt, even one with an aborted signal, so a stray dispatch after a cancellation is visible.30function scriptedFetch(steps: Step[]) {31	const transport = {32		attempts: 0,33		active: 0,34		aborted: 0,35		requests: [] as Request[],36		bodies: [] as string[],37		async fetch(input: RequestInfo | URL): Promise<Response> {38			if (!(input instanceof Request)) {39				throw new TypeError('Expected Ky to call fetch with a Request');40			}4142			const step = steps[transport.attempts++];43			transport.requests.push(input);4445			// Like native fetch, an aborted signal rejects before anything is sent.46			input.signal.throwIfAborted();4748			transport.active++;4950			try {51				transport.bodies.push(input.body ? await input.text() : '');5253				if (step === undefined) {54					throw new Error(`Unexpected attempt ${transport.attempts}`);55				}5657				if (step === 'hang') {58					if (!input.signal.aborted) {59						await once(input.signal, 'abort');60					}6162					transport.aborted++;63					input.signal.throwIfAborted();64				}6566				if (step instanceof Error) {67					throw step;68				}6970				const {status = 200, body = '', headers = {}} = step as Exclude<Step, 'hang' | Error>;71				return new Response(body, {status, headers});72			} finally {73				transport.active--;74			}75		},76	};7778	return transport;79}8081// Tracks a promise without awaiting it, so a test can check whether it has settled yet.82function observe<T>(promise: Promise<T>) {83	const state: {settled: boolean; value?: T; error?: unknown} = {settled: false};84	void (async () => {85		try {86			state.value = await promise;87		} catch (error) {88			state.error = error;89		} finally {90			state.settled = true;91		}92	})();9394	return state;95}9697const busy = (body = 'busy'): Step => ({status: 503, body});98const ready = (body = 'ready'): Step => ({body});99const networkError = () => new TypeError('fetch failed');100101// Options shared by the scripted scenarios: fixed delays, no jitter, and no per-attempt timeout unless a test sets one.102function client(transport: ReturnType<typeof scriptedFetch>, options: Options = {}) {103	return ky.create({104		fetch: transport.fetch,105		timeout: false,106		...options,107		retry: {108			limit: 2,109			delay: () => 20,110			jitter: false,111			...(typeof options.retry === 'object' ? options.retry : {}),112		},113	});114}115116// Basic retry contract117118test('recovers after two 503 responses with exactly three attempts and no later dispatch', async t => {119	const transport = scriptedFetch([busy(), busy(), ready()]);120121	t.is(await client(transport)(url).text(), 'ready');122	t.is(transport.attempts, 3);123124	await delay(100);125	t.is(transport.attempts, 3);126	t.is(transport.active, 0);127});128129test('retry exhaustion rejects with the response of the last attempt', async t => {130	const transport = scriptedFetch([busy('busy-1'), busy('busy-2'), busy('busy-3')]);131132	const error = await t.throwsAsync(client(transport)(url).text(), {instanceOf: HTTPError});133	t.is(error.response.status, 503);134	t.is(error.data, 'busy-3');135	t.is(transport.attempts, 3);136137	await delay(100);138	t.is(transport.attempts, 3);139});140141test('retry: 0 makes exactly one attempt and rejects with its response', async t => {142	const transport = scriptedFetch([busy('only')]);143144	const error = await t.throwsAsync(client(transport, {retry: {limit: 0}})(url).text(), {instanceOf: HTTPError});145	t.is(error.data, 'only');146	t.is(transport.attempts, 1);147148	await delay(100);149	t.is(transport.attempts, 1);150});151152test('recovers after two network errors with exactly three attempts', async t => {153	const transport = scriptedFetch([networkError(), networkError(), ready()]);154155	t.is(await client(transport)(url).text(), 'ready');156	t.is(transport.attempts, 3);157});158159test('recovers across different failure kinds in one retry sequence', async t => {160	const transport = scriptedFetch([busy(), networkError(), {status: 500}, {status: 429}, ready()]);161162	t.is(await client(transport, {retry: {limit: 4}})(url).text(), 'ready');163	t.is(transport.attempts, 5);164});165166test('exhaustion after a network error rejects with a NetworkError that keeps the last raw error', async t => {167	const last = networkError();168	const transport = scriptedFetch([busy(), networkError(), last]);169170	const error = await t.throwsAsync(client(transport)(url), {instanceOf: NetworkError});171	t.is(error.cause, last);172	t.is(transport.attempts, 3);173});174175test('an exhausted request does not affect the next request on the same instance', async t => {176	const transport = scriptedFetch([busy(), busy(), busy(), ready('next')]);177	const api = client(transport);178179	await t.throwsAsync(api(url), {instanceOf: HTTPError});180	t.is(await api(url).text(), 'next');181	t.is(transport.attempts, 4);182});183184test('every attempt reaches the transport with the same method, URL and headers', async t => {185	const transport = scriptedFetch([busy(), networkError(), ready()]);186187	await client(transport)(url, {headers: {'x-trace': 'abc'}, searchParams: {page: 2}});188189	t.is(transport.requests.length, 3);190	for (const request of transport.requests) {191		t.is(request.method, 'GET');192		t.is(request.url, `${url}?page=2`);193		t.is(request.headers.get('x-trace'), 'abc');194	}195});196197test('every attempt gets its own Request with an unaborted signal', async t => {198	const transport = scriptedFetch([busy(), busy(), ready()]);199200	await client(transport)(url);201202	const [first, second, third] = transport.requests;203	t.not(first, second);204	t.not(second, third);205	for (const request of transport.requests) {206		t.false(request.signal.aborted);207	}208});209210// Retry + abort during backoff211212test('aborting during the backoff settles promptly with the abort reason and dispatches nothing more', async t => {213	const transport = scriptedFetch([busy(), ready('healthy'), ready('healthy')]);214	const api = client(transport, {retry: {delay: () => 1000}});215	const controller = new AbortController();216217	const result = observe(api(url, {signal: controller.signal}).text());218	await delay(20);219	controller.abort();220	await delay(50);221222	t.true(result.settled, 'Cancellation must settle during the backoff');223	t.is(result.error, controller.signal.reason);224225	await delay(1100);226	t.is(transport.attempts, 1, 'No dispatch after cancellation');227228	t.is(await api(url).text(), 'healthy');229	t.is(transport.attempts, 2);230	t.is(transport.active, 0);231});232233test('aborting during the default exponential backoff settles promptly', async t => {234	const transport = scriptedFetch([busy()]);235	const controller = new AbortController();236237	// The first default delay is 300ms.238	const result = observe(ky(url, {239		fetch: transport.fetch, timeout: false, retry: {limit: 2, jitter: false}, signal: controller.signal,240	}).text());241	await delay(20);242	controller.abort();243	await delay(50);244245	t.true(result.settled);246	t.is(result.error, controller.signal.reason);247248	await delay(400);249	t.is(transport.attempts, 1);250});251252test('aborting during the second backoff stops after two attempts', async t => {253	const transport = scriptedFetch([busy(), busy(), ready()]);254	const controller = new AbortController();255	const api = client(transport, {retry: {delay: attemptCount => attemptCount === 1 ? 10 : 1000}});256257	const result = observe(api(url, {signal: controller.signal}));258	await delay(100);259	t.is(transport.attempts, 2);260	controller.abort();261	await delay(50);262263	t.true(result.settled);264	t.is(result.error, controller.signal.reason);265266	await delay(1000);267	t.is(transport.attempts, 2);268});269270test('aborting during the backoff after a network error rejects with the abort reason, not a NetworkError', async t => {271	const transport = scriptedFetch([networkError()]);272	const controller = new AbortController();273274	const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal: controller.signal}));275	await delay(20);276	controller.abort();277	await delay(50);278279	t.true(result.settled);280	t.is(result.error, controller.signal.reason);281	t.is(transport.attempts, 1);282});283284test('aborting during the backoff after a timed out attempt rejects with the abort reason', async t => {285	const transport = scriptedFetch(['hang']);286	const controller = new AbortController();287288	const result = observe(client(transport, {289		timeout: 30,290		retry: {retryOnTimeout: true, delay: () => 1000},291	})(url, {signal: controller.signal}));292	await delay(100);293	t.is(transport.aborted, 1, 'The per-attempt timeout must abort the hung attempt');294	controller.abort();295	await delay(50);296297	t.true(result.settled);298	t.is(result.error, controller.signal.reason);299300	await delay(1000);301	t.is(transport.attempts, 1);302	t.is(transport.active, 0);303});304305test('a non-Error abort reason during the backoff reaches the caller unchanged', async t => {306	const transport = scriptedFetch([busy()]);307	const controller = new AbortController();308309	const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal: controller.signal}));310	await delay(20);311	controller.abort('gave up');312	await delay(50);313314	t.true(result.settled);315	t.is(result.error, 'gave up');316	t.is(transport.attempts, 1);317});318319test('an AbortSignal.timeout() caller signal ends the backoff with its own TimeoutError', async t => {320	const transport = scriptedFetch([busy()]);321	const signal = AbortSignal.timeout(50);322323	const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal}));324	await delay(150);325326	t.true(result.settled);327	t.is(result.error, signal.reason);328	t.false(result.error instanceof TimeoutError, 'A caller deadline is not a Ky timeout');329	t.is((result.error as DOMException).name, 'TimeoutError');330	t.is(transport.attempts, 1);331});332333test('a signal from the instance defaults ends the backoff', async t => {334	const transport = scriptedFetch([busy()]);335	const controller = new AbortController();336	const api = client(transport, {retry: {delay: () => 1000}, signal: controller.signal});337338	const result = observe(api(url));339	await delay(20);340	controller.abort();341	await delay(50);342343	t.true(result.settled);344	t.is(result.error, controller.signal.reason);345	t.is(transport.attempts, 1);346});347348test('a signal on a Request input ends the backoff', async t => {349	const transport = scriptedFetch([busy()]);350	const controller = new AbortController();351352	const result = observe(client(transport, {retry: {delay: () => 1000}})(new Request(url, {signal: controller.signal})));353	await delay(20);354	controller.abort();355	await delay(50);356357	t.true(result.settled);358	t.is(result.error, controller.signal.reason);359	t.is(transport.attempts, 1);360});361362test('aborting during the backoff does not run beforeRetry hooks', async t => {363	const transport = scriptedFetch([busy()]);364	const controller = new AbortController();365	let beforeRetryCalls = 0;366367	const result = observe(client(transport, {368		retry: {delay: () => 200},369		hooks: {370			beforeRetry: [() => {371				beforeRetryCalls++;372			}],373		},374	})(url, {signal: controller.signal}));375	await delay(20);376	controller.abort();377	await delay(300);378379	t.true(result.settled);380	t.is(beforeRetryCalls, 0);381	t.is(transport.attempts, 1);382});383384test('aborting during the backoff reaches beforeError hooks as the abort reason', async t => {385	const transport = scriptedFetch([busy()]);386	const controller = new AbortController();387	const seen: unknown[] = [];388389	const result = observe(client(transport, {390		retry: {delay: () => 1000},391		hooks: {392			beforeError: [({error}) => {393				seen.push(error);394				return error;395			}],396		},397	})(url, {signal: controller.signal}));398	await delay(20);399	controller.abort(new Error('cancelled'));400	await delay(50);401402	t.true(result.settled);403	t.deepEqual(seen, [controller.signal.reason]);404	t.is(result.error, controller.signal.reason);405});406407test('aborting one request during its backoff does not affect a concurrent request on the same instance', async t => {408	const transport = scriptedFetch([busy(), busy(), ready('second')]);409	const api = client(transport, {retry: {delay: () => 150}});410	const controller = new AbortController();411412	const first = observe(api(url, {signal: controller.signal}).text());413	const second = api(url).text();414	await delay(20);415	controller.abort();416	await delay(50);417418	t.true(first.settled);419	t.is(first.error, controller.signal.reason);420	t.is(await second, 'second');421422	await delay(200);423	t.is(transport.attempts, 3);424});425426test('aborting many concurrent requests during their backoff leaves nothing running', async t => {427	const count = 20;428	const transport = scriptedFetch(Array.from({length: count}, () => busy()));429	const api = client(transport, {retry: {delay: () => 1000}});430	const controller = new AbortController();431432	const results = Array.from({length: count}, () => observe(api(url, {signal: controller.signal})));433	await delay(50);434	t.is(transport.attempts, count);435	controller.abort();436	await delay(50);437438	for (const result of results) {439		t.true(result.settled);440		t.is(result.error, controller.signal.reason);441	}442443	await delay(1000);444	t.is(transport.attempts, count);445	t.is(transport.active, 0);446});447448test('an already aborted signal rejects with its reason and is not retried', async t => {449	const transport = scriptedFetch([ready()]);450	const controller = new AbortController();451	controller.abort();452453	const error = await t.throwsAsync(client(transport)(url, {signal: controller.signal}));454	t.is(error, controller.signal.reason);455456	// Ky leaves the aborted signal to fetch, which rejects before sending anything.457	await delay(100);458	t.is(transport.attempts, 1);459});460461test('aborting during a hung attempt aborts that attempt and does not retry', async t => {462	const transport = scriptedFetch(['hang', ready()]);463	const controller = new AbortController();464465	const result = observe(client(transport)(url, {signal: controller.signal}));466	await delay(20);467	controller.abort();468	await delay(50);469470	t.true(result.settled);471	t.is(result.error, controller.signal.reason);472	t.is(transport.aborted, 1);473	t.is(transport.active, 0);474475	await delay(100);476	t.is(transport.attempts, 1);477});478479test('aborting during a hung retry aborts that attempt and does not retry again', async t => {480	const transport = scriptedFetch([busy(), 'hang', ready()]);481	const controller = new AbortController();482483	const result = observe(client(transport)(url, {signal: controller.signal}));484	// Wait for the retry to start, since a busy machine can stretch the retry delay.485	while (transport.attempts < 2) {486		// eslint-disable-next-line no-await-in-loop487		await delay(5);488	}489490	controller.abort();491	await delay(50);492493	t.true(result.settled);494	t.is(result.error, controller.signal.reason);495	t.is(transport.aborted, 1);496	t.is(transport.active, 0);497498	await delay(100);499	t.is(transport.attempts, 2);500});501502// Retry + total timeout503504test('totalTimeout expiring during the backoff rejects at the deadline and never dispatches the retry', async t => {505	const transport = scriptedFetch([busy(), ready('healthy')]);506	const api = client(transport, {totalTimeout: 300, retry: {limit: 1, delay: () => 1000}});507508	const result = observe(api(url));509	await delay(150);510	t.false(result.settled, 'The deadline must not fire early');511	await delay(300);512513	t.true(result.settled, 'The deadline must cover the backoff');514	t.true(result.error instanceof TimeoutError);515516	await delay(700);517	t.is(transport.attempts, 1, 'No dispatch after the deadline');518519	t.is(await api(url).text(), 'healthy');520	t.is(transport.attempts, 2);521});522523test('totalTimeout expiring during a hung retry aborts that attempt', async t => {524	const transport = scriptedFetch([busy(), 'hang', ready('healthy')]);525	const api = client(transport, {totalTimeout: 300, retry: {limit: 1, delay: () => 20}});526527	const result = observe(api(url));528	await delay(150);529	t.false(result.settled);530	t.is(transport.attempts, 2);531	await delay(300);532533	t.true(result.settled);534	t.true(result.error instanceof TimeoutError);535	t.is(transport.aborted, 1, 'The hung attempt must be aborted');536	t.is(transport.active, 0);537538	await delay(100);539	t.is(transport.attempts, 2);540541	t.is(await api(url).text(), 'healthy');542});543544test('totalTimeout aborts a hung first attempt when the per-attempt timeout is disabled', async t => {545	const transport = scriptedFetch(['hang']);546547	const error = await t.throwsAsync(client(transport, {totalTimeout: 300})(url), {instanceOf: TimeoutError});548	t.is(error.request.url, url);549	await delay(10);550	t.is(transport.attempts, 1);551	t.is(transport.aborted, 1);552	t.is(transport.active, 0);553});554555test('each request on an instance gets a fresh totalTimeout budget', async t => {556	const transport = scriptedFetch([busy(), ready('one'), busy(), ready('two')]);557	const api = client(transport, {totalTimeout: 500, retry: {delay: () => 120}});558559	t.is(await api(url).text(), 'one');560	// A shared budget would be spent by now.561	await delay(400);562	t.is(await api(url).text(), 'two');563	t.is(transport.attempts, 4);564});565566test('totalTimeout aborts every hung attempt under per-attempt timeouts and retryOnTimeout', async t => {567	const transport = scriptedFetch(['hang', 'hang', 'hang', 'hang']);568	// The deadline is not a multiple of the 50ms attempt cycle, so it never ties with an attempt starting.569	const api = client(transport, {timeout: 40, totalTimeout: 175, retry: {limit: 10, retryOnTimeout: true, delay: () => 10}});570571	await t.throwsAsync(api(url), {instanceOf: TimeoutError});572	await delay(10);573	t.is(transport.active, 0);574	t.is(transport.aborted, transport.attempts);575576	const {attempts} = transport;577	await delay(100);578	t.is(transport.attempts, attempts);579});580581test('per-attempt timeouts with retryOnTimeout abort every hung attempt and stop at the retry limit', async t => {582	const transport = scriptedFetch(['hang', 'hang', 'hang']);583584	await t.throwsAsync(client(transport, {timeout: 30, retry: {retryOnTimeout: true}})(url), {instanceOf: TimeoutError});585	await delay(10);586	t.is(transport.attempts, 3);587	t.is(transport.aborted, 3);588	t.is(transport.active, 0);589});590591// Retry-After + abort592593const retryAfterCases = [594	{595		title: 'delay seconds',596		header: () => '1',597		options: {},598		minimum: 1000,599		maximum: 1000,600	},601	{602		title: 'an HTTP date',603		// HTTP dates have second precision, so the wait lands between one and two seconds.604		header: () => new Date(Date.now() + 2000).toUTCString(),605		options: {},606		minimum: 1000,607		maximum: 2000,608	},609	{610		title: 'a malformed value',611		header: () => 'soon',612		options: {},613		// Falls back to the configured `delay`.614		minimum: 150,615		maximum: 150,616	},617	{618		title: 'a value above maxRetryAfter',619		header: () => '1000',620		options: {maxRetryAfter: 300},621		minimum: 300,622		maximum: 300,623	},624] as const;625626for (const {title, header, options, minimum, maximum} of retryAfterCases) {627	test(`Retry-After with ${title} controls the retry delay`, async t => {628		const transport = scriptedFetch([{status: 503, headers: {'Retry-After': header()}}, ready()]);629		const api = client(transport, {630			retry: {631				limit: 1, afterStatusCodes: [503], delay: () => 150, ...options,632			},633		});634635		const result = observe(api(url).text());636		// Before the expected delay, and after the 150ms fallback for every case that should not use it.637		await delay(minimum - 50);638		t.is(transport.attempts, 1, 'The retry must wait for the advertised delay');639640		await delay(maximum - minimum + 300);641		t.true(result.settled);642		t.is(result.value, 'ready');643		t.is(transport.attempts, 2);644	});645646	test(`aborting during a Retry-After wait with ${title} settles promptly and dispatches nothing more`, async t => {647		const transport = scriptedFetch([{status: 503, headers: {'Retry-After': header()}}, ready()]);648		const api = client(transport, {649			retry: {650				limit: 1, afterStatusCodes: [503], delay: () => 150, ...options,651			},652		});653		const controller = new AbortController();654655		const result = observe(api(url, {signal: controller.signal}));656		await delay(20);657		controller.abort();658		await delay(50);659660		t.true(result.settled, 'Abort must interrupt the header-derived wait');661		t.is(result.error, controller.signal.reason);662663		await delay(maximum + 100);664		t.is(transport.attempts, 1, 'No dispatch after the wait is cancelled');665	});666}667668test('Retry-After on a status outside afterStatusCodes uses the configured backoff', async t => {669	const transport = scriptedFetch([{status: 503, headers: {'Retry-After': '10'}}, ready()]);670	const api = client(transport, {retry: {limit: 1, afterStatusCodes: [429], delay: () => 50}});671672	const result = observe(api(url).text());673	await delay(300);674675	t.true(result.settled);676	t.is(result.value, 'ready');677});678679// Retry + throwing hooks680681// Each hook throws only on its first call, so a follow-up request shows the instance is still usable.682const hookCases: Array<{title: string; options: (throwOnce: () => void) => Options}> = [683	{684		title: 'a synchronous shouldRetry',685		options: throwOnce => ({686			retry: {687				shouldRetry() {688					throwOnce();689					return undefined;690				},691			},692		}),693	},694	{695		title: 'an asynchronous shouldRetry',696		options: throwOnce => ({697			retry: {698				async shouldRetry() {699					await delay(5);700					throwOnce();701					return undefined;702				},703			},704		}),705	},706	{707		title: 'a synchronous beforeRetry hook',708		options: throwOnce => ({709			hooks: {710				beforeRetry: [throwOnce],711			},712		}),713	},714	{715		title: 'an asynchronous beforeRetry hook',716		options: throwOnce => ({717			hooks: {718				beforeRetry: [async () => {719					await delay(5);720					throwOnce();721				}],722			},723		}),724	},725	{726		title: 'retry.delay',727		options: throwOnce => ({728			retry: {729				delay() {730					throwOnce();731					return 20;732				},733			},734		}),735	},736	{737		title: 'retry.jitter',738		options: throwOnce => ({739			retry: {740				jitter(delay) {741					throwOnce();742					return delay;743				},744			},745		}),746	},747];748749for (const {title, options} of hookCases) {750	test(`an error thrown from ${title} reaches the caller unchanged and is not retried`, async t => {751		const transport = scriptedFetch([busy(), busy(), ready('healthy')]);752		const sentinel = new Error(`sentinel: ${title}`);753		let armed = true;754		const api = client(transport, options(() => {755			if (armed) {756				armed = false;757				throw sentinel;758			}759		}));760761		const result = observe(api(url));762		await delay(200);763764		t.true(result.settled, 'A throwing hook must settle the caller');765		t.is(result.error, sentinel);766		t.is(transport.attempts, 1);767768		t.is(await api(url).text(), 'healthy');769		t.is(transport.attempts, 3);770	});771}772773test('an error thrown from an afterResponse hook on a retryable response is not retried', async t => {774	const transport = scriptedFetch([busy(), ready()]);775	const sentinel = new Error('afterResponse');776777	const error = await t.throwsAsync(client(transport, {778		hooks: {779			afterResponse: [() => {780				throw sentinel;781			}],782		},783	})(url));784	t.is(error, sentinel);785	t.is(transport.attempts, 1);786});787788test('a beforeRetry hook that throws on the second retry stops after two attempts', async t => {789	const transport = scriptedFetch([busy(), busy(), ready()]);790	const sentinel = new Error('second retry');791792	const error = await t.throwsAsync(client(transport, {793		hooks: {794			beforeRetry: [({retryCount}) => {795				if (retryCount === 2) {796					throw sentinel;797				}798			}],799		},800	})(url));801	t.is(error, sentinel);802	t.is(transport.attempts, 2);803});804805test('a shouldRetry that throws after a network error reaches the caller unchanged', async t => {806	const transport = scriptedFetch([networkError(), ready()]);807	const sentinel = new Error('shouldRetry');808809	const error = await t.throwsAsync(client(transport, {810		retry: {811			shouldRetry() {812				throw sentinel;813			},814		},815	})(url));816	t.is(error, sentinel);817	t.is(transport.attempts, 1);818});819820// Retry + body replay821822const payload = 'payload: café / 123 🦄';823const bytes = new TextEncoder().encode(payload);824825// `expected` is the exact body on the wire and `contentType` its header, left out when there is none. Both are left out for FormData, whose boundary is random.826const bodyCases: Array<{title: string; expected?: string; contentType?: string; send: (transport: ReturnType<typeof scriptedFetch>) => Promise<unknown>}> = [827	{828		title: 'a string',829		contentType: 'text/plain;charset=UTF-8',830		expected: payload,831		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: payload}),832	},833	{834		title: 'a Uint8Array',835		expected: payload,836		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: bytes}),837	},838	{839		title: 'an ArrayBuffer',840		expected: payload,841		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new TextEncoder().encode(payload).buffer}),842	},843	{844		title: 'a Blob',845		expected: payload,846		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new Blob([payload])}),847	},848	{849		title: 'URLSearchParams',850		contentType: 'application/x-www-form-urlencoded;charset=UTF-8',851		expected: new URLSearchParams({payload}).toString(),852		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new URLSearchParams({payload})}),853	},854	{855		title: 'FormData',856		async send(transport) {857			const formData = new FormData();858			formData.append('payload', payload);859			formData.append('file', new Blob([bytes]), 'file.txt');860			return client(transport, {retry: {methods: ['post']}}).post(url, {body: formData});861		},862	},863	{864		title: 'json',865		contentType: 'application/json',866		expected: JSON.stringify({payload}),867		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {json: {payload}}),868	},869	{870		title: 'a ReadableStream',871		expected: payload,872		send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {873			body: new ReadableStream({874				start(controller) {875					controller.enqueue(bytes.slice(0, 5));876					controller.enqueue(bytes.slice(5));877					controller.close();878				},879			}),880		}),881	},882	{883		title: 'a Request input with a string body',884		contentType: 'text/plain;charset=UTF-8',885		expected: payload,886		send: async transport => client(transport, {retry: {methods: ['post']}})(new Request(url, {method: 'POST', body: payload})),887	},888	{889		title: 'a Request input with a stream body',890		expected: payload,891		send: async transport => client(transport, {retry: {methods: ['post']}})(new Request(url, {892			method: 'POST',893			body: new ReadableStream({894				start(controller) {895					controller.enqueue(bytes);896					controller.close();897				},898			}),899			duplex: 'half',900		} as RequestInit)),901	},902	{903		title: 'a PUT under the default retry methods',904		contentType: 'text/plain;charset=UTF-8',905		expected: payload,906		send: async transport => client(transport).put(url, {body: payload}),907	},908];909910for (const {title, expected, contentType, send} of bodyCases) {911	test(`a retry resends ${title} body byte for byte`, async t => {912		const transport = scriptedFetch([busy(), networkError(), ready()]);913914		await send(transport);915916		t.is(transport.attempts, 3);917		const contentTypes = transport.requests.map(request => request.headers.get('content-type'));918		if (expected === undefined) {919			const boundary = contentTypes[0]?.split('multipart/form-data; boundary=')[1];920			t.truthy(boundary);921			t.true(transport.bodies[0]!.includes(`--${boundary}`), 'The body must use the boundary from the header');922			t.true(transport.bodies[0]!.includes(payload));923		} else {924			t.is(transport.bodies[0], expected);925			t.is(contentTypes[0] ?? undefined, contentType);926		}927928		t.deepEqual(transport.bodies, Array.from({length: 3}, () => transport.bodies[0]));929		t.deepEqual(contentTypes, Array.from({length: 3}, () => contentTypes[0]));930	});931}932933test('aborting during the backoff of a POST with a stream body dispatches nothing more', async t => {934	const transport = scriptedFetch([busy(), ready()]);935	const controller = new AbortController();936937	const result = observe(client(transport, {retry: {methods: ['post'], delay: () => 1000}}).post(url, {938		signal: controller.signal,939		body: new ReadableStream({940			start(streamController) {941				streamController.enqueue(bytes);942				streamController.close();943			},944		}),945	}));946	await delay(20);947	controller.abort();948	await delay(50);949950	t.true(result.settled);951	t.is(result.error, controller.signal.reason);952953	await delay(1000);954	t.deepEqual(transport.bodies, [payload]);955});956957// Real HTTP958959// Waits for `promise`, failing instead of hanging when it takes longer than two seconds.960async function withinTwoSeconds<T>(promise: Promise<T>, message: string): Promise<T> {961	const timeout = delay(2000, undefined, {ref: false}).then(() => {962		throw new Error(message);963	});964965	return Promise.race([promise, timeout]);966}967968test('retry over real HTTP recovers after two 503 responses', async t => {969	const server = await createHttpTestServer(t);970	const arrivals: string[] = [];971	server.get('/flaky', (request, response) => {972		arrivals.push(request.url);973		if (arrivals.length < 3) {974			response.sendStatus(503);975			return;976		}977978		response.end('ready');979	});980981	t.is(await ky(`${server.url}/flaky`, {retry: {limit: 2, delay: () => 5}}).text(), 'ready');982	t.deepEqual(arrivals, ['/flaky', '/flaky', '/flaky']);983});984985test('a timeout over real HTTP closes the hung connection and the next request still works', async t => {986	const server = await createHttpTestServer(t);987	const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();988	server.get('/slow', (_request, response) => {989		response.once('close', markClosed);990	});991	server.get('/', (_request, response) => {992		response.end('ready');993	});994995	await t.throwsAsync(ky(`${server.url}/slow`, {timeout: 100, retry: 0}), {instanceOf: TimeoutError});996	await withinTwoSeconds(closed, 'The hung connection was not closed');997	t.is(await ky(server.url).text(), 'ready');998});9991000test('a totalTimeout over real HTTP closes the hung retry connection', async t => {1001	const server = await createHttpTestServer(t);1002	const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();1003	let arrivals = 0;1004	server.get('/', (_request, response) => {1005		arrivals++;1006		if (arrivals === 1) {1007			response.sendStatus(503);1008			return;1009		}10101011		response.once('close', markClosed);1012	});10131014	await t.throwsAsync(ky(server.url, {timeout: false, totalTimeout: 1000, retry: {limit: 1, delay: () => 20}}), {instanceOf: TimeoutError});1015	await withinTwoSeconds(closed, 'The hung retry connection was not closed');1016	t.is(arrivals, 2);1017});10181019test('aborting during the backoff over real HTTP makes exactly one arrival', async t => {1020	const server = await createHttpTestServer(t);1021	const {promise: firstArrival, resolve: markFirstArrival} = Promise.withResolvers<void>();1022	let arrivals = 0;1023	server.get('/', (_request, response) => {1024		arrivals++;1025		response.sendStatus(503);1026		markFirstArrival();1027	});1028	const controller = new AbortController();10291030	const result = observe(ky(server.url, {signal: controller.signal, retry: {limit: 2, delay: () => 1000}}));1031	await firstArrival;1032	// Let Ky receive the response and start the backoff.1033	await delay(100);1034	controller.abort();1035	await delay(50);10361037	t.true(result.settled);1038	t.is(result.error, controller.signal.reason);1039	await delay(1000);1040	t.is(arrivals, 1);1041});10421043test('aborting a hung attempt over real HTTP closes its connection and does not retry', async t => {1044	const server = await createHttpTestServer(t);1045	const {promise: arrived, resolve: markArrived} = Promise.withResolvers<void>();1046	const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();1047	let arrivals = 0;1048	server.get('/', (_request, response) => {1049		arrivals++;1050		response.once('close', markClosed);1051		markArrived();1052	});1053	const controller = new AbortController();10541055	const result = observe(ky(server.url, {signal: controller.signal, timeout: false, retry: {limit: 2, delay: () => 5}}));1056	await arrived;1057	controller.abort();1058	await delay(50);10591060	t.true(result.settled);1061	t.is(result.error, controller.signal.reason);1062	await withinTwoSeconds(closed, 'The aborted connection was not closed');1063	await delay(100);1064	t.is(arrivals, 1);1065});10661067test('aborting while Ky reads a retryable error body over real HTTP settles promptly and does not retry', async t => {1068	const server = await createHttpTestServer(t);1069	const {promise: arrived, resolve: markArrived} = Promise.withResolvers<void>();1070	let arrivals = 0;1071	server.get('/', (_request, response) => {1072		arrivals++;1073		// The error body never ends, so Ky is still reading it when the caller aborts.1074		response.writeHead(503, {'content-type': 'text/plain'});1075		response.write('partial');1076		markArrived();1077	});1078	const controller = new AbortController();10791080	const result = observe(ky(server.url, {signal: controller.signal, timeout: false, retry: {limit: 2, delay: () => 5}}));1081	await arrived;1082	await delay(100);1083	t.false(result.settled);1084	controller.abort();1085	await delay(50);10861087	t.true(result.settled);1088	t.is(result.error, controller.signal.reason);1089	await delay(100);1090	t.is(arrivals, 1);1091});10921093test('a POST body is resent byte for byte over real HTTP', async t => {1094	const server = await createHttpTestServer(t, {bodyParser: false});1095	const bodies: string[] = [];1096	server.post('/', async (request, response) => {1097		const chunks: Uint8Array[] = [];1098		for await (const chunk of request) {1099			chunks.push(chunk as Uint8Array);1100		}11011102		bodies.push(Buffer.concat(chunks).toString());1103		if (bodies.length === 1) {1104			response.sendStatus(503);1105			return;1106		}11071108		response.end('ready');1109	});11101111	t.is(await ky.post(server.url, {1112		body: new ReadableStream({1113			start(controller) {1114				controller.enqueue(bytes);1115				controller.close();1116			},1117		}),1118		retry: {limit: 1, methods: ['post'], delay: () => 5},1119	}).text(), 'ready');1120	t.deepEqual(bodies, [payload, payload]);1121});