Skip to content
Myr

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooks

Before adoption: this commit came in with the history the project adopted, so no landing records it.

A fresh `Request` returned from these hooks carried its own signal, so Ky's managed signal never reached the fetch. User `signal` aborts left the request pending forever, and per-attempt, body-read, and total timeouts threw `TimeoutError` without cancelling the in-flight fetch. The returned request now gets the managed signal re-attached, the same way `ky.retry({request})` already did. Only `Request` instances get the managed signal; `Request`-like objects are used as-is since the `Request` constructor cannot copy them, so resetting the aborted signal before a retry reuses the same helper instead of rebuilding the request and throwing a `TypeError`.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent ee3dec1 · Browse files · 4 files+390 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+390 added−9 removed

  • tests:+373 added−0 removed
  • other:+17 added−9 removed

4 files+390 added−9 removed

modified:source/core/Ky.ts+13 added-5 removed
985 unmodified lines
986 throw new TimeoutError(this.request);987 }988989 if (isRequestInstance(result)) {990 this.#assignRequest(result);990 this.#assignRequest(this.#withManagedSignal(result));991 } else if (isResponseInstance(result)) {992 return result;993 }994 }
98 unmodified lines
1093 // Reset abortController if it was aborted (happens on timeout retry) so hooks and the retried request get a fresh signal1094 if (this.#abortController?.signal.aborted) {1095 this.#abortController = new globalThis.AbortController();1096 this.#options.signal = this.#createManagedSignal();1097 this.#assignRequest(new globalThis.Request(this.request, {signal: this.#options.signal}));1097 this.#assignRequest(this.#withManagedSignal(this.request));1098 }10991100 // Apply custom request from forced retry before beforeRetry hooks1101 // Ensure the custom request has the correct managed signal for timeouts and user aborts1102 if (error instanceof ForceRetryError && error.customRequest) {1103 const customRequest = new globalThis.Request(error.customRequest, this.#options.signal ? {signal: this.#options.signal} : undefined);1103 // Replacement Requests are authoritative by design. Do not rewrite headers here,1104 // even for cross-origin retries. Callers using `ky.retry({request})` explicitly1105 // opted into the exact Request they constructed.1107 this.#assignRequest(customRequest);1106 this.#assignRequest(this.#withManagedSignal(error.customRequest));1107 }11081109 for (const hook of this.#options.hooks.beforeRetry) {1110 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOutOperation;
20 unmodified lines
11311132 if (isRequestInstance(hookResult)) {1133 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`1134 // is used as-is rather than being sanitized or otherwise rewritten by Ky.1136 this.#assignRequest(hookResult);1135 this.#assignRequest(this.#withManagedSignal(hookResult));1136 break;1137 }11381139 if (isResponseInstance(hookResult)) {
102 unmodified lines
1242 this.#cachedNormalizedOptions = undefined;1243 this.request = request;1244 }12451246 // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them.1247 #withManagedSignal(request: Request): Request {1248 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1249 return request;1250 }12511252 return new globalThis.Request(request, {signal: this.#options.signal});1253 }12541255 #getResponseRequest(response: Response): Request {1256 return this.#responseRequests.get(response) ?? this.request;1257 }1258
13 unmodified lines
modified:source/types/hooks.ts+2 added-2 removed
118 unmodified lines
119 This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.120121 The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.122123 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc.123 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work.124125 Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.126127 @example
40 unmodified lines
168169 /**170 This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and retry count. You could, for example, modify `request.headers` here.171172 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.172 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.173174 **Warning:** Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.175176 The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.
194 unmodified lines
modified:test/hooks.ts+373 added
176 unmodified lines
177178 t.is(responseText, 'yes');179});180181test('beforeRequest hook returning a Request-like object still retries after a timeout', async t => {182 let attempts = 0;183 const neverSettlingPromise = new Promise<never>(() => {184 void 0;185 });186187 const text = await ky(requestFixtureUrl, {188 timeout: 40,189 retry: {limit: 1, retryOnTimeout: true, delay: () => 1},190 async fetch(request) {191 attempts++;192 t.is((request as Request).headers.get('x-tagged-request'), 'yes');193 return attempts === 1 ? neverSettlingPromise : new Response('retried');194 },195 hooks: {196 beforeRequest: [197 ({request}) => createRequestLike(withHeader(request, 'x-tagged-request', 'yes')),198 ],199 },200 }).text();201202 t.is(text, 'retried');203 t.is(attempts, 2);204});205206test('beforeRetry hook returning a Request-like object still retries after a later timeout', async t => {207 let attempts = 0;208 const neverSettlingPromise = new Promise<never>(() => {209 void 0;210 });211212 const text = await ky(requestFixtureUrl, {213 timeout: 40,214 retry: {limit: 2, retryOnTimeout: true, delay: () => 1},215 async fetch() {216 attempts++;217 if (attempts === 1) {218 throw new TypeError('fetch failed');219 }220221 return attempts === 2 ? neverSettlingPromise : new Response('retried');222 },223 hooks: {224 beforeRetry: [225 ({request, retryCount}) => retryCount === 1 ? createRequestLike(request) : undefined,226 ],227 },228 }).text();229230 t.is(text, 'retried');231 t.is(attempts, 3);232});233234test('beforeRequest hook allows modifications', async t => {235 const server = await createHttpTestServer(t);236 server.post('/', async (request, response) => {237 response.json(request.body);
2531 unmodified lines
2769 t.is(result, 'success');2770 t.is(requestCount, 2); // Initial request + 1 retry2771});27722773test('beforeRequest hook returning a new Request still honors the user abort signal', async t => {2774 const server = await createHttpTestServer(t);2775 // eslint-disable-next-line @typescript-eslint/no-empty-function2776 server.get('/', () => {});27772778 const abortController = new AbortController();2779 const responsePromise = ky(`${server.url}/original`, {2780 signal: abortController.signal,2781 hooks: {2782 beforeRequest: [2783 () => new Request(server.url),2784 ],2785 },2786 });27872788 setTimeout(() => {2789 abortController.abort();2790 }, 50);27912792 const error = (await t.throwsAsync(responsePromise))!;2793 t.is(error.name, 'AbortError');2794});27952796test('beforeRequest hook returning a new Request still aborts the fetch on timeout', async t => {2797 let didAbort = false;27982799 await t.throwsAsync(ky('https://example.com', {2800 timeout: 50,2801 retry: 0,2802 hooks: {2803 beforeRequest: [2804 () => new Request('https://example.com/other'),2805 ],2806 },2807 async fetch(request) {2808 (request as Request).signal.addEventListener('abort', () => {2809 didAbort = true;2810 }, {once: true});2811 await delay(200);2812 return new Response('late');2813 },2814 }), {2815 instanceOf: TimeoutError,2816 });28172818 t.true(didAbort);2819});28202821test('beforeRequest hook returning a new Request still aborts a never-ending body read on timeout', async t => {2822 let didAbort = false;28232824 await t.throwsAsync(ky('https://example.com', {2825 timeout: 50,2826 hooks: {2827 beforeRequest: [2828 () => new Request('https://example.com/other'),2829 ],2830 },2831 async fetch(request) {2832 (request as Request).signal.addEventListener('abort', () => {2833 didAbort = true;2834 }, {once: true});28352836 const body = new ReadableStream<Uint8Array>({2837 start(controller) {2838 controller.enqueue(new TextEncoder().encode('partial'));2839 },2840 });28412842 return new Response(body, {status: 200});2843 },2844 }).text(), {2845 instanceOf: TimeoutError,2846 });28472848 t.true(didAbort);2849});28502851test('beforeRequest hook returning a new Request keeps the signal from a Request input', async t => {2852 const server = await createHttpTestServer(t);2853 // eslint-disable-next-line @typescript-eslint/no-empty-function2854 server.get('/', () => {});28552856 const abortController = new AbortController();2857 const responsePromise = ky(new Request(`${server.url}/original`, {signal: abortController.signal}), {2858 hooks: {2859 beforeRequest: [2860 () => new Request(server.url),2861 ],2862 },2863 });28642865 setTimeout(() => {2866 abortController.abort();2867 }, 50);28682869 const error = (await t.throwsAsync(responsePromise))!;2870 t.is(error.name, 'AbortError');2871});28722873test('beforeRequest hook returning a new Request keeps signals merged from an extended instance', async t => {2874 const server = await createHttpTestServer(t);2875 // eslint-disable-next-line @typescript-eslint/no-empty-function2876 server.get('/', () => {});28772878 const instanceController = new AbortController();2879 const requestController = new AbortController();2880 const instance = ky.create({2881 signal: instanceController.signal,2882 hooks: {2883 beforeRequest: [2884 () => new Request(server.url),2885 ],2886 },2887 });28882889 const responsePromise = instance(`${server.url}/original`, {signal: requestController.signal});28902891 setTimeout(() => {2892 instanceController.abort();2893 }, 50);28942895 const error = (await t.throwsAsync(responsePromise))!;2896 t.is(error.name, 'AbortError');2897});28982899test('beforeRequest hook returning a Request with an aborted signal still sends the request', async t => {2900 const server = await createHttpTestServer(t);2901 server.get('/', (_request, response) => {2902 response.end('success');2903 });29042905 const abortController = new AbortController();2906 abortController.abort();29072908 const result = await ky(`${server.url}/original`, {2909 hooks: {2910 beforeRequest: [2911 () => new Request(server.url, {signal: abortController.signal}),2912 ],2913 },2914 }).text();29152916 t.is(result, 'success');2917});29182919test('beforeRequest hook returning a new Request keeps its URL, method, headers, and body', async t => {2920 const server = await createHttpTestServer(t);2921 server.put('/replaced', async (request, response) => {2922 response.json({2923 header: request.headers['x-replaced'],2924 body: request.body,2925 });2926 });29272928 const result = await ky.get(`${server.url}/original`, {2929 hooks: {2930 beforeRequest: [2931 () => new Request(`${server.url}/replaced`, {2932 method: 'PUT',2933 headers: {'x-replaced': 'yes', 'content-type': 'text/plain'},2934 body: 'hello',2935 }),2936 ],2937 },2938 }).json();29392940 t.deepEqual(result, {header: 'yes', body: 'hello'});2941});29422943test('beforeRequest hook returning a new Request with a body retries with that body', async t => {2944 let requestCount = 0;2945 const bodies: unknown[] = [];29462947 const server = await createHttpTestServer(t);2948 server.post('/', async (request, response) => {2949 requestCount++;2950 bodies.push(request.body);2951 if (requestCount === 1) {2952 response.sendStatus(500);2953 } else {2954 response.end('success');2955 }2956 });29572958 const result = await ky.post(`${server.url}/original`, {2959 retry: {limit: 1, methods: ['post'], delay: () => 0},2960 hooks: {2961 beforeRequest: [2962 () => new Request(server.url, {2963 method: 'POST',2964 headers: {'content-type': 'text/plain'},2965 body: 'hello',2966 }),2967 ],2968 },2969 }).text();29702971 t.is(result, 'success');2972 t.is(requestCount, 2);2973 t.deepEqual(bodies, ['hello', 'hello']);2974});29752976test('beforeRequest hook returning the same request keeps the JSON body', async t => {2977 const server = await createHttpTestServer(t);2978 server.post('/', async (request, response) => {2979 response.json(request.body);2980 });29812982 const result = await ky.post(server.url, {2983 json: {foo: true},2984 hooks: {2985 beforeRequest: [2986 ({request}) => {2987 request.headers.set('x-touched', 'yes');2988 return request;2989 },2990 ],2991 },2992 }).json();29932994 t.deepEqual(result, {foo: true});2995});29962997test('beforeRetry hook returning a new Request still honors the user abort signal', async t => {2998 let requestCount = 0;29993000 const abortController = new AbortController();3001 const server = await createHttpTestServer(t);3002 server.get('/', (_request, response) => {3003 requestCount++;3004 if (requestCount === 1) {3005 response.sendStatus(500);3006 } else {3007 // Abort only once the retried request is in flight, so the abort must reach the hook-returned request.3008 abortController.abort();3009 }3010 });30113012 const responsePromise = ky(server.url, {3013 signal: abortController.signal,3014 retry: {limit: 1, delay: () => 0},3015 hooks: {3016 beforeRetry: [3017 () => new Request(server.url),3018 ],3019 },3020 });30213022 const error = (await t.throwsAsync(responsePromise))!;3023 t.is(error.name, 'AbortError');3024 t.is(requestCount, 2);3025});30263027test('beforeRetry hook returning a new Request still aborts the retried fetch on timeout', async t => {3028 let requestCount = 0;3029 let didAbort = false;30303031 await t.throwsAsync(ky('https://example.com', {3032 timeout: 50,3033 retry: {limit: 1, delay: () => 0},3034 hooks: {3035 beforeRetry: [3036 () => new Request('https://example.com/other'),3037 ],3038 },3039 async fetch(request) {3040 requestCount++;3041 if (requestCount === 1) {3042 return new Response('error', {status: 500});3043 }30443045 (request as Request).signal.addEventListener('abort', () => {3046 didAbort = true;3047 }, {once: true});3048 await delay(200);3049 return new Response('late');3050 },3051 }), {3052 instanceOf: TimeoutError,3053 });30543055 t.is(requestCount, 2);3056 t.true(didAbort);3057});30583059test('beforeRetry hook returning a new Request with a body sends that body', async t => {3060 let requestCount = 0;3061 const bodies: unknown[] = [];30623063 const server = await createHttpTestServer(t);3064 server.post('/', async (request, response) => {3065 requestCount++;3066 bodies.push(request.body);3067 if (requestCount === 1) {3068 response.sendStatus(500);3069 } else {3070 response.end('success');3071 }3072 });30733074 const result = await ky.post(server.url, {3075 body: 'first',3076 headers: {'content-type': 'text/plain'},3077 retry: {limit: 1, methods: ['post'], delay: () => 0},3078 hooks: {3079 beforeRetry: [3080 () => new Request(server.url, {3081 method: 'POST',3082 headers: {'content-type': 'text/plain'},3083 body: 'second',3084 }),3085 ],3086 },3087 }).text();30883089 t.is(result, 'success');3090 t.deepEqual(bodies, ['first', 'second']);3091});30923093test('beforeRetry hook can return Response to skip retry', async t => {3094 let requestCount = 0;30953096 const server = await createHttpTestServer(t);
2873 unmodified lines
modified:readme.md+2 added-2 removed
470 unmodified lines
471This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.472473The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.474475The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc.475The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work.476477Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.478479```js
38 unmodified lines
518Default: `[]`519520This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and retry count. You could, for example, modify `request.headers` here.521522The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.522The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.523524> [!WARNING]525> Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.526
1330 unmodified lines