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
Provenance
- Commit
55599c8- Tree
cb13bd4- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
3ded2aa
8 files changed+158 added−32 removed
modified:source/core/Ky.ts+16 added-17 removed
96 unmodified lines97 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);98 }99 };100 101-// 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.102 const 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 lines609 } as RequestInit);610 }611 }612 614- if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {615- throw new TypeError('The `onUploadProgress` option must be a function');616- }617-613 // `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 lines966 if (didTimeOut) {967 this.#abortController?.abort();968 969 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 lines977 978 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 }985 986 abortSignal.throwIfAborted();987 }147 unmodified lines1135 this.#cancelBody(value.body ?? undefined);1136 }1137 }1138 1139+ // 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+ }1145+1146 #createManagedSignal(): AbortSignal {1147 return this.#userProvidedAbortSignal1148 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1149 : this.#abortController!.signal;170 unmodified lines1320 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();1326+1327+ // 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 linesmodified:source/types/options.ts+2 added
183 unmodified lines184 `retry.limit`, including numeric shorthand, must be a finite, non-negative integer.185 186 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.187 188+ 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.189+190 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.191 192 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 linesmodified:source/types/retry.ts+2 added
75 unmodified lines76777879808182838485104 unmodified linesExpand all75 unmodified lines
/** A function to calculate the delay in milliseconds between retries given `attemptCount` (starts from 1).
Must return a non-negative number or `Infinity`; anything else 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.
@default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000 */ delay?: ((attemptCount: number) => number) | undefined;
104 unmodified linesExpand allmodified:source/utils/body.ts+27 added-12 removed
181 unmodified lines182 183 return response;184 };185 186+// 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.187+const 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+ }192+193+ return body;194+};195+196 export 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 }201 202 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 lines217 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());218 };219 220 export 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 }226 227 // `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);232 233 return copyResponseMetadata(new Response(body, response), response);234 };235 236 // eslint-disable-next-line @typescript-eslint/no-restricted-types237 export 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 }249 250 // 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 linesmodified:source/index.ts+1 added-1 removed
44 unmodified lines45 46 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 }52 53 return createInstance(validateAndMerge(defaults, newDefaults));64 unmodified linesmodified:test/retry.ts+85 added
1144 unmodified lines1145 t.is(response, 'ok');1146 t.is(requestCount, 1);1147 });1148 1149+// The limit is read again when each attempt starts, and `beforeRetry` runs before that, so it can raise the limit.1150+test('allows beforeRetry hooks to raise the retry limit', async t => {1151+ let requestCount = 0;1152+1153+ 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+ );1173+1174+ t.is(requestCount, 4);1175+});1176+1177 test('uses the normalized retry limit when cloning request bodies', async t => {1178 let requestCount = 0;1179 1180 await t.throwsAsync(3261 unmodified lines4442 for (const approval of [false, undefined]) {4443 test(`a late shouldRetry ${approval} decision preserves cancellation`, lateRetryDecision, approval, new Error('custom failure'));4444 }4445 4446+// 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.4447+test('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;4454+4455+ 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();4473+4474+ await hookStarted.promise;4475+ controller.abort(reason);4476+4477+ await t.throwsAsync(pending, {is: reason});4478+ t.is(attempts, 1);4479+ t.deepEqual(errors, [reason]);4480+});4481+4482 test('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 lines4998 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 });5001 5002+// 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.5003+test('`replaceOption` resolves inside a search parameter record', async t => {5004+ const fetchFunction = async (request: Request) => new Response(request.url);5005+5006+ t.is(await ky('https://example.com', {5007+ searchParams: {page: replaceOption('1') as never},5008+ fetch: fetchFunction,5009+ }).text(), 'https://example.com/?page=1');5010+5011+ const extended = ky.create({fetch: fetchFunction, searchParams: {sort: 'name'}})5012+ .extend({searchParams: {page: replaceOption('1') as never}});5013+5014+ t.is(await extended('https://example.com').text(), 'https://example.com/?sort=name&page=1');5015+5016+ // 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}});5019+5020+ t.is(await replaced('https://example.com').text(), 'https://example.com/?sort=name&page=1');5021+});5022+5023 test('`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 linesmodified:test/stream.ts+21 added
1610 unmodified lines1611 1612 t.is(getRequestCount(), 0);1613 t.is(callbackCalls, 1);1614 });1615+1616+// 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.1617+test('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());1629+1630+ const withoutProgress = await run();1631+ const withProgress = await run(() => undefined);1632+1633+ t.truthy(withoutProgress?.message);1634+ t.is(withProgress?.message, withoutProgress?.message);1635+});modified:readme.md+4 added-2 removed
278 unmodified lines279 `retry.limit`, including numeric shorthand, must be a finite, non-negative integer.280 281 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.282 283+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.284+285 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.286 287 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.288 3 unmodified lines292 To clamp the delay, set `backoffLimit` to 1000, for example.293 A delay from a retry timing header is not subject to this limit; use `maxRetryAfter` to bound it.294 By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.295 294-The `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.296+The `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.297 298 The `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.299 300 **Note:** Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.173 unmodified lines474 Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`475 476 Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.477 476-Each 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.478+Each 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.479 480 ###### hooks.init481 482 Type: `Function[]`\1447 unmodified lines