Skip to content
Myr

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping check

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 3ded2aa · Browse files · 8 files+158 added−32 removed
This commit

State

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

Diff stats

8 files+158 added−32 removed

  • tests:+106 added−0 removed
  • other:+52 added−32 removed

8 files+158 added−32 removed

modified:source/core/Ky.ts+16 added-17 removed
96 unmodified lines
97 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);98 }99};100101// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's102// own internals rather than the option the caller set.101// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's own internals rather than the option the caller set.102const validateCallbackOptions = (options: Record<string, unknown>): void => {104 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress'] as const) {103 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {104 if (options[key] !== undefined && typeof options[key] !== 'function') {105 throw new TypeError(`The \`${key}\` option must be a function`);106 }107 }
501 unmodified lines
609 } as RequestInit);610 }611 }612614 if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {615 throw new TypeError('The `onUploadProgress` option must be a function');616 }617613 // `totalTimeout` starts when the request pipeline is created, so it also includes614 // Ky's internal scheduling and user hook time before the first fetch attempt.615 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;616 }
349 unmodified lines
966 if (didTimeOut) {967 this.#abortController?.abort();968969 if (result === timedOutOperation) {975 void operationPromise.then(value => {976 this.#cancelReturnedBody(value);977 }).catch(() => undefined);970 this.#releaseWhenSettled(operationPromise);971 } else {972 this.#cancelReturnedBody(result);973 }974
2 unmodified lines
977978 return result;979 } catch (error: unknown) {980 if (abortSignal?.aborted) {988 // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the989 // same way the timeout path below does for a value it never consumed.981 // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the same way the timeout path below does for a value it never consumed.982 if (operationPromise) {991 void operationPromise.then(value => {992 this.#cancelReturnedBody(value);993 }).catch(() => undefined);983 this.#releaseWhenSettled(operationPromise);984 }985986 abortSignal.throwIfAborted();987 }
147 unmodified lines
1135 this.#cancelBody(value.body ?? undefined);1136 }1137 }11381139 // Releases the body of a value whose owner already gave up on it, once the operation settles with something. The promise is abandoned on purpose, so its rejection is swallowed rather than surfacing as an unhandled rejection.1140 #releaseWhenSettled(operationPromise: Promise<unknown>): void {1141 void operationPromise.then(value => {1142 this.#cancelReturnedBody(value);1143 }).catch(() => undefined);1144 }11451146 #createManagedSignal(): AbortSignal {1147 return this.#userProvidedAbortSignal1148 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1149 : this.#abortController!.signal;
170 unmodified lines
1320 error: error instanceof Error ? error : new NonError(error),1321 retryCount: this.#retryCount + 1,1322 }), this.#userProvidedAbortSignal);1323 } catch (hookError) {1327 // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError`1328 // rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.1324 // A cancellation is part of the request lifecycle, so it reaches `beforeError` like every other abort rather than being hidden as a hook error below.1325 this.#throwIfAbortedByUser();13261327 // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError` rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.1328 if (isError(hookError) && hookError !== error) {1329 this.#beforeRetryHookErrors.add(hookError);1330 }1331
194 unmodified lines
modified:source/types/options.ts+2 added
183 unmodified lines
184 `retry.limit`, including numeric shorthand, must be a finite, non-negative integer.185186 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.187188 A hook can change `retry.limit` through `options`. Ky reads the limit again when each attempt starts. A `beforeRequest` or `beforeRetry` hook runs before the attempt starts, so it can lower or raise the limit. An `afterResponse` hook runs after the attempt started, so it can lower the limit, for example to stop retrying once a response says so. A higher limit set there only applies from the next attempt.189190 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.191192 When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as Unix timestamps, from 2001-09-09 onwards. A value below that is read as delay seconds, and a timestamp already in the past means the retry happens immediately. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.193
355 unmodified lines
modified:source/types/retry.ts+2 added
modified:source/utils/body.ts+27 added-12 removed
181 unmodified lines
182183 return response;184};185186// The body of a response the two wrappers below can pipe through, or `undefined` when they must leave it alone. A body an `afterResponse` hook already read, or locked with a reader, would otherwise fail with "The ReadableStream is locked" instead of the native "Body is unusable" error that names the actual mistake. A null body status cannot be given a replacement body at all, and there is nothing left to report once the body is gone.187const wrappableBody = (response: Response): ReadableStream<Uint8Array> | undefined => {188 const {body} = response;189 if (!body || response.bodyUsed || body.locked || nullBodyStatuses.has(response.status)) {190 return undefined;191 }192193 return body;194};195196export const limitResponseSize = (response: Response, request: Request, maxResponseSize: number): Response => {187 // A body a hook already read, or locked with a reader, cannot be piped through, and would otherwise fail with188 // "The ReadableStream is locked" instead of the native "Body is unusable" error that names the actual mistake.189 if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status) || maxResponseSize === Number.POSITIVE_INFINITY) {197 const originalBody = wrappableBody(response);198 if (!originalBody || maxResponseSize === Number.POSITIVE_INFINITY) {199 return response;200 }201202 let transferredBytes = 0;203 let sizeError: ResponseSizeError | undefined;195 const getOriginalSizeError = responseSizeErrors.get(response.body);196 const body = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({204 const getOriginalSizeError = responseSizeErrors.get(originalBody);205 const body = originalBody.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({206 transform(chunk, controller) {207 transferredBytes += chunk.byteLength;208 if (transferredBytes > maxResponseSize) {209 sizeError = new ResponseSizeError(request, maxResponseSize);
7 unmodified lines
217 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());218};219220export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {212 // A response with no body at all is not streamed. That covers a null body status and a `HEAD` request, which has213 // no body even on an ordinary status, so neither reports progress.214 // See `limitResponseSize`: there is nothing left to stream and nothing to report once a hook consumed the body.215 if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status)) {221 // A response with no wrappable body is not streamed, so it reports no progress. That covers a null body status, and a `HEAD` response in runtimes that give it no body.222 const originalBody = wrappableBody(response);223 if (!originalBody) {224 return response;225 }226227 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after decompression. Using it for a content-coded response would report a total below what actually arrives, so every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`. `identity` is a registered no-op coding (RFC 9110 §8.4.2), so it leaves the length valid.228 const contentEncoding = response.headers.get('content-encoding')?.toLowerCase();229 const isContentCoded = Boolean(contentEncoding) && contentEncoding !== 'identity';230 const totalBytes = isContentCoded ? 0 : Math.max(0, Number(response.headers.get('content-length')) || 0);223 const body = withProgress(response.body, totalBytes, onDownloadProgress);231 const body = withProgress(originalBody, totalBytes, onDownloadProgress);232233 return copyResponseMetadata(new Response(body, response), response);234};235236// eslint-disable-next-line @typescript-eslint/no-restricted-types237export const streamRequest = (request: Request, onUploadProgress: Options['onUploadProgress'], originalBody?: BodyInit | null) => {230 // A Request-like object from a hook is used as-is, because the `Request` constructor cannot copy it. It would stringify the object as a URL here, so progress reporting is skipped for it.231 if (!request.body || request.keepalive || request.mode === 'no-cors' || !(request instanceof globalThis.Request)) {238 // A Request-like object from a hook is used as-is, because the `Request` constructor cannot copy it. It would stringify the object as a URL here, so progress reporting is skipped for it. A body a hook already read, or locked with a reader, is left alone for the same reason as a response body: the runtime's own error names the actual mistake, where piping it would fail with "The ReadableStream is locked".239 if (240 !request.body241 || request.bodyUsed242 || request.body.locked243 || request.keepalive244 || request.mode === 'no-cors'245 || !(request instanceof globalThis.Request)246 ) {247 return request;248 }249250 // Use original body for size calculation since request.body is already a stream. A `ReadableStream` measures 0, so fall back to a `content-length` the caller declared. Browsers drop that header from a request, so this only helps outside browsers.
13 unmodified lines
modified:source/index.ts+1 added-1 removed
44 unmodified lines
4546 ky.create = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(newDefaults));47 ky.extend = (newDefaults?: Partial<Options> | ((parentDefaults: Partial<Options>) => Partial<Options>)) => {48 if (typeof newDefaults === 'function') {49 // Pass a deep copy so mutations inside the callback cannot leak into this instance's defaults. Deep, because options like `context` are merged shallowly, so a nested value would still point at the parent's object.49 // Pass a copy so mutations inside the callback cannot leak into this instance's defaults. Deep, because options like `context` are merged shallowly, so a nested value would still point at the parent's object. Non-plain values such as a `FormData` body are shared, the same way the `hooks.init` copies share them.50 newDefaults = newDefaults(validateAndMerge(cloneDeep(defaults)));51 }5253 return createInstance(validateAndMerge(defaults, newDefaults));
64 unmodified lines
modified:test/retry.ts+85 added
1144 unmodified lines
1145 t.is(response, 'ok');1146 t.is(requestCount, 1);1147});11481149// The limit is read again when each attempt starts, and `beforeRetry` runs before that, so it can raise the limit.1150test('allows beforeRetry hooks to raise the retry limit', async t => {1151 let requestCount = 0;11521153 await t.throwsAsync(1154 ky('https://example.com', {1155 async fetch() {1156 requestCount++;1157 return new Response(null, {status: 500});1158 },1159 retry: {1160 limit: 1,1161 delay: () => 0,1162 },1163 hooks: {1164 beforeRetry: [({options}) => {1165 options.retry.limit = 3;1166 }],1167 },1168 }).text(),1169 {1170 message: /status code 500/,1171 },1172 );11731174 t.is(requestCount, 4);1175});11761177test('uses the normalized retry limit when cloning request bodies', async t => {1178 let requestCount = 0;11791180 await t.throwsAsync(
3261 unmodified lines
4442for (const approval of [false, undefined]) {4443 test(`a late shouldRetry ${approval} decision preserves cancellation`, lateRetryDecision, approval, new Error('custom failure'));4444}44454446// A cancellation is part of the request lifecycle and reaches `beforeError` from every other stage. The `beforeRetry` hook races the user signal, so the abort arrived through the hook-error path, which exists to hide hook failures.4447test('a user abort during a beforeRetry hook reaches beforeError hooks as the abort reason', async t => {4448 const controller = new AbortController();4449 const reason = new Error('cancelled-during-beforeRetry');4450 const hookStarted = Promise.withResolvers<void>();4451 const neverReleased = Promise.withResolvers<void>();4452 const errors: Error[] = [];4453 let attempts = 0;44544455 const pending = ky('https://example.com', {4456 signal: controller.signal,4457 retry: {limit: 1, delay: () => 0},4458 async fetch() {4459 attempts++;4460 return new Response('boom', {status: 500});4461 },4462 hooks: {4463 beforeRetry: [async () => {4464 hookStarted.resolve();4465 await neverReleased.promise;4466 }],4467 beforeError: [({error}) => {4468 errors.push(error);4469 return error;4470 }],4471 },4472 }).text();44734474 await hookStarted.promise;4475 controller.abort(reason);44764477 await t.throwsAsync(pending, {is: reason});4478 t.is(attempts, 1);4479 t.deepEqual(errors, [reason]);4480});44814482test('cancellation interrupts a pending shouldRetry decision', async t => {4483 const controller = new AbortController();4484 const reason = new Error('cancelled');4485 const decisionStarted = Promise.withResolvers<void>();
512 unmodified lines
4998 t.deepEqual(validateAndMerge({list: [1, replaceOption(2), 3]}).list, [1, 2, 3]);4999 t.deepEqual(validateAndMerge({custom: {inner: replaceOption({a: 1})}}).custom, {inner: {a: 1}});5000});50015002// Search parameters merge per key and stringify every value on the way, so a wrapper that reached that step landed in the URL as `[object Object]`, while the very same value resolved correctly when it was the only layer.5003test('`replaceOption` resolves inside a search parameter record', async t => {5004 const fetchFunction = async (request: Request) => new Response(request.url);50055006 t.is(await ky('https://example.com', {5007 searchParams: {page: replaceOption('1') as never},5008 fetch: fetchFunction,5009 }).text(), 'https://example.com/?page=1');50105011 const extended = ky.create({fetch: fetchFunction, searchParams: {sort: 'name'}})5012 .extend({searchParams: {page: replaceOption('1') as never}});50135014 t.is(await extended('https://example.com').text(), 'https://example.com/?sort=name&page=1');50155016 // A wrapped value replaces the values its key inherited, while the other keys still merge.5017 const replaced = ky.create({fetch: fetchFunction, searchParams: {sort: 'name', page: '5'}})5018 .extend({searchParams: {page: replaceOption('1') as never}});50195020 t.is(await replaced('https://example.com').text(), 'https://example.com/?sort=name&page=1');5021});50225023test('`replaceOption` leaves untouched values identical', t => {5024 const json = {nested: {list: [1, 2]}};5025 const fetchFunction = () => new Response('ok');5026 const merged = validateAndMerge({json, fetch: fetchFunction}) as {json: unknown; fetch: unknown};
250 unmodified lines
modified:test/stream.ts+21 added
1610 unmodified lines
16111612 t.is(getRequestCount(), 0);1613 t.is(callbackCalls, 1);1614});16151616// The response wrappers already skip a body a hook read, so the native error names the mistake. The upload wrapper did not, and failed with "The ReadableStream is locked" instead.1617test('upload progress leaves a request body that a hook already read to the native error', async t => {1618 const run = async (onUploadProgress?: () => void) => t.throwsAsync(ky.post('https://example.com', {1619 body: 'x',1620 retry: 0,1621 onUploadProgress,1622 fetch: async input => new Response(await (input as Request).text()),1623 hooks: {1624 beforeRequest: [async ({request}) => {1625 await request.text();1626 }],1627 },1628 }).text());16291630 const withoutProgress = await run();1631 const withProgress = await run(() => undefined);16321633 t.truthy(withoutProgress?.message);1634 t.is(withProgress?.message, withoutProgress?.message);1635});
modified:readme.md+4 added-2 removed
278 unmodified lines
279`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.280281Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.282283A hook can change `retry.limit` through `options`. Ky reads the limit again when each attempt starts. A `beforeRequest` or `beforeRetry` hook runs before the attempt starts, so it can lower or raise the limit. An `afterResponse` hook runs after the attempt started, so it can lower the limit, for example to stop retrying once a response says so. A higher limit set there only applies from the next attempt.284285`413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.286287When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as Unix timestamps, from 2001-09-09 onwards. A value below that is read as delay seconds, and a timestamp already in the past means the retry happens immediately. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.288
3 unmodified lines
292To clamp the delay, set `backoffLimit` to 1000, for example.293A delay from a retry timing header is not subject to this limit; use `maxRetryAfter` to bound it.294By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.295294The `delay` option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at `1`, and must return the delay in milliseconds.296The `delay` option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at `1`, and must return the delay in milliseconds. A value that is not a non-negative number or `Infinity` throws a `TypeError` rather than collapsing to a 1ms retry, and the error that was being retried is kept as its `cause` so `beforeError` can still reach it.297298The `jitter` option adds random jitter to retry delays to prevent thundering herd problems. When many clients retry simultaneously (e.g., after hitting a rate limit), they can overwhelm the server again. Jitter adds randomness to break this synchronization. Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay. Alternatively, pass a function to implement custom jitter strategies.299300**Note:** Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.
173 unmodified lines
474Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`475476Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.477476Each hook must be an array of functions. A single function, a string, or any other value throws a `TypeError` rather than being silently dropped, and a nullish value means absent, so it clears the hooks it would have replaced.478Each hook must be an array of functions. A single function, a string, or any other value, `null` included, throws a `TypeError` rather than being silently dropped. `undefined` means absent, so it clears the hooks it would have replaced.479480###### hooks.init481482Type: `Function[]`\
1447 unmodified lines