Fix abortions between retries (#433)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Richie Bendall · committed by GitHub · parent 6d9f7c8 · Browse files · 8 files·+87 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
Diff stats
8 files+87 added−41 removed
- tests:+7 added−4 removed
- other:+80 added−37 removed
Provenance
- Commit
dddf7ba- Tree
b8fff17- Author
Richie Bendall <richiebendall@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
6d9f7c8
8 files changed+87 added−41 removed
modified:source/core/Ky.ts+6 added-3 removed
3 unmodified lines4 import type {Input, InternalOptions, NormalizedOptions, Options, SearchParamsInit} from '../types/options.js';5 import {ResponsePromise} from '../types/ResponsePromise.js';6 import {deepMerge, mergeHeaders} from '../utils/merge.js';7 import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';8-import {delay, timeout, TimeoutOptions} from '../utils/time.js';8+import timeout, {TimeoutOptions} from '../utils/timeout.js';9+import delay from '../utils/delay.js';10 import {ObjectEntries} from '../utils/types.js';11 import {12 maxSafeTimeout,13 responseTypes,139 unmodified lines153 154 if (supportsAbortController) {155 this.abortController = new globalThis.AbortController();156 if (this._options.signal) {157+ const originalSignal = this._options.signal;158+159 this._options.signal.addEventListener('abort', () => {157- this.abortController!.abort();160+ this.abortController!.abort(originalSignal.reason);161 });162 }163 164 this._options.signal = this.abortController.signal;84 unmodified lines249 // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch250 } catch (error) {251 const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);252 if (ms !== 0 && this._retryCount > 0) {250- await delay(ms);253+ await delay(ms, {signal: this._options.signal});254 255 for (const hook of this._options.hooks.beforeRetry) {256 // eslint-disable-next-line no-await-in-loop257 const hookResult = await hook({98 unmodified linesadded:source/errors/DOMException.ts+8 added
12345678const DOMException = globalThis.DOMException ?? Error;
export default DOMException;
// When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)export function composeAbortError(signal?: AbortSignal) { return new DOMException(signal?.reason ?? 'The operation was aborted.');}added:source/utils/delay.ts+34 added
12345678910111213141516171819202122232425262728293031323334// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
import {composeAbortError} from '../errors/DOMException.js';import {InternalOptions} from '../types/options.js';
export interface DelayOptions { signal?: InternalOptions['signal'];}
export default async function delay( ms: number, {signal}: DelayOptions,): Promise<void> { return new Promise((resolve, reject) => { if (signal) { if (signal.aborted) { reject(composeAbortError(signal)); return; }
signal.addEventListener('abort', handleAbort, {once: true}); }
function handleAbort() { reject(composeAbortError(signal!)); clearTimeout(timeoutId); }
const timeoutId = setTimeout(() => { signal?.removeEventListener('abort', handleAbort); resolve(); }, ms); });}deleted:source/utils/time.ts-34 removed
12345678910111213141516171819202122232425262728293031323334import {TimeoutError} from '../errors/TimeoutError.js';
export type TimeoutOptions = { timeout: number; fetch: typeof fetch;};
// `Promise.race()` workaround (#91)export const timeout = async ( request: Request, abortController: AbortController | undefined, options: TimeoutOptions,): Promise<Response> => new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { if (abortController) { abortController.abort(); }
reject(new TimeoutError(request)); }, options.timeout);
void options .fetch(request) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutId); }); });
export const delay = async (ms: number) => new Promise(resolve => { setTimeout(resolve, ms);});added:source/utils/timeout.ts+31 added
12345678910111213141516171819202122232425262728293031import {TimeoutError} from '../errors/TimeoutError.js';
export type TimeoutOptions = { timeout: number; fetch: typeof fetch;};
// `Promise.race()` workaround (#91)export default async function timeout( request: Request, abortController: AbortController | undefined, options: TimeoutOptions,): Promise<Response> { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { if (abortController) { abortController.abort(); }
reject(new TimeoutError(request)); }, options.timeout);
void options .fetch(request) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutId); }); });}modified:test/browser.ts+4 added-2 removed
81 unmodified lines82 83 const error = await page.evaluate(async (url: string) => {84 const controller = new AbortController();85 const request = window.ky(`${url}/test`, {signal: controller.signal}).text();86- controller.abort();86+ controller.abort('🦄');87 return request.catch(error_ => error_.toString());88 }, server.url);89- t.is(error, 'AbortError: Failed to execute \'fetch\' on \'Window\': The user aborted a request.');89 90+ // TODO: When targeting Node.js 18, also assert that the error is a DOMException91+ t.is(error.split(': ')[1], '🦄');92+93 await server.close();94 });95 96 test('should copy origin response info when using `onDownloadProgress`', withPage, async (t: ExecutionContext, page: Page) => {427 unmodified linesmodified:test/main.ts+3 added-2 removed
550 unmodified lines551 552 await server.close();553 });554 555-test('throws AbortError when aborted by user', async t => {555+test('throws DOMException when aborted by user', async t => {556 const server = await createHttpTestServer();557 // eslint-disable-next-line @typescript-eslint/no-empty-function558 server.get('/', () => {});559 1 unmodified line561 const {signal} = abortController;562 const response = ky(server.url, {signal});563 abortController.abort();564 565- await t.throwsAsync(response, {name: 'AbortError'});565+ const {name} = (await t.throwsAsync(response))!;566+ t.true(['DOMException', 'Error'].includes(name), `Expected DOMException or Error, got ${name}`);567 });568 569 test('supports Request instance as input', async t => {570 const server = await createHttpTestServer();133 unmodified linesmodified:package.json+1 added
53 unmodified lines54555657585960616257 unmodified lines53 unmodified lines "@type-challenges/utils": "^0.1.1", "@types/body-parser": "^1.19.2", "@types/busboy": "^0.3.1", "@types/express": "^4.17.14", "@types/node": "^18.11.7", "@types/node-fetch": "^2.6.2", "abort-controller": "^3.0.0", "ava": "^4.3.3", "body-parser": "^1.20.1",57 unmodified lines