From 44157e21cb16105a84080da1983870983aab46cf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 19:27:18 +0000 Subject: [PATCH 01/15] Bun.serve: apply TCP backpressure to a request body the handler reads slowly When a Bun.serve handler consumes req.body (via for-await, getReader, or pipeTo) slower than the client sends, the uWS onData callback kept pushing every chunk into the ByteStream's internal buffer without ever pausing the socket. A client on loopback could therefore finish writing a multi-GB PUT in a few hundred milliseconds while the server's RSS grew to ~body-size and the next read() returned one body-sized mega-chunk. The node:http server on the same uWS socket already paused reads via NodeHTTPResponse; the Bun.serve req.body path simply never wired the equivalent. on_buffered_body_chunk now pauses the socket once the ByteStream's unconsumed buffer (or the pre-stream request_body_buf, for a handler that has not touched req.body yet) crosses 1 MiB. The existing Body/PendingValue on_stream_drained hook is wired so the ByteStream's signal_drained (fired when a read() empties the buffer) resumes the socket. on_start_buffering resumes and opts out for .text()/.json()/... which need the whole body. The drain handler is detached from the stream source before the request context is released so the source cannot call back into a freed context, and detach_response resumes a paused socket so keep-alive connections return to a readable state after an early response. Fixes #4970 --- src/runtime/server/RequestContext.rs | 113 ++++++++++++- src/runtime/server/mod.rs | 3 + src/runtime/server/server_body.rs | 6 + test/js/bun/http/serve.test.ts | 231 +++++++++++++++++++++++++++ 4 files changed, 352 insertions(+), 1 deletion(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index f85ad8e6a6a9..3ff705639176 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1506,6 +1506,7 @@ where } self.response_weakref.deref(); + self.clear_request_body_stream_drain_handler(global_this); self.request_body_readable_stream_ref.deinit(); // Releases the ref taken in `set_cookies` (via `CookieMapRef::drop`). @@ -2374,6 +2375,10 @@ where self.request_body_buf = Vec::new(); if let Some(resp) = self.resp.take() { + if self.flags.request_body_paused() { + self.flags.set_request_body_paused(false); + resp.resume_(); + } if self.flags.is_waiting_for_request_body() { self.flags.set_is_waiting_for_request_body(false); resp.clear_on_data(); @@ -3901,6 +3906,7 @@ where if this.request_body_streamed_len > server.config().max_request_body_size { this.resp.expect("infallible: resp bound").clear_on_data(); this.flags.set_is_waiting_for_request_body(false); + this.resume_request_body_socket(); let _exit = vm.enter_event_loop_scope(); @@ -3911,6 +3917,9 @@ where readable.value.ensure_still_alive(); if let Some(bytes) = readable.ptr.bytes() { + let source = bytes.parent_const(); + source.drain_handler.set(None); + source.drain_ctx.set(None); let mut err = Body::ValueError::Message(BunString::static_( "Request body exceeded maxRequestBodySize", )); @@ -3951,7 +3960,17 @@ where ); // TODO: properly propagate exception upwards let _ = bytes.on_data(WebCore::streams::Result::Temporary(borrowed)); + + // Backpressure: if the reader did not consume this chunk + // synchronously, `on_data` parked it in the ByteStream's + // internal buffer. Stop reading from the socket until the JS + // side drains it (signalled via `on_stream_drained`). + let buffered = bytes.buffer.get().len().saturating_sub(bytes.offset.get()); + if buffered >= REQUEST_BODY_HIGH_WATER_MARK { + this.pause_request_body_socket(); + } } else { + this.resume_request_body_socket(); // Moved out so the Strong (and its underlying GC handle) is // released at scope exit via `Drop` on `strong::Optional`. let _strong = core::mem::take(&mut this.request_body_readable_stream_ref); @@ -3966,6 +3985,9 @@ where let bytes = bun_ptr::BackRef::from( NonNull::new(bytes_ptr).expect("Source::Bytes payload is non-null"), ); + let source = bytes.parent_const(); + source.drain_handler.set(None); + source.drain_ctx.set(None); // TODO: properly propagate exception upwards let _ = bytes.on_data(WebCore::streams::Result::TemporaryAndDone(borrowed)); } @@ -4055,9 +4077,71 @@ where ); } this.request_body_buf.extend_from_slice(chunk); + + // Backpressure for bodies that have not been touched yet: cap the + // pre-stream buffer so a handler that delays reading does not have + // the whole body queued in memory. Resumed when the handler starts + // streaming (first `read()` drains the ByteStream and fires + // `on_stream_drained`) or opts into whole-body buffering. + if !this.flags.request_body_buffer_all() + && this.request_body_buf.len() >= REQUEST_BODY_HIGH_WATER_MARK + { + this.pause_request_body_socket(); + } + } + } + + fn pause_request_body_socket(&mut self) { + if self.flags.request_body_paused() { + return; + } + let Some(resp) = self.resp else { + return; + }; + ctx_log!("pauseRequestBodySocket"); + self.flags.set_request_body_paused(true); + resp.pause(); + } + + fn resume_request_body_socket(&mut self) { + if !self.flags.request_body_paused() { + return; + } + ctx_log!("resumeRequestBodySocket"); + self.flags.set_request_body_paused(false); + if let Some(resp) = self.resp { + resp.resume_(); } } + /// Detach `on_request_body_stream_drained_callback` from the body's + /// ByteStream source before this context is released (the stream can + /// outlive it in JS). + fn clear_request_body_stream_drain_handler(&self, global_this: &JSGlobalObject) { + let Some(readable) = self.request_body_readable_stream_ref.get(global_this) else { + return; + }; + if let Some(bytes) = readable.ptr.bytes() { + let source = bytes.parent_const(); + source.drain_handler.set(None); + source.drain_ctx.set(None); + } + } + + /// # Safety + /// `ctx` must be a `*mut RequestContext` previously registered as the body + /// `on_stream_drained` context. + pub(crate) fn on_request_body_stream_drained_callback(ctx: Option<*mut c_void>) { + let Some(ctx) = ctx else { return }; + // SAFETY: caller upholds the fn-level contract — `ctx` is the + // `*mut RequestContext` registered as the body callback context. + let this = unsafe { bun_ptr::callback_ctx::(ctx) }; + if this.is_aborted_or_ended() { + return; + } + this.resume_request_body_socket(); + } + pub fn on_start_streaming_request_body(&mut self) -> WebCore::DrainResult { ctx_log!("onStartStreamingRequestBody"); if self.is_aborted_or_ended() { @@ -4089,6 +4173,10 @@ where pub fn on_start_buffering(&mut self) { if let Some(server) = self.server { ctx_log!("onStartBuffering"); + // `.text()`/`.json()` etc. want the whole body: release any + // pre-stream backpressure and stop re-applying it. + self.flags.set_request_body_buffer_all(true); + self.resume_request_body_socket(); // TODO: check if is someone calling onStartBuffering other than onStartBufferingCallback // if is not, this should be removed and only keep protect + setAbortHandler // HTTP/3 (RFC 9114): Content-Length is optional; the body is @@ -4183,6 +4271,12 @@ where const MAX_REQUEST_BODY_PREALLOCATE_LENGTH: usize = 1024 * 256; +/// Pause the socket when the request-body ByteStream (or the pre-stream +/// `request_body_buf`) holds more than this many unconsumed bytes. Two uWS recv +/// buffers' worth (`LIBUS_RECV_BUFFER_LENGTH` = 512 KB) keeps loopback +/// throughput high while bounding memory to O(1) per request. +const REQUEST_BODY_HIGH_WATER_MARK: usize = 1024 * 1024; + // Trap host fn for the `(false, _, true)` arms of `exported_host_fns`. Those // `RequestContext` monomorphs (plain-HTTP/3) are type-reachable via the // blanket H3 impls but never serve requests at runtime — HTTP/3 always @@ -4395,7 +4489,7 @@ pub struct SendfileContext { // `is_web_browser_navigation` / `has_finalized` accessors on the const params. bitflags::bitflags! { #[derive(Default, Clone, Copy)] - pub struct FlagsBits: u16 { + pub struct FlagsBits: u32 { const HAS_MARKED_COMPLETE = 1 << 0; const HAS_MARKED_PENDING = 1 << 1; const HAS_ABORT_HANDLER = 1 << 2; @@ -4416,6 +4510,13 @@ bitflags::bitflags! { const ABORTED = 1 << 13; const HAS_FINALIZED = 1 << 14; const IS_ERROR_PROMISE_PENDING = 1 << 15; + /// Socket reads are paused because the request-body ByteStream (or the + /// pre-stream `request_body_buf`) is over its high-water mark. + const REQUEST_BODY_PAUSED = 1 << 16; + /// The handler has asked for the whole body via `.text()`/`.json()` + /// etc. (`on_start_buffering` fired). Skip backpressure on the + /// pre-stream buffer: the consumer wants everything. + const REQUEST_BODY_BUFFER_ALL = 1 << 17; } } @@ -4495,6 +4596,16 @@ impl Flags { set_is_error_promise_pending, IS_ERROR_PROMISE_PENDING ); + flag_accessor!( + request_body_paused, + set_request_body_paused, + REQUEST_BODY_PAUSED + ); + flag_accessor!( + request_body_buffer_all, + set_request_body_buffer_all, + REQUEST_BODY_BUFFER_ALL + ); #[inline] pub fn is_web_browser_navigation(self) -> bool { diff --git a/src/runtime/server/mod.rs b/src/runtime/server/mod.rs index f50f6ce8b23d..458f86e84c2d 100644 --- a/src/runtime/server/mod.rs +++ b/src/runtime/server/mod.rs @@ -818,6 +818,9 @@ impl NewServer { on_readable_stream_available: Some( ServerRequestContext::::on_request_body_readable_stream_available, ), + on_stream_drained: Some( + ServerRequestContext::::on_request_body_stream_drained_callback, + ), ..Default::default() }); } diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index 560b52bc0269..bf2cd1db254e 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -136,6 +136,7 @@ pub(super) trait RequestCtxOps: RequestCtx { global_this: &JSGlobalObject, readable: WebCore::ReadableStream, ); + fn on_request_body_stream_drained_callback(this: Option<*mut c_void>); } impl RequestCtxOps @@ -275,6 +276,10 @@ where ) { Self::on_request_body_readable_stream_available(this, global_this, readable) } + #[inline] + fn on_request_body_stream_drained_callback(this: Option<*mut c_void>) { + Self::on_request_body_stream_drained_callback(this) + } } // NOTE: local request/response trait so generic `Ctx::Req` / `Ctx::Resp` @@ -3187,6 +3192,7 @@ where on_readable_stream_available: Some( Ctx::on_request_body_readable_stream_available, ), + on_stream_drained: Some(Ctx::on_request_body_stream_drained_callback), ..Default::default() }); } diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index d6534b96eae8..32f0099395bf 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -3268,6 +3268,237 @@ it("resumes a backpressured Response(ReadableStream) once the client drains and } }); +// https://github.com/oven-sh/bun/issues/4970 +it("applies backpressure to a streamed request body when the handler reads slowly", async () => { + // The server reads one chunk then stalls on a gate. Without backpressure the + // client can push the whole body into the ByteStream's internal buffer in + // that window (one ~TOTAL-sized mega-chunk once the gate opens). With it the + // socket is paused once ~1 MiB is buffered, so the client's write loop parks + // on `drain` well short of TOTAL and every delivered chunk stays bounded. + const TOTAL = 32 * 1024 * 1024; + const BLOCK = Buffer.alloc(256 * 1024, 7); + + const gate = Promise.withResolvers(); + const gotFirstChunk = Promise.withResolvers(); + let serverBytes = 0; + let maxChunk = 0; + let contentOk = true; + const serverDone = Promise.withResolvers(); + + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + const reader = req.body!.getReader(); + const first = await reader.read(); + if (first.value) { + serverBytes += first.value.length; + maxChunk = Math.max(maxChunk, first.value.length); + if (first.value[0] !== 7 || first.value.at(-1) !== 7) contentOk = false; + } + gotFirstChunk.resolve(); + await gate.promise; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + serverBytes += value.length; + maxChunk = Math.max(maxChunk, value.length); + if (value[0] !== 7 || value.at(-1) !== 7) contentOk = false; + } + serverDone.resolve(); + return new Response("ok"); + }, + }); + + const sock = net.connect(server.port, "127.0.0.1"); + await new Promise((resolve, reject) => { + sock.once("connect", () => resolve()); + sock.once("error", reject); + }); + sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + + let sent = 0; + let drainWaiters = 0; + const writeMore = () => { + while (sent < TOTAL) { + const n = Math.min(BLOCK.length, TOTAL - sent); + const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); + sent += n; + if (!ok) { + drainWaiters++; + sock.once("drain", writeMore); + return; + } + } + }; + writeMore(); + await gotFirstChunk.promise; + + // Poll until the client's progress plateaus (backpressure engaged) or it + // manages to send the whole body (the bug). + let last = -1; + let stable = 0; + while (sent < TOTAL && stable < 12) { + await Bun.sleep(25); + if (sent === last) stable++; + else { + stable = 0; + last = sent; + } + } + const sentBeforeGate = sent; + + gate.resolve(); + sock.on("data", () => {}); + await serverDone.promise; + sock.destroy(); + + // With backpressure the client stalls after ~HWM + kernel socket buffers. + // Without it, the client finishes the whole body before the gate opens. + expect(sentBeforeGate).toBeGreaterThan(0); + expect(sentBeforeGate).toBeLessThan(TOTAL); + expect(drainWaiters).toBeGreaterThan(0); + // The ByteStream buffer is capped at ~1 MiB, so the largest chunk the + // handler ever sees is that plus at most one recv buffer. Without + // backpressure the second read would deliver ~TOTAL bytes in one chunk. + expect(maxChunk).toBeLessThan(4 * 1024 * 1024); + expect(serverBytes).toBe(TOTAL); + expect(contentOk).toBe(true); +}); + +it("applies backpressure to a request body that the handler has not touched yet", async () => { + // Same shape as above but the handler does not touch req.body until after the + // client has plateaued, covering the pre-stream request_body_buf path. + const TOTAL = 32 * 1024 * 1024; + const BLOCK = Buffer.alloc(256 * 1024, 9); + + const gate = Promise.withResolvers(); + let serverBytes = 0; + let maxChunk = 0; + const serverDone = Promise.withResolvers(); + + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + await gate.promise; + for await (const c of req.body!) { + serverBytes += c.length; + maxChunk = Math.max(maxChunk, c.length); + } + serverDone.resolve(); + return new Response("ok"); + }, + }); + + const sock = net.connect(server.port, "127.0.0.1"); + await new Promise((resolve, reject) => { + sock.once("connect", () => resolve()); + sock.once("error", reject); + }); + sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + + let sent = 0; + const writeMore = () => { + while (sent < TOTAL) { + const n = Math.min(BLOCK.length, TOTAL - sent); + const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); + sent += n; + if (!ok) { + sock.once("drain", writeMore); + return; + } + } + }; + writeMore(); + + let last = -1; + let stable = 0; + while (sent < TOTAL && stable < 12) { + await Bun.sleep(25); + if (sent === last) stable++; + else { + stable = 0; + last = sent; + } + } + const sentBeforeGate = sent; + + gate.resolve(); + sock.on("data", () => {}); + await serverDone.promise; + sock.destroy(); + + expect(sentBeforeGate).toBeGreaterThan(0); + expect(sentBeforeGate).toBeLessThan(TOTAL); + expect(maxChunk).toBeLessThan(4 * 1024 * 1024); + expect(serverBytes).toBe(TOTAL); +}); + +it("resumes a paused request body when the handler calls .arrayBuffer()", async () => { + // .arrayBuffer() wants the whole body, so the pre-stream pause must release + // once it is called instead of leaving the socket wedged. + const TOTAL = 8 * 1024 * 1024; + const BLOCK = Buffer.alloc(256 * 1024, 5); + + const gate = Promise.withResolvers(); + const serverDone = Promise.withResolvers(); + + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + await gate.promise; + const buf = await req.arrayBuffer(); + serverDone.resolve(buf.byteLength); + return new Response("ok"); + }, + }); + + const sock = net.connect(server.port, "127.0.0.1"); + await new Promise((resolve, reject) => { + sock.once("connect", () => resolve()); + sock.once("error", reject); + }); + sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + + let sent = 0; + const writeMore = () => { + while (sent < TOTAL) { + const n = Math.min(BLOCK.length, TOTAL - sent); + const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); + sent += n; + if (!ok) { + sock.once("drain", writeMore); + return; + } + } + }; + writeMore(); + + let last = -1; + let stable = 0; + while (sent < TOTAL && stable < 12) { + await Bun.sleep(25); + if (sent === last) stable++; + else { + stable = 0; + last = sent; + } + } + expect(sent).toBeLessThan(TOTAL); + + gate.resolve(); + sock.on("data", () => {}); + const bytes = await serverDone.promise; + sock.destroy(); + + expect(bytes).toBe(TOTAL); +}); + // https://github.com/oven-sh/bun/issues/32469 it("type: direct stream awaiting flush(true) under backpressure does not re-enter pull", async () => { const CHUNK = Buffer.alloc(256 * 1024, 67); From 2328cafabf25c4b5d049cb750ee14791f1c7c631 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 19:43:50 +0000 Subject: [PATCH 02/15] test: dedupe the request-body backpressure client helper; widen .arrayBuffer body past loopback socket buffers --- test/js/bun/http/serve.test.ts | 370 ++++++++++++++------------------- 1 file changed, 158 insertions(+), 212 deletions(-) diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index 32f0099395bf..4d0135023fc1 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -3268,235 +3268,181 @@ it("resumes a backpressured Response(ReadableStream) once the client drains and } }); -// https://github.com/oven-sh/bun/issues/4970 -it("applies backpressure to a streamed request body when the handler reads slowly", async () => { - // The server reads one chunk then stalls on a gate. Without backpressure the - // client can push the whole body into the ByteStream's internal buffer in - // that window (one ~TOTAL-sized mega-chunk once the gate opens). With it the - // socket is paused once ~1 MiB is buffered, so the client's write loop parks - // on `drain` well short of TOTAL and every delivered chunk stays bounded. - const TOTAL = 32 * 1024 * 1024; - const BLOCK = Buffer.alloc(256 * 1024, 7); - - const gate = Promise.withResolvers(); - const gotFirstChunk = Promise.withResolvers(); - let serverBytes = 0; - let maxChunk = 0; - let contentOk = true; - const serverDone = Promise.withResolvers(); - - using server = serve({ - port: 0, - idleTimeout: 0, - maxRequestBodySize: TOTAL + 1, - async fetch(req) { - const reader = req.body!.getReader(); - const first = await reader.read(); - if (first.value) { - serverBytes += first.value.length; - maxChunk = Math.max(maxChunk, first.value.length); - if (first.value[0] !== 7 || first.value.at(-1) !== 7) contentOk = false; - } - gotFirstChunk.resolve(); - await gate.promise; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - serverBytes += value.length; - maxChunk = Math.max(maxChunk, value.length); - if (value[0] !== 7 || value.at(-1) !== 7) contentOk = false; +describe("request body backpressure", () => { + // Raw-socket PUT client: connect, send the request head, then pump `total` + // bytes of `fill`, pausing on `drain`. Resolves once the client's `sent` + // counter has plateaued for 12×25 ms (backpressure engaged) or it finished + // the whole body (the bug). + async function pumpUploadUntilPlateau(port: number, total: number, fill: number) { + const block = Buffer.alloc(256 * 1024, fill); + const sock = net.connect(port, "127.0.0.1"); + await new Promise((resolve, reject) => { + sock.once("connect", () => resolve()); + sock.once("error", reject); + }); + sock.on("error", () => {}); + sock.on("data", () => {}); + sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${total}\r\nConnection: close\r\n\r\n`); + + let sent = 0; + let drainWaiters = 0; + const writeMore = () => { + while (sent < total) { + const n = Math.min(block.length, total - sent); + const ok = sock.write(n === block.length ? block : block.subarray(0, n)); + sent += n; + if (!ok) { + drainWaiters++; + sock.once("drain", writeMore); + return; + } } - serverDone.resolve(); - return new Response("ok"); - }, - }); - - const sock = net.connect(server.port, "127.0.0.1"); - await new Promise((resolve, reject) => { - sock.once("connect", () => resolve()); - sock.once("error", reject); - }); - sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + }; + writeMore(); - let sent = 0; - let drainWaiters = 0; - const writeMore = () => { - while (sent < TOTAL) { - const n = Math.min(BLOCK.length, TOTAL - sent); - const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); - sent += n; - if (!ok) { - drainWaiters++; - sock.once("drain", writeMore); - return; + let last = -1; + let stable = 0; + while (sent < total && stable < 12) { + await Bun.sleep(25); + if (sent === last) stable++; + else { + stable = 0; + last = sent; } } - }; - writeMore(); - await gotFirstChunk.promise; - - // Poll until the client's progress plateaus (backpressure engaged) or it - // manages to send the whole body (the bug). - let last = -1; - let stable = 0; - while (sent < TOTAL && stable < 12) { - await Bun.sleep(25); - if (sent === last) stable++; - else { - stable = 0; - last = sent; - } + return { sock, sentBeforeGate: sent, drainWaiters }; } - const sentBeforeGate = sent; - - gate.resolve(); - sock.on("data", () => {}); - await serverDone.promise; - sock.destroy(); - - // With backpressure the client stalls after ~HWM + kernel socket buffers. - // Without it, the client finishes the whole body before the gate opens. - expect(sentBeforeGate).toBeGreaterThan(0); - expect(sentBeforeGate).toBeLessThan(TOTAL); - expect(drainWaiters).toBeGreaterThan(0); - // The ByteStream buffer is capped at ~1 MiB, so the largest chunk the - // handler ever sees is that plus at most one recv buffer. Without - // backpressure the second read would deliver ~TOTAL bytes in one chunk. - expect(maxChunk).toBeLessThan(4 * 1024 * 1024); - expect(serverBytes).toBe(TOTAL); - expect(contentOk).toBe(true); -}); - -it("applies backpressure to a request body that the handler has not touched yet", async () => { - // Same shape as above but the handler does not touch req.body until after the - // client has plateaued, covering the pre-stream request_body_buf path. - const TOTAL = 32 * 1024 * 1024; - const BLOCK = Buffer.alloc(256 * 1024, 9); - - const gate = Promise.withResolvers(); - let serverBytes = 0; - let maxChunk = 0; - const serverDone = Promise.withResolvers(); - using server = serve({ - port: 0, - idleTimeout: 0, - maxRequestBodySize: TOTAL + 1, - async fetch(req) { - await gate.promise; - for await (const c of req.body!) { - serverBytes += c.length; - maxChunk = Math.max(maxChunk, c.length); - } - serverDone.resolve(); - return new Response("ok"); - }, - }); + it("applies backpressure to a streamed request body when the handler reads slowly", async () => { + // The server reads one chunk then stalls on a gate. Without backpressure the + // client can push the whole body into the ByteStream's internal buffer in + // that window (one ~TOTAL-sized mega-chunk once the gate opens). With it the + // socket is paused once ~1 MiB is buffered, so the client's write loop parks + // on `drain` well short of TOTAL and every delivered chunk stays bounded. + const TOTAL = 32 * 1024 * 1024; + const gate = Promise.withResolvers(); + let serverBytes = 0; + let maxChunk = 0; + let contentOk = true; + const serverDone = Promise.withResolvers(); - const sock = net.connect(server.port, "127.0.0.1"); - await new Promise((resolve, reject) => { - sock.once("connect", () => resolve()); - sock.once("error", reject); - }); - sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + const reader = req.body!.getReader(); + const first = await reader.read(); + if (first.value) { + serverBytes += first.value.length; + maxChunk = Math.max(maxChunk, first.value.length); + if (first.value[0] !== 7 || first.value.at(-1) !== 7) contentOk = false; + } + await gate.promise; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + serverBytes += value.length; + maxChunk = Math.max(maxChunk, value.length); + if (value[0] !== 7 || value.at(-1) !== 7) contentOk = false; + } + serverDone.resolve(); + return new Response("ok"); + }, + }); - let sent = 0; - const writeMore = () => { - while (sent < TOTAL) { - const n = Math.min(BLOCK.length, TOTAL - sent); - const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); - sent += n; - if (!ok) { - sock.once("drain", writeMore); - return; - } - } - }; - writeMore(); - - let last = -1; - let stable = 0; - while (sent < TOTAL && stable < 12) { - await Bun.sleep(25); - if (sent === last) stable++; - else { - stable = 0; - last = sent; + const { sock, sentBeforeGate, drainWaiters } = await pumpUploadUntilPlateau(server.port, TOTAL, 7); + try { + gate.resolve(); + await serverDone.promise; + + // With backpressure the client stalls after ~HWM + kernel socket buffers. + // Without it, the client finishes the whole body before the gate opens. + expect(sentBeforeGate).toBeGreaterThan(0); + expect(sentBeforeGate).toBeLessThan(TOTAL); + expect(drainWaiters).toBeGreaterThan(0); + // The ByteStream buffer is capped at ~1 MiB, so the largest chunk the + // handler ever sees is that plus at most one recv buffer. Without + // backpressure the second read would deliver ~TOTAL bytes in one chunk. + expect(maxChunk).toBeLessThan(4 * 1024 * 1024); + expect(serverBytes).toBe(TOTAL); + expect(contentOk).toBe(true); + } finally { + sock.destroy(); } - } - const sentBeforeGate = sent; - - gate.resolve(); - sock.on("data", () => {}); - await serverDone.promise; - sock.destroy(); - - expect(sentBeforeGate).toBeGreaterThan(0); - expect(sentBeforeGate).toBeLessThan(TOTAL); - expect(maxChunk).toBeLessThan(4 * 1024 * 1024); - expect(serverBytes).toBe(TOTAL); -}); + }); -it("resumes a paused request body when the handler calls .arrayBuffer()", async () => { - // .arrayBuffer() wants the whole body, so the pre-stream pause must release - // once it is called instead of leaving the socket wedged. - const TOTAL = 8 * 1024 * 1024; - const BLOCK = Buffer.alloc(256 * 1024, 5); + it("applies backpressure to a request body that the handler has not touched yet", async () => { + // Same shape as above but the handler does not touch req.body until after the + // client has plateaued, covering the pre-stream request_body_buf path. + const TOTAL = 32 * 1024 * 1024; + const gate = Promise.withResolvers(); + let serverBytes = 0; + let maxChunk = 0; + let contentOk = true; + const serverDone = Promise.withResolvers(); - const gate = Promise.withResolvers(); - const serverDone = Promise.withResolvers(); + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + await gate.promise; + for await (const c of req.body!) { + serverBytes += c.length; + maxChunk = Math.max(maxChunk, c.length); + if (c[0] !== 9 || c.at(-1) !== 9) contentOk = false; + } + serverDone.resolve(); + return new Response("ok"); + }, + }); - using server = serve({ - port: 0, - idleTimeout: 0, - maxRequestBodySize: TOTAL + 1, - async fetch(req) { - await gate.promise; - const buf = await req.arrayBuffer(); - serverDone.resolve(buf.byteLength); - return new Response("ok"); - }, + const { sock, sentBeforeGate } = await pumpUploadUntilPlateau(server.port, TOTAL, 9); + try { + gate.resolve(); + await serverDone.promise; + + expect(sentBeforeGate).toBeGreaterThan(0); + expect(sentBeforeGate).toBeLessThan(TOTAL); + expect(maxChunk).toBeLessThan(4 * 1024 * 1024); + expect(serverBytes).toBe(TOTAL); + expect(contentOk).toBe(true); + } finally { + sock.destroy(); + } }); - const sock = net.connect(server.port, "127.0.0.1"); - await new Promise((resolve, reject) => { - sock.once("connect", () => resolve()); - sock.once("error", reject); - }); - sock.write(`PUT /up HTTP/1.1\r\nHost: x\r\nContent-Length: ${TOTAL}\r\nConnection: close\r\n\r\n`); + it("resumes a paused request body when the handler calls .arrayBuffer()", async () => { + // .arrayBuffer() wants the whole body, so the pre-stream pause must release + // once it is called instead of leaving the socket wedged. + const TOTAL = 32 * 1024 * 1024; + const gate = Promise.withResolvers(); + const serverDone = Promise.withResolvers(); - let sent = 0; - const writeMore = () => { - while (sent < TOTAL) { - const n = Math.min(BLOCK.length, TOTAL - sent); - const ok = sock.write(n === BLOCK.length ? BLOCK : BLOCK.subarray(0, n)); - sent += n; - if (!ok) { - sock.once("drain", writeMore); - return; - } - } - }; - writeMore(); - - let last = -1; - let stable = 0; - while (sent < TOTAL && stable < 12) { - await Bun.sleep(25); - if (sent === last) stable++; - else { - stable = 0; - last = sent; - } - } - expect(sent).toBeLessThan(TOTAL); + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + async fetch(req) { + await gate.promise; + const buf = await req.arrayBuffer(); + serverDone.resolve(buf.byteLength); + return new Response("ok"); + }, + }); - gate.resolve(); - sock.on("data", () => {}); - const bytes = await serverDone.promise; - sock.destroy(); + const { sock, sentBeforeGate } = await pumpUploadUntilPlateau(server.port, TOTAL, 5); + try { + expect(sentBeforeGate).toBeLessThan(TOTAL); - expect(bytes).toBe(TOTAL); + gate.resolve(); + const bytes = await serverDone.promise; + expect(bytes).toBe(TOTAL); + } finally { + sock.destroy(); + } + }); }); // https://github.com/oven-sh/bun/issues/32469 From 4eb163601b260d35a258f66a10fdb5b94b306e47 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 19:47:31 +0000 Subject: [PATCH 03/15] tighten request-body backpressure comments --- src/runtime/server/RequestContext.rs | 34 +++++++++------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 3ff705639176..656f1be5b387 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -3961,10 +3961,8 @@ where // TODO: properly propagate exception upwards let _ = bytes.on_data(WebCore::streams::Result::Temporary(borrowed)); - // Backpressure: if the reader did not consume this chunk - // synchronously, `on_data` parked it in the ByteStream's - // internal buffer. Stop reading from the socket until the JS - // side drains it (signalled via `on_stream_drained`). + // Whatever `on_data` did not hand to a waiting reader is now in + // `bytes.buffer`; `on_stream_drained` resumes once it empties. let buffered = bytes.buffer.get().len().saturating_sub(bytes.offset.get()); if buffered >= REQUEST_BODY_HIGH_WATER_MARK { this.pause_request_body_socket(); @@ -4078,11 +4076,8 @@ where } this.request_body_buf.extend_from_slice(chunk); - // Backpressure for bodies that have not been touched yet: cap the - // pre-stream buffer so a handler that delays reading does not have - // the whole body queued in memory. Resumed when the handler starts - // streaming (first `read()` drains the ByteStream and fires - // `on_stream_drained`) or opts into whole-body buffering. + // Pre-stream backpressure; resumed by `on_stream_drained` once the + // handler reads, or by `on_start_buffering` for `.text()` etc. if !this.flags.request_body_buffer_all() && this.request_body_buf.len() >= REQUEST_BODY_HIGH_WATER_MARK { @@ -4114,9 +4109,8 @@ where } } - /// Detach `on_request_body_stream_drained_callback` from the body's - /// ByteStream source before this context is released (the stream can - /// outlive it in JS). + /// Detach the body ByteStream's `drain_handler` before this context is + /// released: the stream can outlive it in JS. fn clear_request_body_stream_drain_handler(&self, global_this: &JSGlobalObject) { let Some(readable) = self.request_body_readable_stream_ref.get(global_this) else { return; @@ -4173,8 +4167,7 @@ where pub fn on_start_buffering(&mut self) { if let Some(server) = self.server { ctx_log!("onStartBuffering"); - // `.text()`/`.json()` etc. want the whole body: release any - // pre-stream backpressure and stop re-applying it. + // `.text()`/`.json()` want the whole body; disable pre-stream backpressure. self.flags.set_request_body_buffer_all(true); self.resume_request_body_socket(); // TODO: check if is someone calling onStartBuffering other than onStartBufferingCallback @@ -4271,10 +4264,8 @@ where const MAX_REQUEST_BODY_PREALLOCATE_LENGTH: usize = 1024 * 256; -/// Pause the socket when the request-body ByteStream (or the pre-stream -/// `request_body_buf`) holds more than this many unconsumed bytes. Two uWS recv -/// buffers' worth (`LIBUS_RECV_BUFFER_LENGTH` = 512 KB) keeps loopback -/// throughput high while bounding memory to O(1) per request. +/// Pause socket reads once the request-body buffer holds this many unconsumed +/// bytes: two `LIBUS_RECV_BUFFER_LENGTH` (512 KB) recv buffers. const REQUEST_BODY_HIGH_WATER_MARK: usize = 1024 * 1024; // Trap host fn for the `(false, _, true)` arms of `exported_host_fns`. Those @@ -4510,12 +4501,9 @@ bitflags::bitflags! { const ABORTED = 1 << 13; const HAS_FINALIZED = 1 << 14; const IS_ERROR_PROMISE_PENDING = 1 << 15; - /// Socket reads are paused because the request-body ByteStream (or the - /// pre-stream `request_body_buf`) is over its high-water mark. + /// Socket reads are paused because the request-body buffer is over its high-water mark. const REQUEST_BODY_PAUSED = 1 << 16; - /// The handler has asked for the whole body via `.text()`/`.json()` - /// etc. (`on_start_buffering` fired). Skip backpressure on the - /// pre-stream buffer: the consumer wants everything. + /// `on_start_buffering` fired (`.text()` etc.); skip pre-stream backpressure. const REQUEST_BODY_BUFFER_ALL = 1 << 17; } } From 4e88302b7a5b6255cee5ed5c9759dde8e3741eb4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 19:50:14 +0000 Subject: [PATCH 04/15] collapse request-body backpressure comments to one line each --- src/runtime/server/RequestContext.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 656f1be5b387..400ee35d964e 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -3961,8 +3961,7 @@ where // TODO: properly propagate exception upwards let _ = bytes.on_data(WebCore::streams::Result::Temporary(borrowed)); - // Whatever `on_data` did not hand to a waiting reader is now in - // `bytes.buffer`; `on_stream_drained` resumes once it empties. + // What `on_data` buffered; `on_stream_drained` resumes once it empties. let buffered = bytes.buffer.get().len().saturating_sub(bytes.offset.get()); if buffered >= REQUEST_BODY_HIGH_WATER_MARK { this.pause_request_body_socket(); @@ -4076,8 +4075,7 @@ where } this.request_body_buf.extend_from_slice(chunk); - // Pre-stream backpressure; resumed by `on_stream_drained` once the - // handler reads, or by `on_start_buffering` for `.text()` etc. + // Pre-stream backpressure; resumed by `on_stream_drained` / `on_start_buffering`. if !this.flags.request_body_buffer_all() && this.request_body_buf.len() >= REQUEST_BODY_HIGH_WATER_MARK { @@ -4109,8 +4107,7 @@ where } } - /// Detach the body ByteStream's `drain_handler` before this context is - /// released: the stream can outlive it in JS. + /// Detach the body ByteStream's `drain_handler` (the stream can outlive this ctx in JS). fn clear_request_body_stream_drain_handler(&self, global_this: &JSGlobalObject) { let Some(readable) = self.request_body_readable_stream_ref.get(global_this) else { return; @@ -4264,8 +4261,7 @@ where const MAX_REQUEST_BODY_PREALLOCATE_LENGTH: usize = 1024 * 256; -/// Pause socket reads once the request-body buffer holds this many unconsumed -/// bytes: two `LIBUS_RECV_BUFFER_LENGTH` (512 KB) recv buffers. +/// Pause socket reads at this many unconsumed request-body bytes (two 512 KB uWS recv buffers). const REQUEST_BODY_HIGH_WATER_MARK: usize = 1024 * 1024; // Trap host fn for the `(false, _, true)` arms of `exported_host_fns`. Those From adf72bda8b670a871e71442beaef7a20094d4b13 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 20:11:05 +0000 Subject: [PATCH 05/15] resume request body for ByteStream buffer_action consumers and the already-responded-stream teardown path A handler that materialises req.body and then calls .text()/.arrayBuffer() routes through ByteStream::to_buffered_value (buffer_action mode), which never drives on_pull, so the HWM pause was never released. Skip the pause (and release any earlier one) when buffer_action or a native pipe is set. end_already_responded_stream() is the one HTTP/1 teardown path that bypasses detach_response; mirror the resume there so a keep-alive socket whose body was paused is readable for the next request. on_request_body_stream_drained_callback now dispatches via *mut Self (borrow = ptr): ByteStream::on_data re-enters it from inside on_buffered_body_chunk while that frame already holds &mut Self. Tests: add error() handlers that reject serverDone, and a variant that touches req.body before .arrayBuffer() to cover the buffer_action path. --- src/runtime/server/RequestContext.rs | 30 +++++++++--- test/js/bun/http/serve.test.ts | 69 +++++++++++++++++----------- 2 files changed, 65 insertions(+), 34 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 400ee35d964e..9d175bec3e3a 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1186,6 +1186,9 @@ where pub fn end_already_responded_stream(&mut self) { ctx_log!("endAlreadyRespondedStream"); debug_assert!(!HTTP3); + // Resume before `take()`: READABLE was disabled while paused, so the + // socket cannot have been recycled onto a next request in the interim. + self.resume_request_body_socket(); if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); self.flags.set_has_abort_handler(false); @@ -3963,7 +3966,10 @@ where // What `on_data` buffered; `on_stream_drained` resumes once it empties. let buffered = bytes.buffer.get().len().saturating_sub(bytes.offset.get()); - if buffered >= REQUEST_BODY_HIGH_WATER_MARK { + if bytes.buffer_action.get().is_some() || bytes.pipe.get().ctx.is_some() { + // `.text()`-after-`.body` / native pipe want it all; no `on_pull` will fire. + this.resume_request_body_socket(); + } else if buffered >= REQUEST_BODY_HIGH_WATER_MARK { this.pause_request_body_socket(); } } else { @@ -4124,13 +4130,23 @@ where /// `on_stream_drained` context. pub(crate) fn on_request_body_stream_drained_callback(ctx: Option<*mut c_void>) { let Some(ctx) = ctx else { return }; - // SAFETY: caller upholds the fn-level contract — `ctx` is the - // `*mut RequestContext` registered as the body callback context. - let this = unsafe { bun_ptr::callback_ctx::(ctx) }; - if this.is_aborted_or_ended() { - return; + let this = ctx.cast::(); + // SAFETY: `ctx` is the registered `*mut RequestContext`. `ByteStream:: + // on_data` can re-enter here while `on_buffered_body_chunk` already + // holds `&mut Self` (borrow = ptr), so dispatch via the raw pointer. + unsafe { + let flags = &raw mut (*this).flags; + if !(*flags).request_body_paused() { + return; + } + if (*this).resp.is_none() || (*flags).aborted() { + return; + } + (*flags).set_request_body_paused(false); + if let Some(resp) = (*this).resp { + resp.resume_(); + } } - this.resume_request_body_socket(); } pub fn on_start_streaming_request_body(&mut self) -> WebCore::DrainResult { diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index 4d0135023fc1..2ad5169ceb24 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -3330,6 +3330,9 @@ describe("request body backpressure", () => { port: 0, idleTimeout: 0, maxRequestBodySize: TOTAL + 1, + error(e) { + serverDone.reject(e); + }, async fetch(req) { const reader = req.body!.getReader(); const first = await reader.read(); @@ -3386,6 +3389,9 @@ describe("request body backpressure", () => { port: 0, idleTimeout: 0, maxRequestBodySize: TOTAL + 1, + error(e) { + serverDone.reject(e); + }, async fetch(req) { await gate.promise; for await (const c of req.body!) { @@ -3413,36 +3419,45 @@ describe("request body backpressure", () => { } }); - it("resumes a paused request body when the handler calls .arrayBuffer()", async () => { - // .arrayBuffer() wants the whole body, so the pre-stream pause must release - // once it is called instead of leaving the socket wedged. - const TOTAL = 32 * 1024 * 1024; - const gate = Promise.withResolvers(); - const serverDone = Promise.withResolvers(); + for (const touchBodyFirst of [false, true]) { + it(`resumes a paused request body when the handler calls .arrayBuffer()${touchBodyFirst ? " after touching req.body" : ""}`, async () => { + // .arrayBuffer() wants the whole body, so the pre-stream pause must + // release once it is called instead of leaving the socket wedged. The + // second variant materializes `req.body` first so `.arrayBuffer()` goes + // through the ByteStream buffer_action fastpath instead of + // on_start_buffering. + const TOTAL = 32 * 1024 * 1024; + const gate = Promise.withResolvers(); + const serverDone = Promise.withResolvers(); - using server = serve({ - port: 0, - idleTimeout: 0, - maxRequestBodySize: TOTAL + 1, - async fetch(req) { - await gate.promise; - const buf = await req.arrayBuffer(); - serverDone.resolve(buf.byteLength); - return new Response("ok"); - }, - }); + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + error(e) { + serverDone.reject(e); + }, + async fetch(req) { + if (touchBodyFirst) void req.body; + await gate.promise; + const buf = await req.arrayBuffer(); + serverDone.resolve(buf.byteLength); + return new Response("ok"); + }, + }); - const { sock, sentBeforeGate } = await pumpUploadUntilPlateau(server.port, TOTAL, 5); - try { - expect(sentBeforeGate).toBeLessThan(TOTAL); + const { sock, sentBeforeGate } = await pumpUploadUntilPlateau(server.port, TOTAL, 5); + try { + expect(sentBeforeGate).toBeLessThan(TOTAL); - gate.resolve(); - const bytes = await serverDone.promise; - expect(bytes).toBe(TOTAL); - } finally { - sock.destroy(); - } - }); + gate.resolve(); + const bytes = await serverDone.promise; + expect(bytes).toBe(TOTAL); + } finally { + sock.destroy(); + } + }); + } }); // https://github.com/oven-sh/bun/issues/32469 From 18f562dc2042e18f8753923e308241c0c8beeb1a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 20:12:34 +0000 Subject: [PATCH 06/15] collapse end_already_responded_stream resume comment to one line --- src/runtime/server/RequestContext.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 9d175bec3e3a..ccd9b961c9a2 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1186,8 +1186,7 @@ where pub fn end_already_responded_stream(&mut self) { ctx_log!("endAlreadyRespondedStream"); debug_assert!(!HTTP3); - // Resume before `take()`: READABLE was disabled while paused, so the - // socket cannot have been recycled onto a next request in the interim. + // Resume before `take()`: READABLE was disabled while paused, so the socket has not been recycled. self.resume_request_body_socket(); if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); From fa95bc4e3a0ccaa1056efbe0f06057ec5efdf665 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 20:18:28 +0000 Subject: [PATCH 07/15] drop stale u16 width note on the FlagsBits comment --- src/runtime/server/RequestContext.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index ccd9b961c9a2..4b009f3ab5ed 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4486,9 +4486,9 @@ pub struct SendfileContext { pub total: BlobSizeType, } -// All flags are bool (with two debug-conditional ones), so `bitflags!` over u16 -// works. We keep all bits in every build and just gate the -// `is_web_browser_navigation` / `has_finalized` accessors on the const params. +// All flags are bool (with two debug-conditional ones). We keep all bits in +// every build and just gate the `is_web_browser_navigation` / `has_finalized` +// accessors on the const params. bitflags::bitflags! { #[derive(Default, Clone, Copy)] pub struct FlagsBits: u32 { From 59092018aed2754eedeaca6e775b3efd2e822e5b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 21:25:09 +0000 Subject: [PATCH 08/15] fire on_start_buffering from Bun.write's Locked-body path and resume the socket in the sink's end_from_js Bun.write(file, req) on a server request body registers on_receive_value and overwrites locked.task without going through on_start_buffering, so the pre-stream 1 MiB pause was never released. Invoke on_start_buffering with the original task first, mirroring BodyValueBufferer. end_already_responded_stream()'s own contract is that resp may already be freed (uWS markDone dropped onAborted, so nothing nulls self.resp when the peer closes and us_internal_free_closed_sockets runs). Calling resp.resume_() there was a potential UAF. Clear the flag there without dereferencing, and release any request-body pause inside HTTPServerWritable::end_from_js instead, right before send_readable/end while res is known live. Adds a Bun.write(file, req) variant to the backpressure tests. --- src/runtime/server/RequestContext.rs | 4 +-- src/runtime/webcore/Blob.rs | 5 ++++ src/runtime/webcore/streams.rs | 6 +++++ test/js/bun/http/serve.test.ts | 37 ++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 4b009f3ab5ed..7fc4a26c6251 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1186,8 +1186,8 @@ where pub fn end_already_responded_stream(&mut self) { ctx_log!("endAlreadyRespondedStream"); debug_assert!(!HTTP3); - // Resume before `take()`: READABLE was disabled while paused, so the socket has not been recycled. - self.resume_request_body_socket(); + // `resp` may be freed (see above); the sink resumed the socket at `res.end()` while live. + self.flags.set_request_body_paused(false); if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); self.flags.set_has_abort_handler(false); diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index ec3d76a55648..08be65ab0fb6 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -5244,6 +5244,11 @@ pub fn write_file_internal( let BodyValue::Locked(locked) = (unsafe { &mut *body_value }) else { unreachable!() }; + if let (Some(on_start_buffering), Some(orig_task)) = + (locked.on_start_buffering.take(), locked.task) + { + on_start_buffering(orig_task); + } locked.task = Some(task.cast::()); locked.on_receive_value = Some(WriteFileWaitFromLockedValueTask::then_wrap); // SAFETY: `task` was just heap-allocated; consumed in `then_wrap`. diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index d4dfdc47f1cf..978b4ba02afb 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1760,6 +1760,12 @@ impl HTTPServerWritable { } self.requested_end = true; + // Release any request-body backpressure pause before `markDone()` drops + // `onAborted`, after which the RequestContext's stale `resp` must not + // be dereferenced (see `end_already_responded_stream`). + if let Some(res) = self.any_res() { + res.resume_(); + } let readable_len = self.readable_slice().len(); self.end_len = readable_len; diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index 2ad5169ceb24..f9473d519bce 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -3419,6 +3419,43 @@ describe("request body backpressure", () => { } }); + it("resumes a paused request body when the handler calls Bun.write(file, req)", async () => { + // Bun.write on a Locked body installs on_receive_value without creating a + // ByteStream; the pre-stream pause must release via on_start_buffering. + const TOTAL = 32 * 1024 * 1024; + const gate = Promise.withResolvers(); + const serverDone = Promise.withResolvers(); + + using dir = tempDir("serve-request-body-bunwrite", {}); + const out = join(String(dir), "body"); + + using server = serve({ + port: 0, + idleTimeout: 0, + maxRequestBodySize: TOTAL + 1, + error(e) { + serverDone.reject(e); + }, + async fetch(req) { + await gate.promise; + const n = await Bun.write(out, req); + serverDone.resolve(n); + return new Response("ok"); + }, + }); + + const { sock, sentBeforeGate } = await pumpUploadUntilPlateau(server.port, TOTAL, 3); + try { + expect(sentBeforeGate).toBeLessThan(TOTAL); + + gate.resolve(); + const bytes = await serverDone.promise; + expect(bytes).toBe(TOTAL); + } finally { + sock.destroy(); + } + }); + for (const touchBodyFirst of [false, true]) { it(`resumes a paused request body when the handler calls .arrayBuffer()${touchBodyFirst ? " after touching req.body" : ""}`, async () => { // .arrayBuffer() wants the whole body, so the pre-stream pause must From 6eea56b4da858c5db248c1f42ed5ea9522d354b9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 21:26:28 +0000 Subject: [PATCH 09/15] collapse streams.rs resume comment to one line --- src/runtime/webcore/streams.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index 978b4ba02afb..88a61c613ea9 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1760,9 +1760,7 @@ impl HTTPServerWritable { } self.requested_end = true; - // Release any request-body backpressure pause before `markDone()` drops - // `onAborted`, after which the RequestContext's stale `resp` must not - // be dereferenced (see `end_already_responded_stream`). + // Release any request-body pause while `res` is live (see `end_already_responded_stream`). if let Some(res) = self.any_res() { res.resume_(); } From e89fc9e18fe62662818d84d38e6a3891e43a7661 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 22:10:06 +0000 Subject: [PATCH 10/15] resume the socket in uWS markDone() instead of per-sink entry point HTTPServerWritable has two sibling entry points that lead to ended_response = true (end_from_js via controller.end() and end() via controller.close()), plus the on_writable drain path. Rather than patching each, re-arm READABLE in HttpResponseData::markDone itself: every HTTP/1 response-end path calls it, the socket is live at that moment, and us_socket_resume is a no-op when not paused. markDone also nulls inStream, so no further on_buffered_body_chunk calls can race the flag clear in end_already_responded_stream. Reverts the end_from_js resume; updates the end_already_responded_stream comment to point at markDone. --- packages/bun-uws/src/HttpResponseData.h | 6 ++++++ src/runtime/server/RequestContext.rs | 2 +- src/runtime/webcore/streams.rs | 4 ---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/bun-uws/src/HttpResponseData.h b/packages/bun-uws/src/HttpResponseData.h index c27b94add094..7f17e5f6168b 100644 --- a/packages/bun-uws/src/HttpResponseData.h +++ b/packages/bun-uws/src/HttpResponseData.h @@ -58,6 +58,12 @@ struct HttpResponseData : AsyncSocketData, HttpParser { /* We are done with this request */ this->state &= ~HttpResponseData::HTTP_RESPONSE_PENDING; + /* Release any request-body backpressure pause: onAborted is gone so + * the holder can no longer safely resume, and a keep-alive socket + * left paused never reads the next request. us_socket_resume is a + * no-op when not paused. */ + ((AsyncSocket *) uwsRes)->resume(); + HttpResponseData *httpResponseData = uwsRes->getHttpResponseData(); httpResponseData->isIdle = true; } diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 7fc4a26c6251..cfd5cf45959b 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1186,7 +1186,7 @@ where pub fn end_already_responded_stream(&mut self) { ctx_log!("endAlreadyRespondedStream"); debug_assert!(!HTTP3); - // `resp` may be freed (see above); the sink resumed the socket at `res.end()` while live. + // `resp` may be freed (see above); uWS `markDone()` resumed the socket while it was live. self.flags.set_request_body_paused(false); if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index 88a61c613ea9..d4dfdc47f1cf 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1760,10 +1760,6 @@ impl HTTPServerWritable { } self.requested_end = true; - // Release any request-body pause while `res` is live (see `end_already_responded_stream`). - if let Some(res) = self.any_res() { - res.resume_(); - } let readable_len = self.readable_slice().len(); self.end_len = readable_len; From fe928f43ef526c68c26ad67fa2247bbc61c5db99 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 22:54:43 +0000 Subject: [PATCH 11/15] gate markDone's resume on !HTTP_NODE_READS_PAUSED and skip the drain-callback resume once the sink has ended HttpResponseData::markDone is inherited by the node:http compat specialization; an unconditional resume there would release the pipeline-flood pause (HTTP_NODE_READS_PAUSED) early. Skip the resume when that bit is set so node:http's own gated release points stay authoritative. In the drain callback, once a streaming-response sink has set ended_response the response reached markDone (which resumed the socket and dropped onAborted), so resp may since have been freed. Clear the flag without dereferencing resp on that path; the check reads the sink owned by this RequestContext, which is live until handle_resolve_stream tears it down. --- packages/bun-uws/src/HttpResponseData.h | 9 ++++++--- src/runtime/server/RequestContext.rs | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/bun-uws/src/HttpResponseData.h b/packages/bun-uws/src/HttpResponseData.h index 7f17e5f6168b..066e03774363 100644 --- a/packages/bun-uws/src/HttpResponseData.h +++ b/packages/bun-uws/src/HttpResponseData.h @@ -60,9 +60,12 @@ struct HttpResponseData : AsyncSocketData, HttpParser { /* Release any request-body backpressure pause: onAborted is gone so * the holder can no longer safely resume, and a keep-alive socket - * left paused never reads the next request. us_socket_resume is a - * no-op when not paused. */ - ((AsyncSocket *) uwsRes)->resume(); + * left paused never reads the next request. Skip when the node:http + * pipeline-flood guard owns the pause (HTTP_NODE_READS_PAUSED): that + * path has its own gated release points. */ + if (!(this->state & HttpResponseData::HTTP_NODE_READS_PAUSED)) { + ((AsyncSocket *) uwsRes)->resume(); + } HttpResponseData *httpResponseData = uwsRes->getHttpResponseData(); httpResponseData->isIdle = true; diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index cfd5cf45959b..8cf712c9bcc3 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4141,6 +4141,15 @@ where if (*this).resp.is_none() || (*flags).aborted() { return; } + // A sink that already ended the response reached `markDone()` (which + // resumed the socket and dropped `onAborted`); `resp` may since be + // freed — see `end_already_responded_stream`. Just clear the flag. + if let Some(sink) = (*this).sink { + if (*sink.as_ptr()).sink.ended_response { + (*flags).set_request_body_paused(false); + return; + } + } (*flags).set_request_body_paused(false); if let Some(resp) = (*this).resp { resp.resume_(); From aa66a73e0d0ca71c88cb33f6208a240e3b2adf25 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 23:41:16 +0000 Subject: [PATCH 12/15] move the ended-response resume out of uWS and guard every resume site at the owning layer Drop the markDone() resume: HttpResponseData is shared with node:http, whose JS-level pause owners (pausePipelineReads, IncomingMessage pause) route through HttpResponse::pause() without setting HTTP_NODE_READS_PAUSED, so any markDone-side release would still stomp them. Handle the whole lifecycle in Bun.serve's own layer instead: - HTTPServerWritable resumes the socket at both ended_response = true sites, in the same frame as res.end()/try_end (socket closed at worst, never freed). - resume_request_body_socket() and the drain callback consult resp_may_be_freed() (sink.ended_response) and clear the flag without touching resp once the sink has ended, covering on_start_buffering, the buffer_action/pipe release, the last-chunk and 413 paths. - handle_resolve_stream / handle_reject_stream clear REQUEST_BODY_PAUSED and the ByteStream drain_handler immediately after reading ended_response, before detach()/run_error_handler can re-enter JS, so re-entrant drains after sink.take() early-return on the cleared flag. Verified under ASAN with the direct-stream pull() scenarios (reader.read and req.text after c.end() across a loop tick) and the node:http pipelined-reads-pause test. --- packages/bun-uws/src/HttpResponseData.h | 9 ------ src/runtime/server/RequestContext.rs | 42 ++++++++++++++++++------- src/runtime/webcore/streams.rs | 6 ++++ 3 files changed, 36 insertions(+), 21 deletions(-) diff --git a/packages/bun-uws/src/HttpResponseData.h b/packages/bun-uws/src/HttpResponseData.h index 066e03774363..c27b94add094 100644 --- a/packages/bun-uws/src/HttpResponseData.h +++ b/packages/bun-uws/src/HttpResponseData.h @@ -58,15 +58,6 @@ struct HttpResponseData : AsyncSocketData, HttpParser { /* We are done with this request */ this->state &= ~HttpResponseData::HTTP_RESPONSE_PENDING; - /* Release any request-body backpressure pause: onAborted is gone so - * the holder can no longer safely resume, and a keep-alive socket - * left paused never reads the next request. Skip when the node:http - * pipeline-flood guard owns the pause (HTTP_NODE_READS_PAUSED): that - * path has its own gated release points. */ - if (!(this->state & HttpResponseData::HTTP_NODE_READS_PAUSED)) { - ((AsyncSocket *) uwsRes)->resume(); - } - HttpResponseData *httpResponseData = uwsRes->getHttpResponseData(); httpResponseData->isIdle = true; } diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 8cf712c9bcc3..b3e9577a76b4 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -1186,7 +1186,7 @@ where pub fn end_already_responded_stream(&mut self) { ctx_log!("endAlreadyRespondedStream"); debug_assert!(!HTTP3); - // `resp` may be freed (see above); uWS `markDone()` resumed the socket while it was live. + // `resp` may be freed (see above); the sink resumed it at `ended_response = true`. self.flags.set_request_body_paused(false); if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); @@ -2862,6 +2862,13 @@ where req.flags.set_aborted(aborted); wrote_anything = wrapper.sink.wrote > 0; ended_response = wrapper.sink.ended_response; + if ended_response { + // `resp` may be freed; the sink already resumed it. Clear these + // before `detach()` below re-enters JS so any drain callback / + // `on_start_buffering` reached from there early-returns. + req.flags.set_request_body_paused(false); + req.clear_request_body_stream_drain_handler(req.server().global_this()); + } wrapper.sink.finalize(); let sink_global = wrapper @@ -2946,6 +2953,11 @@ where if let Some(wrapper) = req.sink_mut() { let wrapper_ptr = req.sink.take().expect("infallible: sink_mut returned Some"); ended_response = wrapper.sink.ended_response; + if ended_response { + // `resp` may be freed; the sink already resumed it. Clear before JS below. + req.flags.set_request_body_paused(false); + req.clear_request_body_stream_drain_handler(global_this); + } if let Some(prom) = wrapper.sink.pending_flush.take() { // The promise value was protected when pending_flush was // assigned (flushFromJS / endFromJS). Drop that root before @@ -4107,11 +4119,26 @@ where } ctx_log!("resumeRequestBodySocket"); self.flags.set_request_body_paused(false); + if self.resp_may_be_freed() { + return; + } if let Some(resp) = self.resp { resp.resume_(); } } + /// After a streaming-response sink has set `ended_response`, `markDone()` + /// dropped `onAborted` and `resp` may point at a freed `us_socket_t` (see + /// `end_already_responded_stream`). The sink already resumed the socket. + #[inline] + fn resp_may_be_freed(&self) -> bool { + if let Some(sink) = self.sink { + // SAFETY: `sink` is owned by this context and freed in `handle_resolve_stream`/`deinit`. + return unsafe { (*sink.as_ptr()).sink.ended_response }; + } + false + } + /// Detach the body ByteStream's `drain_handler` (the stream can outlive this ctx in JS). fn clear_request_body_stream_drain_handler(&self, global_this: &JSGlobalObject) { let Some(readable) = self.request_body_readable_stream_ref.get(global_this) else { @@ -4138,19 +4165,10 @@ where if !(*flags).request_body_paused() { return; } - if (*this).resp.is_none() || (*flags).aborted() { + (*flags).set_request_body_paused(false); + if (*this).resp.is_none() || (*flags).aborted() || (*this).resp_may_be_freed() { return; } - // A sink that already ended the response reached `markDone()` (which - // resumed the socket and dropped `onAborted`); `resp` may since be - // freed — see `end_already_responded_stream`. Just clear the flag. - if let Some(sink) = (*this).sink { - if (*sink.as_ptr()).sink.ended_response { - (*flags).set_request_body_paused(false); - return; - } - } - (*flags).set_request_body_paused(false); if let Some(resp) = (*this).resp { resp.resume_(); } diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index d4dfdc47f1cf..d171c8e949bf 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1404,6 +1404,8 @@ impl HTTPServerWritable { if self.requested_end { if let Some(res) = self.any_res() { res.clear_on_writable(); + // Release any request-body pause while `res` is live (see `end_already_responded_stream`). + res.resume_(); } // `send_readable` drained the parked `try_end`, so uWS has // `markDone()`d the response and dropped its `onAborted`. @@ -1778,6 +1780,10 @@ impl HTTPServerWritable { } } + if let Some(res) = self.any_res() { + // Release any request-body pause while `res` is live (see `end_already_responded_stream`). + res.resume_(); + } // Both branches above fully ended the response through uWS, which // `markDone()`s it and drops its `onAborted`. self.ended_response = true; From 0b69a42185a7d304da1cb92d2a0c841a44af6efc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 23:56:51 +0000 Subject: [PATCH 13/15] inline the sink.ended_response check in the drain callback via raw ptr; spot-check Bun.write test output bytes --- src/runtime/server/RequestContext.rs | 8 +++++++- test/js/bun/http/serve.test.ts | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index b3e9577a76b4..42955c7db665 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4166,9 +4166,15 @@ where return; } (*flags).set_request_body_paused(false); - if (*this).resp.is_none() || (*flags).aborted() || (*this).resp_may_be_freed() { + if (*this).resp.is_none() || (*flags).aborted() { return; } + // Inline `resp_may_be_freed()` via raw ptr (borrow = ptr; see above). + if let Some(sink) = (*this).sink { + if (*sink.as_ptr()).sink.ended_response { + return; + } + } if let Some(resp) = (*this).resp { resp.resume_(); } diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index f9473d519bce..1b6f58ce4fec 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -3451,6 +3451,8 @@ describe("request body backpressure", () => { gate.resolve(); const bytes = await serverDone.promise; expect(bytes).toBe(TOTAL); + const written = await Bun.file(out).bytes(); + expect([written.length, written[0], written.at(-1)]).toEqual([TOTAL, 3, 3]); } finally { sock.destroy(); } From dafee3f6e2a0a4d3d65f54aa164d557375a5ada7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:26:33 +0000 Subject: [PATCH 14/15] set ended_response + resume in on_auto_flush when it completes a requested_end on_auto_flush is a third sink completion site that can drain a parked try_end/end (controller.close() + sub-HWM buffered data, no backpressure) without setting ended_response or resuming the socket. Mirror the on_writable/end_from_js completion block so resp_may_be_freed() is accurate and handle_resolve_stream routes to end_already_responded_stream on this path; also closes a pre-existing UAF where the fallthrough end_stream() dereferenced the same freed resp. --- src/runtime/webcore/streams.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index d171c8e949bf..a98f8cdeb8f9 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1865,6 +1865,20 @@ impl HTTPServerWritable { return true; } self.auto_flusher.registered.set(false); + + if self.requested_end { + if let Some(res) = self.any_res() { + res.clear_on_writable(); + // Release any request-body pause while `res` is live (see `end_already_responded_stream`). + res.resume_(); + } + // `send_readable` drained the parked `try_end`/`end`, so uWS has + // `markDone()`d the response and dropped its `onAborted`. + self.ended_response = true; + self.signal.close(None); + let _ = self.flush_promise(); + self.finalize(); + } false } From 2f9c163312a44a4b8cd00d8b08fb5110691e2127 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 00:33:02 +0000 Subject: [PATCH 15/15] guard the drain callback on server detached/terminated too (matching is_aborted_or_ended) --- src/runtime/server/RequestContext.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 42955c7db665..1c2c1d969248 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4166,7 +4166,10 @@ where return; } (*flags).set_request_body_paused(false); - if (*this).resp.is_none() || (*flags).aborted() { + if (*this).resp.is_none() + || (*flags).aborted() + || (*this).server.is_none_or(|s| s.terminated()) + { return; } // Inline `resp_may_be_freed()` via raw ptr (borrow = ptr; see above).