Fix a stale timeout timer aborting the retried attempt when a custom `fetch` throws synchronously
Before adoption: this commit came in with the history the project adopted, so no landing records it.
`timeout()` only cleared its timer through the promise chain of the `fetch` result, so a `fetch` option that threw synchronously left the timer running. When the request was then retried, the stale timer fired mid-flight and aborted the shared `AbortController`, cancelling the new attempt or its body read. The timer is now cleared in a `finally` block so it is always released.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent e1b088e · Browse files · 2 files·+245 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+245 added−16 removed
- tests:+229 added−1 removed
- other:+16 added−15 removed
Provenance
- Commit
0f2e281- Tree
937207a- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
e1b088e
2 files changed+245 added−16 removed
modified:source/utils/timeout.ts+16 added-15 removed
10 unmodified lines111213141516171819151621221718192021222324252627282930312425262728293031323310 unmodified lines init: RequestInit, abortController: AbortController | undefined, options: TimeoutOptions,): Promise<Response> { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { if (abortController) { abortController.abort(); } let timeoutId: ReturnType<typeof setTimeout> | undefined;
reject(new TimeoutError(request)); }, options.timeout); try { return await new Promise((resolve, reject) => { timeoutId = setTimeout(() => { if (abortController) { abortController.abort(); }
void options .fetch(request, init) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutId); }); }); reject(new TimeoutError(request)); }, options.timeout);
// A synchronous throw rejects the promise, and `finally` still clears the timer so it cannot abort a later retry attempt. options.fetch(request, init).then(resolve).catch(reject); }); } finally { clearTimeout(timeoutId); }}modified:test/fetch.ts+229 added-1 removed
1+import {setTimeout as delay} from 'node:timers/promises';2 import test from 'ava';2-import ky from '../source/index.js';3+import ky, {NetworkError} from '../source/index.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5 6 const fixture = 'https://example.com/unicorn';7 280 unmodified lines288 delete (Request.prototype as any).next;289 }290 }291 });292+293+test('a synchronously throwing fetch rejects with that error', async t => {294+ const error = new Error('sync boom');295+296+ await t.throwsAsync(ky(fixture, {297+ retry: 0,298+ fetch() {299+ throw error;300+ },301+ }), {is: error});302+});303+304+test('a synchronously throwing fetch rejects with that error when timeout is disabled', async t => {305+ const error = new Error('sync boom');306+307+ await t.throwsAsync(ky(fixture, {308+ retry: 0,309+ timeout: false,310+ fetch() {311+ throw error;312+ },313+ }), {is: error});314+});315+316+test('a synchronously thrown non-Error value is propagated as-is', async t => {317+ const error = await t.throwsAsync<unknown>(ky(fixture, {318+ retry: 0,319+ fetch() {320+ // eslint-disable-next-line @typescript-eslint/only-throw-error321+ throw 'sync boom';322+ },323+ }) as unknown as Promise<unknown>, {any: true});324+325+ t.is(error, 'sync boom');326+});327+328+test('a synchronously thrown network error is wrapped in NetworkError and retried', async t => {329+ let requestCount = 0;330+331+ const text = await ky(fixture, {332+ retry: {limit: 1, delay: () => 0},333+ // Not `async` so the throw stays synchronous.334+ // eslint-disable-next-line @typescript-eslint/promise-function-async335+ fetch() {336+ requestCount++;337+ if (requestCount === 1) {338+ throw new TypeError('Failed to fetch');339+ }340+341+ return Promise.resolve(new Response('ok'));342+ },343+ }).text();344+345+ t.is(text, 'ok');346+ t.is(requestCount, 2);347+});348+349+test('a synchronously thrown network error is visible to beforeRetry hooks', async t => {350+ let requestCount = 0;351+ const retryErrors: Error[] = [];352+353+ await ky(fixture, {354+ retry: {limit: 1, delay: () => 0},355+ // Not `async` so the throw stays synchronous.356+ // eslint-disable-next-line @typescript-eslint/promise-function-async357+ fetch() {358+ requestCount++;359+ if (requestCount === 1) {360+ throw new TypeError('Failed to fetch');361+ }362+363+ return Promise.resolve(new Response('ok'));364+ },365+ hooks: {366+ beforeRetry: [367+ ({error}) => {368+ retryErrors.push(error);369+ },370+ ],371+ },372+ }).text();373+374+ t.is(retryErrors.length, 1);375+ t.true(retryErrors[0] instanceof NetworkError);376+});377+378+test('a synchronously throwing fetch runs beforeError hooks', async t => {379+ const error = new Error('sync boom');380+ const seenErrors: Error[] = [];381+382+ await t.throwsAsync(ky(fixture, {383+ retry: 0,384+ fetch() {385+ throw error;386+ },387+ hooks: {388+ beforeError: [389+ ({error}) => {390+ seenErrors.push(error);391+ return error;392+ },393+ ],394+ },395+ }), {is: error});396+397+ t.deepEqual(seenErrors, [error]);398+});399+400+test('a synchronously throwing fetch does not turn into a TimeoutError when totalTimeout is set', async t => {401+ const error = new Error('sync boom');402+403+ await t.throwsAsync(ky(fixture, {404+ retry: 0,405+ timeout: 50,406+ totalTimeout: 1000,407+ fetch() {408+ throw error;409+ },410+ }), {is: error});411+});412+413+test('the timeout of a synchronously throwing attempt does not abort the retried attempt', async t => {414+ let requestCount = 0;415+ let retriedRequestSignalAborted: boolean | undefined;416+417+ const text = await ky(fixture, {418+ timeout: 100,419+ retry: {limit: 1, delay: () => 50},420+ // Not `async` so the throw stays synchronous.421+ // eslint-disable-next-line @typescript-eslint/promise-function-async422+ fetch(request) {423+ requestCount++;424+ if (requestCount === 1) {425+ throw new TypeError('Failed to fetch');426+ }427+428+ return (async () => {429+ // Resolve after the first attempt's timeout would have fired, but before this attempt's own timeout.430+ await delay(80);431+ retriedRequestSignalAborted = (request as Request).signal.aborted;432+ return new Response('ok');433+ })();434+ },435+ }).text();436+437+ t.is(text, 'ok');438+ t.is(requestCount, 2);439+ t.false(retriedRequestSignalAborted);440+});441+442+test('the timeout of a synchronously throwing attempt does not abort a retried attempt that reads its body late', async t => {443+ let requestCount = 0;444+445+ const responsePromise = ky(fixture, {446+ timeout: 100,447+ retry: {limit: 1, delay: () => 50},448+ // Not `async` so the throw stays synchronous.449+ // eslint-disable-next-line @typescript-eslint/promise-function-async450+ fetch(request) {451+ requestCount++;452+ if (requestCount === 1) {453+ throw new TypeError('Failed to fetch');454+ }455+456+ const {signal} = request as Request;457+ return Promise.resolve(new Response(new ReadableStream({458+ async pull(controller) {459+ // Deliver the body after the first attempt's timeout would have fired, but within this attempt's own body read timeout.460+ await delay(70);461+ if (signal.aborted) {462+ controller.error(signal.reason);463+ return;464+ }465+466+ controller.enqueue(new TextEncoder().encode('ok'));467+ controller.close();468+ },469+ })));470+ },471+ });472+473+ t.is(await responsePromise.text(), 'ok');474+ t.is(requestCount, 2);475+});476+477+test('a synchronously throwing retry attempt rejects with that error', async t => {478+ let requestCount = 0;479+ const error = new Error('sync boom on retry');480+481+ await t.throwsAsync(ky(fixture, {482+ retry: {limit: 1, delay: () => 0},483+ fetch() {484+ requestCount++;485+ if (requestCount === 1) {486+ throw new TypeError('Failed to fetch');487+ }488+489+ throw error;490+ },491+ }), {is: error});492+493+ t.is(requestCount, 2);494+});495+496+test('a fetch that rejects asynchronously does not leave a timer that aborts the retried attempt', async t => {497+ let requestCount = 0;498+ let retriedRequestSignalAborted: boolean | undefined;499+500+ const text = await ky(fixture, {501+ timeout: 100,502+ retry: {limit: 1, delay: () => 50},503+ async fetch(request) {504+ requestCount++;505+ if (requestCount === 1) {506+ throw new TypeError('Failed to fetch');507+ }508+509+ await delay(80);510+ retriedRequestSignalAborted = (request as Request).signal.aborted;511+ return new Response('ok');512+ },513+ }).text();514+515+ t.is(text, 'ok');516+ t.is(requestCount, 2);517+ t.false(retriedRequestSignalAborted);518+});