diff --git a/mordant-baseline.toml b/mordant-baseline.toml index 14c56af9d263..9f775b277a38 100644 --- a/mordant-baseline.toml +++ b/mordant-baseline.toml @@ -46,7 +46,6 @@ "arg_named_like_other_param:src/runtime/cli/install_completions_command.rs" = 4 "arg_named_like_other_param:src/runtime/cli/pack_command.rs" = 1 "bare_bool_args:src/runtime/api.rs" = 2 -"bare_bool_args:src/runtime/api/bun/h2_frame_parser.rs" = 1 "bare_bool_args:src/runtime/bake/dev_server/incremental_graph.rs" = 1 "bare_bool_args:src/runtime/cli/run_command.rs" = 1 "bare_bool_args:src/runtime/dns_jsc/dns.rs" = 1 diff --git a/src/runtime/api/bun/h2_frame_parser.rs b/src/runtime/api/bun/h2_frame_parser.rs index d49694b433da..34419abc8588 100644 --- a/src/runtime/api/bun/h2_frame_parser.rs +++ b/src/runtime/api/bun/h2_frame_parser.rs @@ -1132,6 +1132,16 @@ enum BatchSegment { Ext { ptr: *const u8, len: u32 }, } +/// Flags for one `H2FrameParser::send_data` call. +#[derive(Clone, Copy)] +struct SendDataOptions { + close: bool, + /// Report a HALF_CLOSED_LOCAL transition through the return value instead of onStreamEnd. + suppress_half_closed_local_dispatch: bool, + /// Hand an unqueued payload's write callback back to the caller instead of invoking it here. + defer_write_callback: bool, +} + struct DispatchGuard<'a>(&'a Cell); impl Drop for DispatchGuard<'_> { @@ -7464,29 +7474,20 @@ impl H2FrameParser { )) } - /// Returns `(settled_state, callback_deferred)`. - /// - /// `settled_state` is the state code the close tail settled on (5 = HALF_CLOSED_LOCAL, - /// 7 = CLOSED, 0 = no close-tail transition ran). With - /// `suppress_half_closed_local_dispatch` the HALF_CLOSED_LOCAL onStreamEnd dispatch - /// is skipped — the synchronous caller (writeStream) hands the state to JS via its - /// return value instead of re-entering the VM mid-host-call. - /// - /// With `defer_write_callback`, when the payload is handed to the socket without being - /// queued (no flow-control / socket backpressure) the write callback is NOT invoked here: - /// `callback_deferred` is true and the JS caller completes it asynchronously instead, so a - /// node Writable's `_write` callback never settles synchronously inside `write()`. When the - /// payload is queued, the engine still owns the callback and invokes it once the queued - /// frames are flushed (backpressure cleared), exactly as before. + /// Returns `(settled_state, callback_deferred)`: the state the close tail settled on (5 = + /// HALF_CLOSED_LOCAL, 7 = CLOSED, 0 = none) and whether `callback` was left to the caller. fn send_data( &self, stream: &mut Stream, payload: &[u8], - close: bool, callback: JSValue, - suppress_half_closed_local_dispatch: bool, - defer_write_callback: bool, + options: SendDataOptions, ) -> (u8, bool) { + let SendDataOptions { + close, + suppress_half_closed_local_dispatch, + defer_write_callback, + } = options; bun_output::scoped_log!( H2FrameParser, "HTTP_FRAME_DATA {} sendData({}, {}, {})", @@ -7748,7 +7749,16 @@ impl H2FrameParser { let stream = unsafe { &mut *stream }; stream.wait_for_trailers = false; - let _ = this.send_data(stream, b"", true, JSValue::UNDEFINED, false, false); + let _ = this.send_data( + stream, + b"", + JSValue::UNDEFINED, + SendDataOptions { + close: true, + suppress_half_closed_local_dispatch: false, + defer_write_callback: false, + }, + ); Ok(JSValue::UNDEFINED) } @@ -8280,10 +8290,12 @@ impl H2FrameParser { let (settled_state, callback_deferred) = this.send_data( &mut stream, &payload, - close, callback_arg, - true, - defer_callback_arg.to_boolean(), + SendDataOptions { + close, + suppress_half_closed_local_dispatch: true, + defer_write_callback: defer_callback_arg.to_boolean(), + }, ); // 5 = HALF_CLOSED_LOCAL: the JS caller runs markWritableDone itself instead of diff --git a/test/js/node/http2/node-http2.test.js b/test/js/node/http2/node-http2.test.js index 26f4f42a1597..e8c6ac6f6f1d 100644 --- a/test/js/node/http2/node-http2.test.js +++ b/test/js/node/http2/node-http2.test.js @@ -4720,6 +4720,82 @@ it("end(chunk) on a HALF_CLOSED_REMOTE stream still emits 'finish'", async () => } }); +it("write() completes its callback on a later turn, not inside write()", async () => { + // _write hands the chunk to the native session with the write callback deferred, so the + // chunk is still counted in writableLength when write() returns and the Writable settles it + // later, like node, where a write only completes once the session has flushed it. Were the + // callback invoked inside the native call, writableLength would already be 0 here. + const server = http2.createServer(); + let client; + try { + const lengths = Promise.withResolvers(); + server.on("stream", async stream => { + try { + stream.respond({ ":status": 200 }); + const chunk = Buffer.from("hello"); + const written = new Promise((resolve, reject) => stream.write(chunk, err => (err ? reject(err) : resolve()))); + const afterWrite = stream.writableLength; + await written; + lengths.resolve({ afterWrite, afterCallback: stream.writableLength }); + stream.end(); + } catch (err) { + lengths.reject(err); + } + }); + const port = await new Promise(resolve => server.listen(0, () => resolve(server.address().port))); + client = http2.connect(`http://127.0.0.1:${port}`); + client.on("error", lengths.reject); + const req = client.request({ ":path": "/" }); + const body = new Promise((resolve, reject) => { + const chunks = []; + req.on("error", reject); + req.on("data", chunk => chunks.push(chunk)); + req.on("end", () => resolve(Buffer.concat(chunks).toString())); + }); + req.end(); + expect(await Promise.all([lengths.promise, body])).toEqual([{ afterWrite: 5, afterCallback: 0 }, "hello"]); + } finally { + client?.close(); + server.close(); + } +}); + +it("sendTrailers({}) ends the stream without a trailer block", async () => { + // An empty trailer object ends the stream with an empty END_STREAM DATA frame rather than a + // HEADERS frame: the peer sees the body end and no 'trailers' event, and the stream closes + // cleanly on both sides. + const server = http2.createServer(); + let client; + try { + const serverClose = Promise.withResolvers(); + server.on("stream", stream => { + stream.on("error", serverClose.reject); + stream.on("wantTrailers", () => stream.sendTrailers({})); + stream.on("close", () => serverClose.resolve(stream.rstCode)); + stream.respond({ ":status": 200 }, { waitForTrailers: true }); + stream.end("OK"); + }); + const port = await new Promise(resolve => server.listen(0, () => resolve(server.address().port))); + client = http2.connect(`http://127.0.0.1:${port}`); + client.on("error", serverClose.reject); + const req = client.request({ ":path": "/" }); + const trailerEvents = []; + req.on("trailers", headers => trailerEvents.push(headers)); + const body = new Promise((resolve, reject) => { + const chunks = []; + req.on("error", reject); + req.on("data", chunk => chunks.push(chunk)); + req.on("end", () => resolve(Buffer.concat(chunks).toString())); + }); + req.end(); + expect(await Promise.all([body, serverClose.promise])).toEqual(["OK", 0]); + expect(trailerEvents).toEqual([]); + } finally { + client?.close(); + server.close(); + } +}); + it("client connects over a user Duplex that already has a 'data' listener", async () => { // A 'data' listener attached before connect() puts the stream in flowing mode, so the // peer's first frames can arrive before the connect callback has run. The preface must