diff --git a/src/runtime/webcore/ByteStream.rs b/src/runtime/webcore/ByteStream.rs index 77a2603581b2..019038c5c01f 100644 --- a/src/runtime/webcore/ByteStream.rs +++ b/src/runtime/webcore/ByteStream.rs @@ -68,8 +68,7 @@ pub(crate) type Source = readable_stream::NewSource; /// A network body producer's (fetch, S3) hold on the stream it feeds: a counted ref on the stream's /// `Source`, so delivery and unhooking go through memory the producer keeps alive rather than the /// JS wrapper (which the VM's last sweep destroys in no particular order), plus the parked bit of -/// the receive backpressure. The ref roots the wrapper except while parked, so an unread stream -/// can be collected (`SourceHandle::consumer_collected`). +/// the receive backpressure. It roots the wrapper only for a native sink or a whole-body read. #[derive(Default)] pub(crate) struct ProducerHold { source: Cell>>, @@ -83,7 +82,7 @@ pub(crate) enum AfterDelivery { Resume, /// At the mark with a back-pressured sink: it resumes the producer when it drains. Pause, - /// At the mark and nothing reads: pause, release the loop, leave the stream collectable. + /// At the mark and nothing reads: pause, release the loop. Park, } @@ -97,8 +96,28 @@ impl ProducerHold { // SAFETY: fn contract; the ref keeps the Source alive past this call. unsafe { let source = Source::from_context_ptr(bytes); - (*source).increment_count(); self.source.set(core::ptr::NonNull::new(source)); + // Before the ref, so `increment_count` only roots a wrapper that stays rooted. + self.sync_wrapper_root(); + (*source).increment_count(); + } + } + + fn sync_wrapper_root(&self) { + let Some(source) = self.source.get() else { + return; + }; + let source = source.as_ptr(); + // SAFETY: live through our ref. The caller may hold the `&ByteStream` of this very source + // (the chunk it just delivered): shared reads of its cells here, and the root is a + // separate field written through the raw pointer. + unsafe { + let bytes = &(*source).context; + if bytes.sink.get().is_some() || bytes.buffer_action.get().is_some() { + Source::root_wrapper(source); + } else { + Source::unroot_wrapper(source); + } } } @@ -107,7 +126,7 @@ impl ProducerHold { } /// The held stream, pinned for the guard's life: a consumer inside `on_data` can cancel the - /// producer (which drops the hold), and while parked the wrapper is not rooted. + /// producer (which drops the hold), and the wrapper is not always rooted. pub(crate) fn bytes(&self) -> Option { let source = self.source.get()?; // SAFETY: live through our ref; no borrow of the source exists yet. @@ -133,7 +152,8 @@ impl ProducerHold { drop(self.take()); } - pub(crate) fn after_delivery(bytes: &ByteStream) -> AfterDelivery { + pub(crate) fn after_delivery(&self, bytes: &ByteStream) -> AfterDelivery { + self.sync_wrapper_root(); if bytes.buffered_len() < bun_http::signals::BODY_HIGH_WATER_MARK || bytes.buffer_action.get().is_some() { @@ -147,28 +167,13 @@ impl ProducerHold { /// Returns whether this call parked (the caller then releases its loop ref). pub(crate) fn park(&self) -> bool { - if self.parked.replace(true) { - return false; - } - if let Some(source) = self.source.get() { - // SAFETY: live through our ref. The caller may hold the `&ByteStream` of this very - // source (the chunk it just delivered), which is why this is not a method call. - unsafe { Source::unroot_wrapper(source.as_ptr()) }; - } - true + !self.parked.replace(true) } - /// Returns whether this call unparked (the caller then re-takes its loop ref). Reached from a - /// consumer holding the stream. + /// A consumer attached or took bytes; returns whether this unparked (re-take the loop ref). pub(crate) fn unpark(&self) -> bool { - if !self.parked.replace(false) { - return false; - } - if let Some(source) = self.source.get() { - // SAFETY: as in `park`. - unsafe { Source::root_wrapper(source.as_ptr()) }; - } - true + self.sync_wrapper_root(); + self.parked.replace(false) } } diff --git a/src/runtime/webcore/ReadableStream.rs b/src/runtime/webcore/ReadableStream.rs index e75931ee0739..8202acb9af8e 100644 --- a/src/runtime/webcore/ReadableStream.rs +++ b/src/runtime/webcore/ReadableStream.rs @@ -810,7 +810,7 @@ pub trait SourceContext: Sized { } /// The JS wrapper was collected while native refs remain. Runs inside a GC - /// sweep: no JS. `ByteStream` tells a parked producer nobody can read it now. + /// sweep: no JS. `ByteStream` tells its producer nobody can read it now. fn wrapper_finalized(&mut self) {} /// `setRefUnrefFn` — default no-op. @@ -878,9 +878,7 @@ pub struct NewSource { /// `Finalized` so [`Self::on_close`] reads `None` instead of a /// dead-but-unswept cell. pub this_jsvalue: jsc::JsRef, - /// The producer holding a native ref has parked ([`Self::unroot_wrapper`]): - /// its ref keeps this allocation, not the wrapper, so an unread stream can - /// be collected. Cleared by [`Self::root_wrapper`]. + /// The producer's native ref does not root the wrapper ([`Self::unroot_wrapper`]). pub wrapper_unrooted: Cell, /// R-2: written by context methods (`ByteStream::to_any_blob`, /// `ByteBlobLoader::to_any_blob`) through their parent accessor, so @@ -1187,8 +1185,7 @@ impl NewSource { } } - /// The producer keeps its native ref but stops rooting the wrapper: nothing - /// is reading, so the stream should be collectable. [`SourceContext::wrapper_finalized`] + /// The producer's ref leaves the wrapper collectable. [`SourceContext::wrapper_finalized`] /// tells the producer if that happens. /// /// Takes a raw pointer: the producer reaches this while it holds a `&C` into @@ -1205,7 +1202,7 @@ impl NewSource { } } - /// Undo [`Self::unroot_wrapper`]: a consumer is reading again. + /// Undo [`Self::unroot_wrapper`]: a consumer that does not hold the wrapper takes the bytes. /// /// # Safety /// As [`Self::unroot_wrapper`]. diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index 40705a013f83..1f6ea98102b5 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -1760,7 +1760,7 @@ impl FetchTasklet { self.abandon_response_body(); } - /// `SourceHandle::consumer_collected`: the parked stream's wrapper was swept, so nothing + /// `SourceHandle::consumer_collected`: the stream's wrapper was swept, so nothing /// can read the rest of the body. Inside a GC sweep, like `on_response_finalize`. pub(crate) fn on_body_stream_collected(&self) { bun_output::scoped_log!(FetchTasklet, "onBodyStreamCollected"); @@ -1785,13 +1785,13 @@ impl FetchTasklet { /// The other half of this rule is in `callback` (HTTP thread). fn after_body_chunk_delivered(&self, bytes: &crate::webcore::ByteStream) { - use crate::webcore::byte_stream::{AfterDelivery, ProducerHold}; + use crate::webcore::byte_stream::AfterDelivery; bun_output::scoped_log!( FetchTasklet, "afterBodyChunkDelivered buffered={}", bytes.buffered_len() ); - match ProducerHold::after_delivery(bytes) { + match self.response_stream.after_delivery(bytes) { AfterDelivery::Resume => self.resume_receive(), AfterDelivery::Pause => self.signal_store.pause_receive(), AfterDelivery::Park => { diff --git a/src/runtime/webcore/s3/client.rs b/src/runtime/webcore/s3/client.rs index 8d90f365fc1e..dc701fae0bc0 100644 --- a/src/runtime/webcore/s3/client.rs +++ b/src/runtime/webcore/s3/client.rs @@ -1375,12 +1375,12 @@ impl S3DownloadStreamWrapper { /// The other half of this rule is in `S3HttpDownloadStreamingTask::process_http_callback` /// (HTTP thread). fn after_chunk_delivered(&self, bytes: &ByteStream) { - use crate::webcore::byte_stream::{AfterDelivery, ProducerHold}; + use crate::webcore::byte_stream::AfterDelivery; let task = self.task.get(); if task.is_null() { return; } - match ProducerHold::after_delivery(bytes) { + match self.stream.after_delivery(bytes) { // SAFETY: see `task`. AfterDelivery::Resume => unsafe { (*task).resume_receive() }, // SAFETY: see `task`. @@ -1389,7 +1389,7 @@ impl S3DownloadStreamWrapper { // SAFETY: see `task`. unsafe { (*task).signal_store.pause_receive() }; if self.stream.park() { - // SAFETY: see `task`; `park` touched the stream's source, not the task. + // SAFETY: see `task`. unsafe { (*task).poll_ref.unref(bun_io::js_vm_ctx()) }; } } @@ -1417,7 +1417,7 @@ impl S3DownloadStreamWrapper { self.unpark(); } - /// The parked stream's wrapper was collected: nothing can read the rest. Inside a GC sweep; + /// The stream's wrapper was collected: nothing can read the rest. Inside a GC sweep; /// touches no JS cell. pub(crate) fn on_stream_collected(&self) { self.on_stream_cancelled(); diff --git a/test/js/web/fetch/fetch-backpressure.test.ts b/test/js/web/fetch/fetch-backpressure.test.ts index f697b83759b3..5aded6c4ebcd 100644 --- a/test/js/web/fetch/fetch-backpressure.test.ts +++ b/test/js/web/fetch/fetch-backpressure.test.ts @@ -1255,6 +1255,56 @@ describe.concurrent("fetch() receive backpressure — a Response whose body noth } }); +// An origin whose body stays under the mark, as an event stream does between events: a head and +// one small chunk, then nothing until `trickle()` sends every response one more chunk and +// `finish()` ends them. The origin never closes, so every close it sees is the client's. +const PIECE = 1024; +async function quietOrigin() { + const piece = Buffer.from(`${PIECE.toString(16)}\r\n${Buffer.alloc(PIECE, 65)}\r\n`); + let closed = 0; + let responded = 0; + const responses = new Set(); + const sockets = new Set(); + const closeWaiters: [number, () => void][] = []; + const responseWaiters: [number, () => void][] = []; + const srv = createTcpServer(socket => { + sockets.add(socket); + socket.on("error", () => {}); + socket.on("close", () => { + closed++; + sockets.delete(socket); + responses.delete(socket); + for (const [n, resolve] of closeWaiters) if (closed >= n) resolve(); + }); + socket.once("data", () => { + socket.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\n\r\n"); + socket.write(piece, () => { + responses.add(socket); + responded++; + for (const [n, resolve] of responseWaiters) if (responded >= n) resolve(); + }); + }); + }); + srv.listen(0, "127.0.0.1"); + await once(srv, "listening"); + const { port } = srv.address() as import("node:net").AddressInfo; + const toEach = (data: string | Buffer) => + Promise.all(Array.from(responses, socket => new Promise(resolve => socket.write(data, resolve)))); + return { + url: `http://127.0.0.1:${port}/`, + respondedTo: (n: number) => + responded >= n ? Promise.resolve() : new Promise(resolve => responseWaiters.push([n, resolve])), + trickle: () => toEach(piece), + finish: () => toEach("0\r\n\r\n"), + closedAtLeast: (n: number) => + closed >= n ? Promise.resolve() : new Promise(resolve => closeWaiters.push([n, resolve])), + [Symbol.asyncDispose]: () => { + for (const socket of sockets) socket.destroy(); + return new Promise(resolve => srv.close(() => resolve())); + }, + }; +} + // S3 downloads go through the same HTTP client with their own body producer // (S3DownloadStreamWrapper). The same rule applies: a reader that stalls pauses the transport, // an unread stream does not hold the process, and a collected one aborts the download. @@ -1652,3 +1702,110 @@ describe.serial("fetch() receive backpressure — an unread body hands its conne }); } }); + +// A body stream nothing can read is collected and its fetch aborted, even under the mark. +// Serial: every test here runs full collections, which would stall the concurrent blocks above. +describe.serial("fetch() receive backpressure — an abandoned body stream under the mark", () => { + const N = 4; + const shapes: [string, "quiet" | "trickle", (res: Response) => Promise][] = [ + ["res.body touched", "quiet", async res => res.body], + ["getReader(), never read", "quiet", async res => void res.body!.getReader()], + // A pull that is in flight when the stream is dropped waits for bytes, and holds the + // stream until some arrive for it. + [ + "one read(), then releaseLock()", + "trickle", + async res => { + const reader = res.body!.getReader(); + await reader.read(); + reader.releaseLock(); + }, + ], + ["dropped while a reader holds the lock", "trickle", async res => void (await res.body!.getReader().read())], + ]; + + test.each(shapes)("%s, %s peer: the stream is collected and its fetch is aborted", async (_name, peer, shape) => { + await using origin = await quietOrigin(); + // Its own frame, so that nothing on this one still refers to a response afterwards. + async function abandonOne() { + await shape(await fetch(origin.url)); + } + for (let i = 0; i < N; i++) await abandonOne(); + await origin.respondedTo(N); + if (peer === "trickle") await origin.trickle(); + await collectUntil(origin.closedAtLeast(N)); + }); + + test("an S3 stream, trickle peer: the stream is collected and its download is aborted", async () => { + await using origin = await quietOrigin(); + const s3 = new S3Client({ accessKeyId: "test", secretAccessKey: "test", endpoint: origin.url, bucket: "b" }); + // Its own frame: after it returns nothing refers to the stream. + await (async () => { + const reader = s3.file("k").stream().getReader(); + await reader.read(); + reader.releaseLock(); + })(); + await origin.respondedTo(1); + await origin.trickle(); + await collectUntil(origin.closedAtLeast(1)); + }); + + // The other side of that rule: a consumer is often held by nothing but its own promise, and + // its body must still arrive, through full collections between the pieces of a body that is + // never anywhere near the mark. + const PIECES = 4; + const count = async (chunks: AsyncIterable<{ length: number }>) => { + let total = 0; + for await (const chunk of chunks) total += chunk.length; + return total; + }; + const consumers: [string, (res: Response, dir: string) => Promise][] = [ + [ + "a reader loop", + async res => { + let total = 0; + for (let r, reader = res.body!.getReader(); !(r = await reader.read()).done; ) total += r.value.byteLength; + return total; + }, + ], + [ + "pipeTo()", + async res => { + let total = 0; + await res.body!.pipeTo(new WritableStream({ write: chunk => void (total += chunk.byteLength) })); + return total; + }, + ], + ["tee()", async res => Math.min(...(await Promise.all(res.body!.tee().map(count))))], + ["Readable.fromWeb()", res => count(Readable.fromWeb(res.body as any))], + ["textStream()", res => count(res.textStream())], + ["res.body.text()", async res => (await res.body!.text()).length], + ["res.text() after res.body", async res => (void res.body, (await res.text()).length)], + ["HTMLRewriter.transform()", async res => (await new HTMLRewriter().on("x", {}).transform(res).text()).length], + ["Bun.write() after res.body", (res, dir) => (void res.body, Bun.write(join(dir, "body"), res))], + [ + "a Bun.serve response", + async res => { + using proxy = Bun.serve({ port: 0, fetch: () => new Response(res.body) }); + return (await (await fetch(proxy.url)).bytes()).byteLength; + }, + ], + ]; + + test.each(consumers)("%s gets a whole body that trickles in while the collector runs", async (_name, consume) => { + using dir = tempDir("fetch-trickle-consumer", {}); + await using origin = await quietOrigin(); + // Its own frame: once it returns, the consumer's promise is all that is held. + const received = (async () => consume(await fetch(origin.url), String(dir)))(); + await origin.respondedTo(1); + for (let i = 1; i < PIECES; i++) { + await stat(import.meta.path); + Bun.gc(true); + await origin.trickle(); + } + await stat(import.meta.path); + Bun.gc(true); + await origin.finish(); + expect(await received).toBe(PIECES * PIECE); + }); +});