Skip to content
Myr

Release the body when a predicate throws, an abort wins, or a response cannot be decorated

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 6e27594 · Browse files · 7 files+246 added−40 removed
This commit

State

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

Diff stats

7 files+246 added−40 removed

  • tests:+180 added−18 removed
  • other:+66 added−22 removed

7 files+246 added−40 removed

modified:source/core/Ky.ts+40 added-14 removed
320 unmodified lines
321322 const currentResponse: Response = response;323324 // Opaque responses (`response.type === 'opaque'`) from `no-cors` requests always have `status: 0` and `ok: false`, but this is not a failure - the actual status is hidden by the browser.325 if (!currentResponse.ok && currentResponse.type !== 'opaque' && (326 typeof ky.#options.throwHttpErrors === 'function'327 ? ky.#options.throwHttpErrors(currentResponse.status)328 : ky.#options.throwHttpErrors329 )) {325 if (!currentResponse.ok && currentResponse.type !== 'opaque' && ky.#shouldThrowHttpErrors(currentResponse)) {326 // `request` must reflect the request that actually failed, but `options` stays as Ky's327 // normalized options snapshot. Replacement `Request` instances do not preserve the328 // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.329 const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());
450 unmodified lines
780781 this.#decoratedResponses.add(response);782 const request = this.#getResponseRequest(response);783784 try {788 response.json = async () => {789 const text = await response.text();790 return this.#options.parseJson!(text, {request, response});791 };785 response.json = async () => {786 const text = await response.text();787 return this.#options.parseJson!(text, {request, response});788 };789793 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.794 const nativeClone = response.clone.bind(response);795 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));790 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.791 const nativeClone = response.clone.bind(response);792 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));793 } catch (error: unknown) {794 // A frozen response cannot be decorated, so the caller never receives it and nothing else can release its795 // body. Report the real problem and let go of the connection.796 this.#cancelResponseBody(response);797 throw error;798 }799800 return response;801 }802
185 unmodified lines
988 }989990 let timeoutId: ReturnType<typeof setTimeout> | undefined;991 let abortListener: (() => void) | undefined;992 let operationPromise: Promise<T> | undefined;993 try {994 const abortPromise = new Promise<never>((_resolve, reject) => {995 if (!abortSignal) {996 return;
9 unmodified lines
1006 if (abortSignal.aborted) {1007 abortListener();1008 }1009 });1006 const operationPromise = operation();1010 operationPromise = operation();10111012 if (remainingTotal === undefined) {1013 return await Promise.race([operationPromise, abortPromise]);1014 }
21 unmodified lines
1036 }10371038 return result;1039 } catch (error: unknown) {1036 abortSignal?.throwIfAborted();1040 if (abortSignal?.aborted) {1041 // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the1042 // same way the timeout path below does for a value it never consumed.1043 if (operationPromise) {1044 void operationPromise.then(value => {1045 this.#cancelReturnedBody(value);1046 }).catch(() => undefined);1047 }10481049 abortSignal.throwIfAborted();1050 }10511052 const remainingAfterOperation = this.#getRemainingTotalTimeout();1053 if (remainingAfterOperation !== undefined && remainingAfterOperation <= 0) {1054 this.#abortController?.abort();1055 return timedOutOperation;
148 unmodified lines
1204 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1205 : this.#abortController!.signal;1206 }12071208 // A `throwHttpErrors` predicate that throws used to escape from the `if` condition, before the body was read or1209 // released, leaving the caller with an error and no handle on the response to release it with.1210 #shouldThrowHttpErrors(response: Response): boolean {1211 const {throwHttpErrors} = this.#options;1212 try {1213 return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1214 } catch (error: unknown) {1215 this.#cancelResponseBody(response);1216 throw error;1217 }1218 }12191220 // `#fetch()` replaces `this.request` with the clone it prepares for a possible retry, so anything reporting the1221 // request that produced a response or failed has to use the one that was actually sent.1222 get #sentRequest(): Request {1223 return this.#originalRequest ?? this.request;
359 unmodified lines
modified:source/utils/merge.ts+24 added-8 removed
1 unmodified line
2import type {Hooks, NormalizedHooks} from '../types/hooks.js';3import {supportsAbortSignal} from '../core/constants.js';4import {isObject} from './is.js';56// Registered globally so that a wrapper created by a second copy of Ky, which happens with a duplicated dependency, is still recognised.6const replaceSymbol: unique symbol = Symbol('replaceOption');7const replaceSymbol: unique symbol = Symbol.for('ky.replaceOption');89type ReplaceMarked<T> = {10 [replaceSymbol]: true;11 value: T;12 toJSON: () => T;13};1415type ReplaceState<T> = {16 isReplace: boolean;
13 unmodified lines
3031/**32Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.3334Inside the `json` option, which holds your own data, use it only where it replaces an inherited value. Ky does not look for it anywhere else there. The `context` option is merged shallowly, so only a wrapper around the whole `context` is supported.3536By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.3738@example39```
10 unmodified lines
50// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]51```52*/53export const replaceOption = <T>(value: T): T => {50 const markedValue: ReplaceMarked<T> = {[replaceSymbol]: true, value};54 const markedValue: ReplaceMarked<T> = {55 [replaceSymbol]: true,56 value,57 // The leftover pass below skips `json`, so a wrapper there with nothing to replace is unwrapped when the body is serialized.58 toJSON: () => value,59 };60 return markedValue as unknown as T;61};6263export const validateAndMerge = (...sources: Array<Partial<Options> | undefined>): Partial<Options> => {
193 unmodified lines
257258 return resolved;259};260252// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a253// merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the254// leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its255// identity. `seen` only holds the values on the current path, so a cyclic option cannot recurse forever while a256// value shared by two branches is still resolved in both.261// `json` and `context` are user data, which can be large, so they are not walked on every request.262const userDataOptions = new Set(['json', 'context']);263264// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its identity. `seen` only holds the values on the current path, so a cyclic option cannot recurse forever while a value shared by two branches is still resolved in both.265const resolveReplaceMarkers = (value: unknown, seen: Set<Record<string, unknown> | unknown[]>): unknown => {266 if (!isMergeable(value) || seen.has(value)) {267 return value;268 }
196 unmodified lines
465 returnValue.signal = signals.at(-1);466 }467 }468461 return isRoot ? resolveReplaceMarkers(returnValue, new Set()) as T : returnValue;469 if (isRoot) {470 for (const [key, value] of Object.entries(returnValue)) {471 if (!userDataOptions.has(key)) {472 returnValue[key] = resolveReplaceMarkers(value, new Set());473 }474 }475 }476477 return returnValue;478};479480export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T =>481 deepMergeInternal<T>(true, ...sources);
modified:test/hooks.ts+50 added-2 removed
7127 unmodified lines
7128 t.is(hookRequests.length, 1);7129 t.is(hookRequests[0], sent);7130});71317132// The cleanup in the request pipeline cancelled the current request body even when fetch was never called, so a7133// caller-owned upload stream was destroyed by a configuration error or a hook that threw before the request started.7132// The `totalTimeout` path releases the value a hook eventually returns once the timer wins, but the abort path did not, so a hook that lost the race leaked the body of the Response or Request it was about to return.7133for (const [label, makeHookResult] of [7134 ['Response', (stream: ReadableStream<Uint8Array>) => new Response(stream)],7135 ['Request', (stream: ReadableStream<Uint8Array>) => new Request('https://example.com', {7136 method: 'POST',7137 body: stream,7138 // @ts-expect-error - Types are outdated.7139 duplex: 'half',7140 })],7141] as Array<[string, (stream: ReadableStream<Uint8Array>) => unknown]>) {7142 test(`an abort that beats a hook releases the ${label} it was about to return`, async t => {7143 const controller = new AbortController();7144 let cancelled = false;7145 let releaseHook: () => void;7146 const gate = new Promise<void>(resolve => {7147 releaseHook = resolve;7148 });71497150 const promise = ky('https://example.com', {7151 signal: controller.signal,7152 retry: 0,7153 fetch: async () => new Response('ok'),7154 hooks: {7155 // The hook only returns its value once the request has already been rejected, so the race is decided by the abort rather than by how two timers happen to interleave.7156 beforeRequest: [async () => {7157 await gate;71587159 // Nothing has read this body, so only a cancel releases it.7160 return makeHookResult(new ReadableStream<Uint8Array>({7161 cancel() {7162 cancelled = true;7163 },7164 }));7165 }],7166 },7167 });71687169 const settled = promise.catch(() => 'rejected' as const);7170 setTimeout(() => {7171 controller.abort();7172 }, 0);71737174 t.is(await settled, 'rejected');7175 releaseHook!();7176 await delay(50);7177 t.true(cancelled, `the ${label} body must be released`);7178 });7179}71807181// The cleanup in the request pipeline cancelled the current request body even when fetch was never called, so a caller-owned upload stream was destroyed by a configuration error or a hook that threw before the request started.7182test('a request that never started leaves the caller-owned body alone', async t => {7183 const failedFetches: boolean[] = [];7184 const cancelledBodies: boolean[] = [];7185
254 unmodified lines
modified:test/http-error.ts+47 added
755 unmodified lines
756 }), {instanceOf: TimeoutError}))!;757758 t.is(error.request, sentRequest);759});760761// A `throwHttpErrors` predicate ran inside the `if` condition, so a throw from it escaped before the body was read762// or released, leaving the caller with an error and no handle on the response to release it with.763test('a `throwHttpErrors` predicate that throws releases the response body', async t => {764 let cancelled = false;765 const body = new ReadableStream<Uint8Array>({766 start(controller) {767 controller.enqueue(new TextEncoder().encode('server error'));768 },769 cancel() {770 cancelled = true;771 },772 });773774 const error = await t.throwsAsync(ky('https://example.com', {775 retry: 0,776 throwHttpErrors() {777 throw new Error('policy engine exploded');778 },779 fetch: async () => new Response(body, {status: 500}),780 }).text(), {message: 'policy engine exploded'});781782 t.is(error?.message, 'policy engine exploded');783 await new Promise(resolve => {784 setTimeout(resolve, 10);785 });786 t.true(cancelled, 'the response body must be released');787});788789test('a `throwHttpErrors` predicate that throws is still seen by `beforeError`', async t => {790 const seen: string[] = [];791792 await t.throwsAsync(ky('https://example.com', {793 retry: 0,794 throwHttpErrors() {795 throw new Error('policy engine exploded');796 },797 fetch: async () => new Response('server error', {status: 500}),798 hooks: {799 beforeError: [({error}) => {800 seen.push(error.message);801 }],802 },803 }).text(), {message: 'policy engine exploded'});804805 t.deepEqual(seen, ['policy engine exploded']);806});
modified:test/response-size.ts+29 added
566 unmodified lines
567 t.throws(() => {568 response.headers.set('x-injected', '1');569 }, {instanceOf: TypeError});570});571572// Decoration assigns to the response, so a frozen one throws. The caller then gets the error and never receives573// the response, which left its body with nobody able to release it.574test('a response that cannot be decorated releases its body', async t => {575 let cancelled = false;576 const body = new ReadableStream<Uint8Array>({577 start(controller) {578 controller.enqueue(new TextEncoder().encode('{"a":1}'));579 },580 cancel() {581 cancelled = true;582 },583 });584585 const error = await t.throwsAsync(ky(url, {586 retry: 0,587 parseJson: (text: string) => JSON.parse(text),588 fetch: async () => Object.freeze(new Response(body, {headers: {'content-type': 'application/json'}})),589 }).json(), {590 name: 'TypeError',591 message: /not extensible/,592 });593594 t.is(error?.name, 'TypeError');595 await new Promise(resolve => {596 setTimeout(resolve, 10);597 });598 t.true(cancelled, 'the response body must be released');599});
modified:test/retry.ts+54 added-16 removed
4958 unmodified lines
49594960 t.is(requestCount, 3);4961});49624963// `replaceOption()` is documented to work with any deep-merged option, but a wrapper was only unwrapped where a4964// merge actually ran, so a nested wrapper with no parent value leaked its `{value}` envelope into the result.4963// `replaceOption()` is documented to work with any deep-merged option, but a wrapper was only unwrapped where a merge actually ran, so a nested wrapper with no parent value leaked its `{value}` envelope into the result.4964test('`replaceOption` resolves nested wrappers with and without a parent value', t => {4966 t.deepEqual(validateAndMerge({json: {filters: replaceOption({tags: ['a']})}}).json, {filters: {tags: ['a']}});4965 t.deepEqual(validateAndMerge({custom: {filters: replaceOption({tags: ['a']})}}).custom, {filters: {tags: ['a']}});4966 t.deepEqual(validateAndMerge({json: {filters: {tags: ['old']}}}, {json: {filters: replaceOption({tags: ['a']})}}).json, {filters: {tags: ['a']}});4967 t.deepEqual(validateAndMerge({json: {a: {b: 1}}}, {json: {a: {c: replaceOption({d: 1})}}}).json, {a: {b: 1, c: {d: 1}}});4968 t.deepEqual(validateAndMerge({list: [replaceOption({a: 1})]}).list, [{a: 1}]);4969 t.deepEqual(validateAndMerge({list: [1, replaceOption(2), 3]}).list, [1, 2, 3]);
12 unmodified lines
4982test('`replaceOption` resolution handles a cyclic option', t => {4983 const custom: {self?: unknown} = {};4984 custom.self = custom;49854987 const merged = validateAndMerge({custom, json: {filters: replaceOption({tags: ['a']})}});4986 const merged = validateAndMerge({custom, other: {filters: replaceOption({tags: ['a']})}});4987 t.is(merged.custom, custom);4989 t.deepEqual(merged.json, {filters: {tags: ['a']}});4988 t.deepEqual(merged.other, {filters: {tags: ['a']}});4989});49904992// `.json()` routed the parse through `#raceWithTotalTimeout()`, whose first statement is `throwIfAborted()`, so it4993// rejected a cancelled request while the other five shortcuts resolved with the bytes that had already arrived.4991// `json` is not walked for leftover wrappers, because it can be large and the pass would run on every request. A wrapper there with nothing to replace still sends its value.4992test('`replaceOption` in `json` with no parent value sends its value', async t => {4993 const body = await ky.post('https://example.com', {4994 json: {filters: replaceOption({tags: ['a']})},4995 fetch: async request => new Response(await request.text()),4996 }).text();49974998 t.is(body, '{"filters":{"tags":["a"]}}');4999});50005001test('`replaceOption` does not make every request walk the `json` body', async t => {5002 // A walk that only starts once `replaceOption()` has been used would otherwise depend on test order.5003 replaceOption({});50045005 const json = new Proxy({}, {5006 ownKeys() {5007 throw new Error('The `json` body was walked');5008 },5009 });50105011 t.is(await ky.post('https://example.com', {5012 json,5013 stringifyJson: () => '{}',5014 fetch: async request => new Response(await request.text()),5015 }).text(), '{}');5016});50175018test('`replaceOption` from another copy of Ky is recognised', async t => {5019 const replaceOptionFromOtherCopy = <T>(value: T): T => {5020 const marker: Record<symbol | string, unknown> = {[Symbol.for('ky.replaceOption')]: true, value};5021 return marker as T;5022 };50235024 const api = ky.create({headers: {a: '1'}}).extend({5025 headers: replaceOptionFromOtherCopy({b: '2'}),5026 fetch: async request => new Response(JSON.stringify([...request.headers])),5027 });50285029 t.deepEqual(await api('https://example.com').json(), [['accept', 'application/json'], ['b', '2']]);5030});50315032// `.json()` routed the parse through `#raceWithTotalTimeout()`, whose first statement is `throwIfAborted()`, so it rejected a cancelled request while the other five shortcuts resolved with the bytes that had already arrived.5033for (const type of ['text', 'arrayBuffer', 'blob', 'bytes'] as const) {5034 test.serial(`a user abort during a \`${type}\` body read throws the abort reason`, async t => {5035 const controller = new AbortController();5036 const hookErrors: string[] = [];
69 unmodified lines
5106 t.is(new ForceRetryError({}).message, 'Forced retry');5107 t.is(new ForceRetryError({code: 'RATE_LIMIT'}).message, 'Forced retry: RATE_LIMIT');5108});51095071// The replace-marker pass only held the values on the current path, so a value shared by two branches was resolved5072// in the first and skipped in the second, which kept its `{value}` envelope. A genuine cycle is still left alone.5110// The replace-marker pass only held the values on the current path, so a value shared by two branches was resolved in the first and skipped in the second, which kept its `{value}` envelope. A genuine cycle is still left alone.5111test('`replaceOption` resolves a shared value in every branch that uses it', t => {5112 const shared = {tags: replaceOption(['a'])};5075 const merged = validateAndMerge({json: {first: shared, second: shared, list: [shared]}});5113 const merged = validateAndMerge({custom: {first: shared, second: shared, list: [shared]}});51145077 t.deepEqual(merged.json, {first: {tags: ['a']}, second: {tags: ['a']}, list: [{tags: ['a']}]});5115 t.deepEqual(merged.custom, {first: {tags: ['a']}, second: {tags: ['a']}, list: [{tags: ['a']}]});5116});51175118test('`replaceOption` leaves a cyclic option intact', t => {5119 const cyclic: Record<string, unknown> = {a: 1};5120 cyclic.self = cyclic;51215084 const merged = validateAndMerge({custom: cyclic, json: {filters: replaceOption({tags: ['a']})}});5122 const merged = validateAndMerge({custom: cyclic, other: {filters: replaceOption({tags: ['a']})}});51235124 t.is(merged.custom, cyclic);5087 t.deepEqual(merged.json, {filters: {tags: ['a']}});5125 t.deepEqual(merged.other, {filters: {tags: ['a']}});5126});51275128test('`replaceOption` on a context keeps it a plain object', t => {5129 class Holder {
13 unmodified lines
51435144 const error = await t.throwsAsync(ky.post('https://example.com', {5145 body: 'payload',5146 retry: {limit: 2, delay: () => 5000, methods: ['post']},5109 totalTimeout: 30,5147 totalTimeout: 300,5148 async fetch(request) {5149 attempts++;5150 sentRequest = request;5151 return new Response('server error', {status: 500});
9 unmodified lines
5161 const sentRequests: Request[] = [];5162 let attempts = 0;51635164 const error = await t.throwsAsync(ky.get('https://example.com', {5127 retry: {limit: 10, delay: () => 30},5128 totalTimeout: 250,5165 retry: {limit: 20, delay: () => 30},5166 totalTimeout: 300,5167 async fetch(request) {5168 attempts++;5169 sentRequests.push(request);5170 return new Response('server error', {status: 500});
6 unmodified lines
modified:readme.md+2 added
1384 unmodified lines
1385### replaceOption13861387Wraps a value so that [`ky.extend()`](#kyextenddefaultoptions) will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.13881389Inside the `json` option, which holds your own data, use it only where it replaces an inherited value. Ky does not look for it anywhere else there. The `context` option is merged shallowly, so only a wrapper around the whole `context` is supported.13901391```js1392import ky, {replaceOption} from 'ky';13931394const api = ky.create({
516 unmodified lines