Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
7 changes: 5 additions & 2 deletions packages/bun-uws/src/HttpContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -718,9 +718,12 @@ struct HttpContext {
}
}

/* Should we close this connection after a response - and is this response really done? */
/* Should we close this connection after a response - and is this response really done?
* HTTP_NODE_SOCKET_ENDED: node:http socket.end() already promised the FIN, so shut
* down once the buffer has drained even if res.end() was never called. */
if (httpResponseData->shouldCloseConnection()) {
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) == 0) {
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) == 0
|| (httpResponseData->state & HttpResponseData<SSL>::HTTP_NODE_SOCKET_ENDED)) {
if (asyncSocket->getBufferedAmount() == 0) {

asyncSocket->shutdown();
Expand Down
6 changes: 6 additions & 0 deletions packages/bun-uws/src/HttpResponseData.h
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ struct HttpResponseData : AsyncSocketData<SSL>, HttpParser {
* into the shared word so the shared response-end path (internalEnd) never
* has to touch the node-only field. */
HTTP_NODE_HAS_RESPONSE_TRAILERS = 1 << 16,
/* node:http socket.end() deferred its FIN because response bytes were
* still buffered. onWritable shuts the socket down once the buffer has
* drained even when HTTP_RESPONSE_PENDING is still set (res.end() may
* never be called; in Node the shared Writable queue orders the FIN
* after every byte handed to res.write()). */
HTTP_NODE_SOCKET_ENDED = 1 << 17,

/* Bits that describe the connection rather than the response in flight.
* There is one HttpResponseData per socket, reused by every request on a
Expand Down
22 changes: 17 additions & 5 deletions src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

extern "C" void Bun__NodeHTTPResponse_setClosed(void* zigResponse);
extern "C" void Bun__NodeHTTPResponse_markTunneled(void* zigResponse);
extern "C" void Bun__NodeHTTPResponse_spillPendingPinnedWrite(void* zigResponse);
extern "C" void Bun__NodeHTTPResponse_onClose(void* zigResponse, JSC::EncodedJSValue jsValue);
extern "C" void us_socket_free_stream_buffer(us_socket_stream_buffer_t* streamBuffer);
extern "C" uint64_t uws_res_get_remote_address_info(void* res, const char** dest, int* port, bool* is_ipv6);
Expand Down Expand Up @@ -242,14 +243,19 @@ bool JSNodeHTTPServerSocket::isClosed() const
template<bool SSL>
static bool deferShutdownUntilResponseDrains(us_socket_t* socket)
{
if (reinterpret_cast<uWS::AsyncSocket<SSL>*>(socket)->getBufferedAmount() == 0) {
auto* asyncSocket = reinterpret_cast<uWS::AsyncSocket<SSL>*>(socket);
/* socket.end() can run inside HttpContext::onData's corked region (e.g. from
* a req 'data' listener); uncork so those bytes reach getBufferedAmount(). */
asyncSocket->uncork();
if (asyncSocket->getBufferedAmount() == 0) {
return false;
}
/* HttpContext<SSL>::onWritable shuts the socket down once the buffered
* response data has flushed and HTTP_CONNECTION_CLOSE is set, so the FIN
* is sequenced after the response bytes (like Node's destroySoon). */
/* HttpContext<SSL>::onWritable shuts the socket down once the buffer has
* flushed (like Node's destroySoon). HTTP_NODE_SOCKET_ENDED lets that gate
* fire even when res.end() never cleared HTTP_RESPONSE_PENDING. */
auto* httpResponseData = reinterpret_cast<uWS::HttpResponseData<SSL>*>(us_socket_ext(socket));
httpResponseData->state |= uWS::HttpResponseData<SSL>::HTTP_CONNECTION_CLOSE;
httpResponseData->state |= uWS::HttpResponseData<SSL>::HTTP_CONNECTION_CLOSE
| uWS::HttpResponseData<SSL>::HTTP_NODE_SOCKET_ENDED;
return true;
Comment thread
robobun marked this conversation as resolved.
Resolved
}

Expand All @@ -258,6 +264,12 @@ bool JSNodeHTTPServerSocket::shutdownAfterResponseDrains()
if (!socket || upgraded || us_socket_is_closed(socket) || us_socket_is_shut_down(socket)) {
return false;
}
/* A large res.write() that hit backpressure keeps its unsent tail pinned in
* the response (not in AsyncSocketData::buffer). Move it there before the
* getBufferedAmount() probe so the FIN is sequenced after those bytes. */
if (auto* res = currentResponseObject.get(); res != nullptr && res->m_ctx != nullptr) {
Bun__NodeHTTPResponse_spillPendingPinnedWrite(res->m_ctx);
}
if (is_ssl) {
return deferShutdownUntilResponseDrains<true>(socket);
}
Expand Down
8 changes: 8 additions & 0 deletions src/runtime/server/NodeHTTPResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1331,6 +1331,14 @@ impl NodeHTTPResponse {
self.update_flags(|f| f.insert(Flags::TUNNELED));
}

/// `socket.end()` is about to probe the uWS buffered amount to decide
/// whether the FIN can go out now; move any held zero-copy write tail
/// there first so it is counted (and so it drains ahead of the FIN).
#[uws::uws_callback(export = "Bun__NodeHTTPResponse_spillPendingPinnedWrite", no_catch)]
pub(crate) fn spill_pending_pinned_write_for_end(&self) {
self.spill_pending_pinned_write(self.server.global_this());
}

pub(crate) fn on_timeout(&self, _resp: uws::AnyResponse) {
scoped_log!(NodeHTTPResponse, "onTimeout");
self.handle_abort_or_timeout::<{ AbortEvent::Timeout }>(JSValue::ZERO);
Expand Down
69 changes: 69 additions & 0 deletions test/js/node/http/node-http-pinned-write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,75 @@ describe("node:http large Buffer writes are sent zero-copy", () => {
expect(exitCode).toBe(0);
});

// In Node res.write() and socket.end() share one Writable, so FIN is ordered
// after every queued byte. The pinned tail sits outside AsyncSocketData::buffer;
// socket.end() must spill it so the full body reaches the client before FIN.
describe.each([
// Chunked adds a hex size + CRLF around the payload (no 0 chunk, since
// res.end() was never called); Content-Length delivers exactly the payload.
["with Content-Length", { "Content-Length": String(RESIZABLE_CHUNK_SIZE) }, 0, "Connection: close\\r\\n"],
["chunked", {}, RESIZABLE_CHUNK_SIZE.toString(16).length + 4, "Connection: close\\r\\n"],
// Two pipelined keep-alive requests in one write: the second request must
// take the queued pipelined branch (HTTP_RESPONSE_PENDING left intact).
[
"pipelined keep-alive",
{ "Content-Length": String(RESIZABLE_CHUNK_SIZE) },
0,
"\\r\\nGET / HTTP/1.1\\r\\nHost: x\\r\\n",
],
] as const)(
"req.socket.end() without res.end() delivers the full pinned body (%s)",
(_name, extraHeaders, framingOverhead, trailer) => {
test.concurrent.skipIf(isWindows)("body reaches the client before FIN", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const http = require("node:http");
const net = require("node:net");
const { once } = require("node:events");
const CHUNK_SIZE = ${RESIZABLE_CHUNK_SIZE};
const payload = Buffer.alloc(CHUNK_SIZE, 0x61);
const server = http.createServer((req, res) => {
res.writeHead(200, ${JSON.stringify({ "Content-Type": "application/octet-stream", ...extraHeaders })});
res.write(payload);
req.socket.end();
});
await once(server.listen(0, "127.0.0.1"), "listening");
const socket = net.connect(server.address().port, "127.0.0.1");
await once(socket, "connect");
const chunks = [];
socket.on("data", c => chunks.push(c));
socket.on("error", () => {});
socket.write("GET / HTTP/1.1\\r\\nHost: x\\r\\n${trailer}\\r\\n");
await new Promise(r => socket.once("close", r));
const received = Buffer.concat(chunks);
const headerEnd = received.indexOf("\\r\\n\\r\\n");
const body = received.subarray(headerEnd + 4);
let as = 0;
for (let i = 0; i < body.length; i++) if (body[i] === 0x61) as++;
console.log(JSON.stringify({ bodyLength: body.length, as }));
server.close();
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const result = JSON.parse(stdout.trim());
expect({ bodyLength: result.bodyLength, as: result.as, exitCode, stderr }).toEqual({
bodyLength: RESIZABLE_CHUNK_SIZE + framingOverhead,
as: RESIZABLE_CHUNK_SIZE,
exitCode: 0,
stderr: expect.any(String),
});
});
},
);

test("a second write before drain releases the pin on the first buffer", async () => {
let detachedAfterSecondWrite: boolean | undefined;
const total = CHUNK_SIZE + 1024;
Expand Down
Loading