Skip to content
Myr

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

2 files+245 added−16 removed

modified:source/utils/timeout.ts+16 added-15 removed
modified:test/fetch.ts+229 added-1 removed
1import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';2import ky from '../source/index.js';3import ky, {NetworkError} from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';56const fixture = 'https://example.com/unicorn';7
280 unmodified lines
288 delete (Request.prototype as any).next;289 }290 }291});292293test('a synchronously throwing fetch rejects with that error', async t => {294 const error = new Error('sync boom');295296 await t.throwsAsync(ky(fixture, {297 retry: 0,298 fetch() {299 throw error;300 },301 }), {is: error});302});303304test('a synchronously throwing fetch rejects with that error when timeout is disabled', async t => {305 const error = new Error('sync boom');306307 await t.throwsAsync(ky(fixture, {308 retry: 0,309 timeout: false,310 fetch() {311 throw error;312 },313 }), {is: error});314});315316test('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});324325 t.is(error, 'sync boom');326});327328test('a synchronously thrown network error is wrapped in NetworkError and retried', async t => {329 let requestCount = 0;330331 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 }340341 return Promise.resolve(new Response('ok'));342 },343 }).text();344345 t.is(text, 'ok');346 t.is(requestCount, 2);347});348349test('a synchronously thrown network error is visible to beforeRetry hooks', async t => {350 let requestCount = 0;351 const retryErrors: Error[] = [];352353 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 }362363 return Promise.resolve(new Response('ok'));364 },365 hooks: {366 beforeRetry: [367 ({error}) => {368 retryErrors.push(error);369 },370 ],371 },372 }).text();373374 t.is(retryErrors.length, 1);375 t.true(retryErrors[0] instanceof NetworkError);376});377378test('a synchronously throwing fetch runs beforeError hooks', async t => {379 const error = new Error('sync boom');380 const seenErrors: Error[] = [];381382 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});396397 t.deepEqual(seenErrors, [error]);398});399400test('a synchronously throwing fetch does not turn into a TimeoutError when totalTimeout is set', async t => {401 const error = new Error('sync boom');402403 await t.throwsAsync(ky(fixture, {404 retry: 0,405 timeout: 50,406 totalTimeout: 1000,407 fetch() {408 throw error;409 },410 }), {is: error});411});412413test('the timeout of a synchronously throwing attempt does not abort the retried attempt', async t => {414 let requestCount = 0;415 let retriedRequestSignalAborted: boolean | undefined;416417 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 }427428 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();436437 t.is(text, 'ok');438 t.is(requestCount, 2);439 t.false(retriedRequestSignalAborted);440});441442test('the timeout of a synchronously throwing attempt does not abort a retried attempt that reads its body late', async t => {443 let requestCount = 0;444445 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 }455456 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 }465466 controller.enqueue(new TextEncoder().encode('ok'));467 controller.close();468 },469 })));470 },471 });472473 t.is(await responsePromise.text(), 'ok');474 t.is(requestCount, 2);475});476477test('a synchronously throwing retry attempt rejects with that error', async t => {478 let requestCount = 0;479 const error = new Error('sync boom on retry');480481 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 }488489 throw error;490 },491 }), {is: error});492493 t.is(requestCount, 2);494});495496test('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;499500 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 }508509 await delay(80);510 retriedRequestSignalAborted = (request as Request).signal.aborted;511 return new Response('ok');512 },513 }).text();514515 t.is(text, 'ok');516 t.is(requestCount, 2);517 t.false(retriedRequestSignalAborted);518});