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`.
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
Provenance
- Commit
e1b088e- Tree
d1b461e- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
ee3dec1
4 files changed+390 added−9 removed
modified:source/core/Ky.ts+13 added-5 removed
985 unmodified lines986 throw new TimeoutError(this.request);987 }988 989 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 lines1093 // 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 }1099 1100 // 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 }1108 1109 for (const hook of this.#options.hooks.beforeRetry) {1110 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOutOperation;20 unmodified lines1131 1132 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 }1138 1139 if (isResponseInstance(hookResult)) {102 unmodified lines1242 this.#cachedNormalizedOptions = undefined;1243 this.request = request;1244 }1245 1246+ // 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+ }1251+1252+ return new globalThis.Request(request, {signal: this.#options.signal});1253+ }1254+1255 #getResponseRequest(response: Response): Request {1256 return this.#responseRequests.get(response) ?? this.request;1257 }1258 13 unmodified linesmodified:source/types/hooks.ts+2 added-2 removed
118 unmodified lines119 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.120 121 The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.122 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.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.124 125 Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.126 127 @example40 unmodified lines168 169 /**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.171 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. **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.173 174 **Warning:** Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.175 176 The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.194 unmodified linesmodified:test/hooks.ts+373 added
176 unmodified lines177 178 t.is(responseText, 'yes');179 });180 181+test('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+ });186+187+ 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();201+202+ t.is(text, 'retried');203+ t.is(attempts, 2);204+});205+206+test('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+ });211+212+ 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+ }220+221+ return attempts === 2 ? neverSettlingPromise : new Response('retried');222+ },223+ hooks: {224+ beforeRetry: [225+ ({request, retryCount}) => retryCount === 1 ? createRequestLike(request) : undefined,226+ ],227+ },228+ }).text();229+230+ t.is(text, 'retried');231+ t.is(attempts, 3);232+});233+234 test('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 lines2769 t.is(result, 'success');2770 t.is(requestCount, 2); // Initial request + 1 retry2771 });2772 2773+test('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('/', () => {});2777+2778+ 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+ });2787+2788+ setTimeout(() => {2789+ abortController.abort();2790+ }, 50);2791+2792+ const error = (await t.throwsAsync(responsePromise))!;2793+ t.is(error.name, 'AbortError');2794+});2795+2796+test('beforeRequest hook returning a new Request still aborts the fetch on timeout', async t => {2797+ let didAbort = false;2798+2799+ 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+ });2817+2818+ t.true(didAbort);2819+});2820+2821+test('beforeRequest hook returning a new Request still aborts a never-ending body read on timeout', async t => {2822+ let didAbort = false;2823+2824+ 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});2835+2836+ const body = new ReadableStream<Uint8Array>({2837+ start(controller) {2838+ controller.enqueue(new TextEncoder().encode('partial'));2839+ },2840+ });2841+2842+ return new Response(body, {status: 200});2843+ },2844+ }).text(), {2845+ instanceOf: TimeoutError,2846+ });2847+2848+ t.true(didAbort);2849+});2850+2851+test('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('/', () => {});2855+2856+ 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+ });2864+2865+ setTimeout(() => {2866+ abortController.abort();2867+ }, 50);2868+2869+ const error = (await t.throwsAsync(responsePromise))!;2870+ t.is(error.name, 'AbortError');2871+});2872+2873+test('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('/', () => {});2877+2878+ 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+ });2888+2889+ const responsePromise = instance(`${server.url}/original`, {signal: requestController.signal});2890+2891+ setTimeout(() => {2892+ instanceController.abort();2893+ }, 50);2894+2895+ const error = (await t.throwsAsync(responsePromise))!;2896+ t.is(error.name, 'AbortError');2897+});2898+2899+test('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+ });2904+2905+ const abortController = new AbortController();2906+ abortController.abort();2907+2908+ const result = await ky(`${server.url}/original`, {2909+ hooks: {2910+ beforeRequest: [2911+ () => new Request(server.url, {signal: abortController.signal}),2912+ ],2913+ },2914+ }).text();2915+2916+ t.is(result, 'success');2917+});2918+2919+test('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+ });2927+2928+ 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();2939+2940+ t.deepEqual(result, {header: 'yes', body: 'hello'});2941+});2942+2943+test('beforeRequest hook returning a new Request with a body retries with that body', async t => {2944+ let requestCount = 0;2945+ const bodies: unknown[] = [];2946+2947+ 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+ });2957+2958+ 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();2970+2971+ t.is(result, 'success');2972+ t.is(requestCount, 2);2973+ t.deepEqual(bodies, ['hello', 'hello']);2974+});2975+2976+test('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+ });2981+2982+ 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();2993+2994+ t.deepEqual(result, {foo: true});2995+});2996+2997+test('beforeRetry hook returning a new Request still honors the user abort signal', async t => {2998+ let requestCount = 0;2999+3000+ 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+ });3011+3012+ 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+ });3021+3022+ const error = (await t.throwsAsync(responsePromise))!;3023+ t.is(error.name, 'AbortError');3024+ t.is(requestCount, 2);3025+});3026+3027+test('beforeRetry hook returning a new Request still aborts the retried fetch on timeout', async t => {3028+ let requestCount = 0;3029+ let didAbort = false;3030+3031+ 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+ }3044+3045+ (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+ });3054+3055+ t.is(requestCount, 2);3056+ t.true(didAbort);3057+});3058+3059+test('beforeRetry hook returning a new Request with a body sends that body', async t => {3060+ let requestCount = 0;3061+ const bodies: unknown[] = [];3062+3063+ 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+ });3073+3074+ 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();3088+3089+ t.is(result, 'success');3090+ t.deepEqual(bodies, ['first', 'second']);3091+});3092+3093 test('beforeRetry hook can return Response to skip retry', async t => {3094 let requestCount = 0;3095 3096 const server = await createHttpTestServer(t);2873 unmodified linesmodified:readme.md+2 added-2 removed
470 unmodified lines471 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.472 473 The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.474 475-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.475+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.476 477 Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.478 479 ```js38 unmodified lines518 Default: `[]`519 520 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.521 522-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.522+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.523 524 > [!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