Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
20 changes: 17 additions & 3 deletions src/js/node/http2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2050,6 +2050,9 @@
// The native side fully closed and freed the stream (state 7 delivered): there is
// nothing left to send on the wire for it.
NativeClosed = 1 << 6, // 1000000 = 64
// respond() is ending the writable side ahead of a HEADERS frame that carries
// END_STREAM, so `_final` must not write an empty DATA frame of its own.
EndStreamOnHeaders = 1 << 7, // 10000000 = 128
}
function markWritableDone(stream: Http2Stream) {
const _final = stream[bunHTTP2StreamFinal];
Expand Down Expand Up @@ -2421,6 +2424,13 @@
const native = session[bunHTTP2Native];
if (native) {
this[bunHTTP2StreamStatus] |= StreamState.FinalCalled;
// respond() is about to submit a HEADERS frame carrying END_STREAM, so there is no DATA
// frame left to write. Settle now, like node's _final does for this case; 'finish' is
// queued on the next tick, after request() has put the frame on the wire.
if ((status & StreamState.EndStreamOnHeaders) !== 0) {
callback();
return;
}
// When waitForTrailers is active, writing an empty DATA frame with
// close=true emits a bare empty DATA frame (flags=0) to the wire
// before the trailer/noTrailers path runs, which then emits ANOTHER
Expand Down Expand Up @@ -3116,6 +3126,13 @@
}

const wireHeaders = rawHeadersList !== null ? rawHeadersList : headers;
if (endStream) {
// node ends the writable side before submitting the HEADERS frame. request() below can
// close an already half-closed stream and destroy it synchronously, and _destroy reads a
// still-open writable side as a client abort - ending first keeps 'aborted' from firing.
this[bunHTTP2StreamStatus] |= StreamState.EndStreamOnHeaders;
this.end();
}

Check warning on line 3135 in src/js/node/http2.ts

View check run for this annotation

Claude / Claude Code Review

respond() ends writable side before native header validation

Moving `this.end()` before native `request()` means header-validation errors that only native `request()` throws (e.g. `ERR_HTTP2_INVALID_PSEUDOHEADER` for `:path` in a response, `ERR_INVALID_HTTP_TOKEN`, `ERR_HTTP2_INVALID_HEADER_VALUE`) now surface *after* the writable side is already ended. If a handler catches such an error from a body-less `respond()` (204/205/304/HEAD/`endStream:true`) and retries with e.g. `respond({':status':500}); stream.end();`, the second `end()` no-ops on the `EndedC
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
if (typeof options === "undefined") {
session[bunHTTP2Native]?.request(this.id, undefined, wireHeaders, sensitiveNames);
} else {
Expand All @@ -3137,9 +3154,6 @@
onServerStreamFinishChannel.publish({ stream: this, headers, flags: 0 });
}
this[bunHTTP2Headers] = headers;
if (endStream) {
this.end();
}

return;
}
Expand Down
92 changes: 92 additions & 0 deletions test/js/node/http2/node-http2.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3186,3 +3186,95 @@ it("http2 allowHTTP1 fallback omits the Connection header on a close-delimited r
server.close();
}
});

// Collects the server stream's lifecycle events for one request, plus `stream.aborted` as read
// from the 'close' handler. 'end' is filtered out: bun and node disagree on whether it lands
// before or after 'finish', which is unrelated to what these tests assert.
async function serverStreamLifecycle(onStream, requestHeaders = { ":path": "/" }) {
const events = [];
let aborted = null;
const { promise: streamClosed, resolve: streamDidClose } = Promise.withResolvers();

const server = http2.createServer();
server.on("stream", stream => {
stream.on("aborted", () => events.push("aborted"));
stream.on("finish", () => events.push("finish"));
stream.on("close", () => {
aborted = stream.aborted;
events.push("close");
streamDidClose();
});
onStream(stream);
});

await new Promise(resolve => server.listen(0, resolve));
const client = http2.connect(`http://localhost:${server.address().port}`);
client.on("error", () => {});
try {
const req = client.request(requestHeaders);
const responseHeaders = await new Promise((resolve, reject) => {
req.on("error", reject);
req.on("response", resolve);
req.end();
});
const body = [];
req.on("data", chunk => body.push(chunk));
await new Promise((resolve, reject) => {
req.on("error", reject);
req.on("end", resolve);
});
await streamClosed;
return { events, aborted, status: responseHeaders[":status"], body: Buffer.concat(body).toString() };
} finally {
client.close();
server.close();
}
}

it("http2 respondWithFile statCheck returning false does not emit a spurious 'aborted'", async () => {
// The documented statCheck veto: reply 304 from a cache validator and cancel the file send.
// Node treats that as a completed response, so no 'aborted' fires and stream.aborted stays false.
const result = await serverStreamLifecycle(stream => {
stream.respondWithFile(
import.meta.path,
{ "content-type": "text/plain" },
{
statCheck() {
stream.respond({ ":status": 304 });
stream.end();
return false;
},
},
);
});

expect(result).toEqual({ events: ["finish", "close"], aborted: false, status: 304, body: "" });
});

it("http2 server respond() with END_STREAM after the request body does not emit a spurious 'aborted'", async () => {
// Any respond() whose HEADERS frame carries END_STREAM (204/205/304, HEAD, endStream: true)
// fully closes a stream whose peer already half-closed. That is a completed response, so the
// writable side must be ended before the frame is submitted or the teardown looks like an abort.
const cases = [
{ name: "304", status: 304, respond: stream => stream.respond({ ":status": 304 }) },
{ name: "204", status: 204, respond: stream => stream.respond({ ":status": 204 }) },
{ name: "205", status: 205, respond: stream => stream.respond({ ":status": 205 }) },
{ name: "endStream", status: 200, respond: stream => stream.respond({ ":status": 200 }, { endStream: true }) },
{ name: "head", status: 200, respond: stream => stream.respond({ ":status": 200 }), method: "HEAD" },
];

const results = [];
for (const { name, respond, method } of cases) {
// Respond once the request body is fully received, which is when the stream is already
// half-closed by the peer and submitting END_STREAM closes it outright.
const { events, aborted, status, body } = await serverStreamLifecycle(
stream => stream.on("end", () => respond(stream)),
method ? { ":path": "/", ":method": method } : { ":path": "/" },
);
results.push({ name, events, aborted, status, body });
}

expect(results).toEqual(
cases.map(({ name, status }) => ({ name, events: ["finish", "close"], aborted: false, status, body: "" })),
);
});
Loading