Skip request cloning when retries are disabled to prevent buffering large streaming bodies
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #831
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 101c74b · Browse files · 2 files·+101 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+101 added−5 removed
- tests:+91 added−0 removed
- other:+10 added−5 removed
Provenance
- Commit
6f3d1bd- Tree
f0d6a4f- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
101c74b
2 files changed+101 added−5 removed
modified:source/core/Ky.ts+10 added-5 removed
59 unmodified lines60 }61 62 // Delay the fetch so that body method shortcuts can set the Accept header63 await Promise.resolve();64- // Before using ky.request, _fetch clones it and saves the clone for future retries to use.65- // If retry is not needed, close the cloned request's ReadableStream for memory safety.64 let response = await ky.#fetch();65 66 for (const hook of ky.#options.hooks.afterResponse) {67 // Clone the response before passing to hook so we can cancel it if needed104 unmodified lines172 const originalRequest = ky.#originalRequest;173 174 // Ignore cancellation errors from already-locked or already-consumed streams.175 ky.#cancelBody(originalRequest?.body ?? undefined);176+ // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries).177+ if (ky.request !== originalRequest) {178- ky.#cancelBody(ky.request.body ?? undefined);178+ ky.#cancelBody(ky.request.body ?? undefined);179+ }180 }181 })() as ResponsePromise;182 183 for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {506 unmodified lines690 }691 692 const nonRequestOptions = findUnknownOptions(this.request, this.#options);693 693- // Cloning is done here to prepare in advance for retries694+ // Cloning is done here to prepare in advance for retries.695+ // Skip cloning when retries are disabled — cloning a streaming body calls ReadableStream#tee()696+ // which buffers the entire stream in memory, causing excessive memory usage for large uploads.697 this.#originalRequest = this.request;698+ if (this.#options.retry.limit > 0) {695- this.request = this.#originalRequest.clone();699+ this.request = this.#originalRequest.clone();700+ }701 702 if (this.#options.timeout === false) {703 return this.#options.fetch(this.#originalRequest, nonRequestOptions);704 }63 unmodified linesmodified:test/retry.ts+91 added
1 import {setTimeout as delay} from 'node:timers/promises';2 import test from 'ava';3 import ky, {TimeoutError} from '../source/index.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5+import {parseRawBody} from './helpers/parse-body.js';6 import {withPerformance} from './helpers/with-performance.js';7 8 const fixture = 'fixture';9 const defaultRetryCount = 2;562 unmodified lines572 573 t.is(requestCount, 1);574 });575 576+test('streaming body POST succeeds when retry.limit is 0', async t => {577+ const server = await createHttpTestServer(t, {bodyParser: false});578+ server.post('/', async (request, response) => {579+ response.send(await parseRawBody(request));580+ });581+582+ const body = 'hello stream';583+ const stream = new ReadableStream({584+ start(controller) {585+ controller.enqueue(new TextEncoder().encode(body));586+ controller.close();587+ },588+ });589+590+ const result = await ky.post(server.url, {591+ // @ts-expect-error - Types are outdated.592+ duplex: 'half',593+ body: stream,594+ retry: {limit: 0},595+ }).text();596+597+ t.is(result, body);598+});599+600+test('streaming body is canceled once when retry.limit is 0 and fetch throws', async t => {601+ let cancelCount = 0;602+ const stream = new ReadableStream({603+ start(controller) {604+ controller.enqueue(new TextEncoder().encode('cancel me'));605+ },606+ cancel() {607+ cancelCount++;608+ },609+ });610+611+ const expectedError = new Error('fetch failed');612+ let fetchCallCount = 0;613+ await t.throwsAsync(ky.post('https://example.com', {614+ // @ts-expect-error - Types are outdated.615+ duplex: 'half',616+ body: stream,617+ retry: {limit: 0},618+ async fetch() {619+ fetchCallCount++;620+ throw expectedError;621+ },622+ }).text(), {623+ is: expectedError,624+ });625+626+ t.is(fetchCallCount, 1);627+ t.is(cancelCount, 1);628+});629+630+test('streaming body POST retries and succeeds when retry.limit is above 0', async t => {631+ let requestCount = 0;632+ const server = await createHttpTestServer(t, {bodyParser: false});633+ server.post('/', async (request, response) => {634+ requestCount++;635+ if (requestCount === 1) {636+ response.sendStatus(408);637+ return;638+ }639+640+ response.send(await parseRawBody(request));641+ });642+643+ const body = 'retry stream body';644+ const stream = new ReadableStream({645+ start(controller) {646+ controller.enqueue(new TextEncoder().encode(body));647+ controller.close();648+ },649+ });650+651+ const result = await ky.post(server.url, {652+ // @ts-expect-error - Types are outdated.653+ duplex: 'half',654+ body: stream,655+ retry: {656+ limit: 1,657+ methods: ['post'],658+ statusCodes: [408],659+ },660+ }).text();661+662+ t.is(result, body);663+ t.is(requestCount, 2);664+});665+666 test('throws when retry.methods is not an array', async t => {667 const server = await createHttpTestServer(t);668 669 t.throws(() => {939 unmodified lines