Skip to content
Myr

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

2 files+101 added−5 removed

modified:source/core/Ky.ts+10 added-5 removed
59 unmodified lines
60 }6162 // 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();6566 for (const hook of ky.#options.hooks.afterResponse) {67 // Clone the response before passing to hook so we can cancel it if needed
104 unmodified lines
172 const originalRequest = ky.#originalRequest;173174 // 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;182183 for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {
506 unmodified lines
690 }691692 const nonRequestOptions = findUnknownOptions(this.request, this.#options);693693 // 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 }701702 if (this.#options.timeout === false) {703 return this.#options.fetch(this.#originalRequest, nonRequestOptions);704 }
63 unmodified lines
modified:test/retry.ts+91 added
1import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';3import ky, {TimeoutError} from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';5import {parseRawBody} from './helpers/parse-body.js';6import {withPerformance} from './helpers/with-performance.js';78const fixture = 'fixture';9const defaultRetryCount = 2;
562 unmodified lines
572573 t.is(requestCount, 1);574});575576test('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 });581582 const body = 'hello stream';583 const stream = new ReadableStream({584 start(controller) {585 controller.enqueue(new TextEncoder().encode(body));586 controller.close();587 },588 });589590 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();596597 t.is(result, body);598});599600test('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 });610611 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 });625626 t.is(fetchCallCount, 1);627 t.is(cancelCount, 1);628});629630test('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 }639640 response.send(await parseRawBody(request));641 });642643 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 });650651 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();661662 t.is(result, body);663 t.is(requestCount, 2);664});665666test('throws when retry.methods is not an array', async t => {667 const server = await createHttpTestServer(t);668669 t.throws(() => {
939 unmodified lines