Honour a late abort, count a no-op `content-encoding`, and keep wrapped headers immutable
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Count a no-op content-encoding and keep wrapped headers immutable A `content-length` header is valid for a response whose `content-encoding` is the registered no-op `identity`, so it is not discarded the way a real coding is. The `Response` constructor also rebuilds the header list under the mutable "response" guard, so a network response that arrived immutable would silently become mutable once wrapped. Reusing the original headers object keeps the guard.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent a0eeae2 · Browse files · 6 files·+155 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+155 added−10 removed
- tests:+137 added−1 removed
- other:+18 added−9 removed
Provenance
- Commit
3f0e330- Tree
8614fa8- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
a0eeae2
6 files changed+155 added−10 removed
modified:source/core/Ky.ts+7 added
926 unmodified lines927 928 result = timedOutResponseData;929 }930 931+ // A cancellation is part of the request lifecycle, so it must not resolve as a successful body read just932+ // because the bytes happened to arrive first. `.json()` already gets this check for free through933+ // `#raceWithTotalTimeout()`, which is why the shortcuts used to disagree here.934+ if (this.#userProvidedAbortSignal?.aborted) {935+ await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);936+ }937+938 if (result === timedOutResponseData || this.#getRemainingTotalTimeout() === 0) {939 // The stream is locked by the native body method's own reader by this point, so940 // `response.body.cancel()` would reject as "already locked". Aborting the request's941 // signal is what actually interrupts the underlying network read.573 unmodified linesmodified:source/utils/body.ts+10 added-8 removed
141 unmodified lines142 // The `Response` constructor cannot set these, so copy them over from the original response.143 url: {value: originalResponse.url},144 redirected: {value: originalResponse.redirected},145 type: {value: originalResponse.type},146+ // The constructor also rebuilds the header list under the mutable "response" guard, so a network response147+ // that arrived immutable would silently become mutable. Reuse the original's headers to keep the guard.148+ headers: {value: originalResponse.headers},149 // Native `clone()` creates a new `Response`, which would drop them again.150 // Keep the shim replaceable like `Response.prototype.clone` for instrumentation and mocks.151 clone: {152 value() {17 unmodified lines170 return response;171 };172 173 export const limitResponseSize = (response: Response, request: Request, maxResponseSize: number): Response => {171- // A body a hook already read cannot be piped through, and would otherwise fail with "The ReadableStream is172- // locked" instead of the native "Body is unusable" error that names the actual mistake.173- if (!response.body || response.bodyUsed || nullBodyStatuses.has(response.status) || maxResponseSize === Number.POSITIVE_INFINITY) {174+ // A body a hook already read, or locked with a reader, cannot be piped through, and would otherwise fail with175+ // "The ReadableStream is locked" instead of the native "Body is unusable" error that names the actual mistake.176+ if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status) || maxResponseSize === Number.POSITIVE_INFINITY) {177 return response;178 }179 180 let transferredBytes = 0;15 unmodified lines196 };197 198 export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {199 // See `limitResponseSize`: there is nothing left to stream and nothing to report once a hook consumed the body.197- if (!response.body || response.bodyUsed || nullBodyStatuses.has(response.status)) {200+ if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status)) {201 return response;202 }203 201- // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after202- // decompression. Using it for a content-coded response would report a total below what actually arrives, so203- // every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`.204- const isContentCoded = response.headers.get('content-encoding') !== null;204+ // `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.205+ const contentEncoding = response.headers.get('content-encoding')?.toLowerCase();206+ const isContentCoded = Boolean(contentEncoding) && contentEncoding !== 'identity';207 const totalBytes = isContentCoded ? 0 : Math.max(0, Number(response.headers.get('content-length')) || 0);208 const body = withProgress(response.body, totalBytes, onDownloadProgress);209 210 return copyResponseMetadata(new Response(body, response), response);22 unmodified linesmodified:source/utils/merge.ts+1 added-1 removed
437 unmodified lines438 returnValue.signal = signals.at(-1);439 }440 }441 442- return isRoot ? resolveReplaceMarkers(returnValue, new Set()) : returnValue;442+ return isRoot ? resolveReplaceMarkers(returnValue, new Set()) as T : returnValue;443 };444 445 export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T =>446 deepMergeInternal<T>(true, ...sources);modified:test/response-size.ts+66 added-1 removed
481 unmodified lines482 // Wrapping a body that a hook already read fails with \"The ReadableStream is locked\", which names neither the real mistake nor the option that caused it. The native \"Body is unusable\" error is far clearer, so the wrappers skip an already consumed body instead of crashing inside `pipeThrough()`.483 for (const [label, options] of [484 ['without the limit', {}],485 ['with `maxResponseSize`', {maxResponseSize: 1000}],486- ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],486+ [487+ 'with `onDownloadProgress`',488+ {489+ // Only the option's presence matters here.490+ onDownloadProgress: () => undefined,491+ },492+ ],493 ] as Array<[string, Record<string, unknown>]>) {494 test(`an afterResponse hook that returns a consumed response reports the native error ${label}`, async t => {495 const response = await ky(url, {496 ...options,11 unmodified lines508 message: 'Body is unusable: Body has already been read',509 });510 });511 }512+513+// A reader taken with `getReader()` but never read leaves `bodyUsed` false, so the guard missed it and `pipeThrough()` failed with an error that names neither the mistake nor the option.514+for (const [label, options] of [515+ ['with `maxResponseSize`', {maxResponseSize: 1000}],516+ [517+ 'with `onDownloadProgress`',518+ {519+ // Only the option's presence matters here.520+ onDownloadProgress: () => undefined,521+ },522+ ],523+] as Array<[string, Record<string, unknown>]>) {524+ test(`a body that is only locked reports the native error ${label}`, async t => {525+ const response = await ky(url, {526+ ...options,527+ async fetch() {528+ const result = new Response('x'.repeat(50));529+ result.body!.getReader();530+ return result;531+ },532+ });533+534+ await t.throwsAsync(response.text(), {535+ name: 'TypeError',536+ message: 'Body is unusable: Body has already been read',537+ });538+ });539+}540+541+// `new Response(body, response)` rebuilds the header list under the mutable "response" guard, so a network response that arrived immutable became mutable as soon as one of these options was set.542+for (const [label, options] of [543+ ['with `maxResponseSize`', {maxResponseSize: 1000}],544+ ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],545+] as Array<[string, Record<string, unknown>]>) {546+ test(`response headers stay immutable ${label}`, async t => {547+ const server = await createHttpTestServer(t);548+ server.get('/', (_request, response) => {549+ response.set('content-type', 'text/plain').end('payload');550+ });551+552+ const response = await ky(server.url, options);553+ t.true(response.headers.get('content-type')!.startsWith('text/plain'));554+ t.throws(() => {555+ response.headers.set('x-injected', '1');556+ }, {instanceOf: TypeError});557+ });558+}559+560+test('response headers stay immutable without the wrapping options', async t => {561+ const server = await createHttpTestServer(t);562+ server.get('/', (_request, response) => {563+ response.end('payload');564+ });565+566+ const response = await ky(server.url);567+ t.throws(() => {568+ response.headers.set('x-injected', '1');569+ }, {instanceOf: TypeError});570+});modified:test/retry.ts+35 added
4985 unmodified lines4986 const merged = validateAndMerge({custom, json: {filters: replaceOption({tags: ['a']})}});4987 t.is(merged.custom, custom);4988 t.deepEqual(merged.json, {filters: {tags: ['a']}});4989 });4990+4991+// `.json()` routed the parse through `#raceWithTotalTimeout()`, whose first statement is `throwIfAborted()`, so it4992+// rejected a cancelled request while the other five shortcuts resolved with the bytes that had already arrived.4993+for (const type of ['text', 'arrayBuffer', 'blob', 'bytes'] as const) {4994+ test.serial(`a user abort during a \`${type}\` body read throws the abort reason`, async t => {4995+ const controller = new AbortController();4996+ const hookErrors: string[] = [];4997+4998+ const promise = ky('https://example.com', {4999+ signal: controller.signal,5000+ async fetch() {5001+ const body = new ReadableStream({5002+ async start(streamController) {5003+ streamController.enqueue(new TextEncoder().encode('{"a":1}'));5004+ await delay(50);5005+ streamController.close();5006+ },5007+ });5008+ return new Response(body, {headers: {'content-type': 'application/json'}});5009+ },5010+ hooks: {5011+ beforeError: [({error}) => {5012+ hookErrors.push(String(error));5013+ }],5014+ },5015+ })[type]();5016+5017+ setTimeout(() => {5018+ controller.abort();5019+ }, 10);5020+5021+ await t.throwsAsync(promise, {name: 'AbortError'});5022+ t.is(hookErrors.length, 1);5023+ });5024+}modified:test/stream.ts+36 added
1369 unmodified lines1370 1371 t.is(text.length, 64);1372 t.is(progressEvents.at(-1)?.totalBytes, 64);1373 });1374+1375+// `content-encoding: identity` is a registered no-op coding (RFC 9110 §8.4.2), so `content-length` is the decoded1376+// length and remains a valid total, as it is for a response with no `content-encoding` at all.1377+for (const [label, headers] of [1378+ ['no content-encoding', {}],1379+ ['content-encoding: identity', {'content-encoding': 'identity'}],1380+ ['content-encoding: Identity', {'content-encoding': 'Identity'}],1381+ ['an empty content-encoding', {'content-encoding': ''}],1382+] as Array<[string, Record<string, string>]>) {1383+ test(`download progress uses content-length with ${label}`, async t => {1384+ const progressEvents: Progress[] = [];1385+ const text = await ky('https://example.com', {1386+ async fetch() {1387+ const body = new ReadableStream<Uint8Array>({1388+ start(controller) {1389+ for (let index = 0; index < 8; index++) {1390+ controller.enqueue(new Uint8Array(1024));1391+ }1392+1393+ controller.close();1394+ },1395+ });1396+ return new Response(body, {headers: {'content-length': '8192', ...headers}});1397+ },1398+ onDownloadProgress(progress) {1399+ progressEvents.push(progress);1400+ },1401+ }).text();1402+1403+ t.is(text.length, 8192);1404+ t.is(progressEvents.at(-1)?.totalBytes, 8192);1405+ t.is(progressEvents[0]?.totalBytes, 8192);1406+ // 1024 of 8192 bytes on the first event, so the percentage has to climb from there.1407+ t.is(progressEvents[0]?.percent, 0.125);1408+ });1409+}