Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions mordant-baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"tuple_wants_struct:src/css/values/color.rs" = 5

[bun_install]
"always_unwrapped_option:src/install/PackageInstall.rs" = 1
"arg_named_like_other_param:src/install/PackageManager/PackageJSONEditor.rs" = 3
"arg_named_like_other_param:src/install/resolution.rs" = 1
"bare_bool_args:src/install/isolated_install.rs" = 1
Expand Down Expand Up @@ -55,7 +54,6 @@
"arg_named_like_other_param:src/runtime/cli/pack_command.rs" = 1
"arg_named_like_other_param:src/runtime/node/path.rs" = 2
"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
Expand All @@ -69,7 +67,6 @@
"error_collapsed_to_bool:src/runtime/ffi/ffi_body.rs" = 1
"field_valid_only_when:src/runtime/cli/filter_run.rs" = 1
"field_valid_only_when:src/runtime/shell/builtin/rm.rs" = 1
"narrowed_two_ways:src/runtime/node/node_crypto_binding.rs" = 1
"parallel_vecs:src/runtime/api/html_rewriter.rs" = 1
"parallel_vecs:src/runtime/bake/dev_server/incremental_graph.rs" = 1
"reimplemented_helper:src/runtime/api/bun/Terminal.rs" = 1
Expand Down
64 changes: 43 additions & 21 deletions src/runtime/api/bun/h2_frame_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,24 @@ enum BatchSegment {
Ext { ptr: *const u8, len: u32 },
}

/// Flags for one `H2FrameParser::send_data` call.
#[derive(Clone, Copy)]
struct SendDataOptions {
/// End the stream after the payload: END_STREAM on the last DATA frame, or, while the
/// stream is waiting for trailers, an onWantTrailers dispatch instead.
Comment thread
robobun marked this conversation as resolved.
Resolved
close: bool,
/// Skip the HALF_CLOSED_LOCAL onStreamEnd dispatch: the synchronous caller (writeStream)
/// hands the settled state to JS via its return value instead of re-entering the VM
/// mid-host-call.
Comment thread
robobun marked this conversation as resolved.
Resolved
suppress_half_closed_local_dispatch: bool,
/// When the payload is handed to the socket without being queued (no flow-control /
/// socket backpressure), do not invoke the write callback here; report it as deferred so
/// the JS caller completes it asynchronously and a node Writable's `_write` callback never
/// settles synchronously inside `write()`. A queued payload keeps its callback with the
/// engine either way: it runs once the queued frames are flushed.
Comment thread
robobun marked this conversation as resolved.
Resolved
defer_write_callback: bool,
}

struct DispatchGuard<'a>(&'a Cell<u32>);

impl Drop for DispatchGuard<'_> {
Expand Down Expand Up @@ -7464,29 +7482,22 @@ 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 code the close tail settled on
/// (5 = HALF_CLOSED_LOCAL, 7 = CLOSED, 0 = no close-tail transition ran), and whether
/// `callback` was left for the caller to complete (see
/// `SendDataOptions::defer_write_callback`).
Comment thread
robobun marked this conversation as resolved.
Resolved
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({}, {}, {})",
Expand Down Expand Up @@ -7748,7 +7759,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)
}

Expand Down Expand Up @@ -8280,10 +8300,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
Expand Down
76 changes: 76 additions & 0 deletions test/js/node/http2/node-http2.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
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)));
const client = http2.connect(`http://127.0.0.1:${port}`);
client.on("error", lengths.reject);
const req = client.request({ ":path": "/" });
req.on("error", lengths.reject);
const body = new Promise(resolve => {
const chunks = [];
req.on("data", chunk => chunks.push(chunk));
req.on("end", () => resolve(Buffer.concat(chunks).toString()));
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
req.end();
expect(await lengths.promise).toEqual({ afterWrite: 5, afterCallback: 0 });
expect(await body).toBe("hello");
client.close();
} finally {
server.close();
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

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();
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)));
const client = http2.connect(`http://127.0.0.1:${port}`);
client.on("error", serverClose.reject);
const req = client.request({ ":path": "/" });
req.on("error", serverClose.reject);
const trailerEvents = [];
req.on("trailers", headers => trailerEvents.push(headers));
const body = new Promise(resolve => {
const chunks = [];
req.on("data", chunk => chunks.push(chunk));
req.on("end", () => resolve(Buffer.concat(chunks).toString()));
});
req.end();
expect(await body).toBe("OK");
expect(await serverClose.promise).toBe(0);
expect(trailerEvents).toEqual([]);
client.close();
} finally {
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
Expand Down
Loading