Skip to content
Closed
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
41 changes: 23 additions & 18 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5890,11 +5890,6 @@ declare module "bun" {
*/
end(data?: string | BufferSource, byteOffset?: number, byteLength?: number): number;

/**
* Close the socket immediately
*/
end(): void;

/**
* Keep Bun's process alive at least until this socket is closed
*
Expand All @@ -5904,11 +5899,20 @@ declare module "bun" {
ref(): void;

/**
* Set a timeout until the socket automatically closes.
* Arm an inactivity timeout that invokes the `timeout` handler after roughly
* `seconds` seconds of no reads or writes on this socket.
*
* This is a **notification only**: Bun does not close the socket for you. If
* you want the socket to close on timeout, call {@link end `end()`} or
* {@link terminate `terminate()`} from the `timeout` handler. If no
* `timeout` handler is registered the timer is a no-op.
*
* To reset the timeout, call this function again.
* Timeouts are coalesced into a shared sweep that runs every 4 seconds, so
* the requested duration is rounded **up** to the next multiple of 4 seconds
* (e.g. `timeout(1)` through `timeout(4)` all fire at ~4 s, `timeout(5)`
* at ~8 s). Pass `0` to disarm the timer.
Comment thread
robobun marked this conversation as resolved.
Resolved
*
* When a timeout happens, the `timeout` callback is called and the socket is closed.
* This mirrors Node's `net.Socket#setTimeout`, which is also notify-only.
*/
timeout(seconds: number): void;

Expand All @@ -5925,19 +5929,20 @@ declare module "bun" {
terminate(): void;

/**
* Shuts down the write-half or both halves of the connection.
* This allows the socket to enter a half-closed state where it can still receive data
* but can no longer send data (`halfClose = true`), or close both read and write
* (`halfClose = false`, similar to `end()` but potentially more immediate depending on OS).
* Calls the `shutdown(2)` syscall internally.
* Half-closes the write side of the connection (sends a TCP FIN via
* `shutdown(fd, SHUT_WR)`).
*
* @param halfClose If `true`, only shuts down the write side (allows receiving). If `false` or omitted, shuts down both read and write. Defaults to `false`.
* After `shutdown()` no more data can be written, but the socket stays open
* for reading: the peer's reply is still delivered to the `data` handler
* and the peer's FIN to the `end`/`close` handlers.
Comment thread
robobun marked this conversation as resolved.
Resolved
*
* This is equivalent to {@link end `end()`} without a data argument.
*
* @param halfClose Ignored. Present for backwards compatibility; every
* call half-closes the write side regardless of this value.
* @example
* ```ts
* // Stop sending data, but allow receiving
* socket.shutdown(true);
*
* // Shutdown both reading and writing
* // Send FIN, keep receiving the peer's reply
* socket.shutdown();
* ```
*/
Expand Down
4 changes: 2 additions & 2 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,7 @@ function onconnection(err, clientHandle) {
remotePort: _socket.remotePort,
remoteFamily: _socket.remoteFamily || "IPv4",
};
clientHandle.end();
clientHandle.close();
self.emit("drop", data);
return;
}
Expand All @@ -1182,7 +1182,7 @@ function onconnection(err, clientHandle) {
remoteFamily: _socket.remoteFamily || "IPv4",
};

clientHandle.end();
clientHandle.close();
self.emit("drop", data);
return;
}
Expand Down
23 changes: 6 additions & 17 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2981,22 +2981,16 @@ impl<const SSL: bool> NewSocket<SSL> {
self.socket.get().flush();

if self.can_end_after_flush() {
self.mark_inactive();
// end() = flush + SHUT_WR; teardown runs via on_close once the peer FINs.
self.update_flags(|f| f.remove(Flags::END_AFTER_FLUSH));
self.socket.get().shutdown();
}
0
}

#[bun_jsc::host_fn(method)]
pub fn flush(this: &Self, _global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSValue> {
jsc::mark_binding!();
// `end()` → `internalFlush` → `markInactive` → `closeAndDetach(.normal)`
// detaches `this.socket` and, for TLS, defers the raw close until the
// peer's close_notify arrives — leaving `is_active` set so the eventual
// `onClose` can run `handlers.markInactive()`. Without this guard a
// follow-up `flush()` re-enters `markInactive`, sees the detached
// socket as closed, and decrements `active_connections` a second time;
// the deferred `onClose` then underflows it. Every other
// `internalFlush` caller already has this check.
if this.socket.get().is_detached() {
return Ok(JSValue::UNDEFINED);
}
Expand Down Expand Up @@ -3038,16 +3032,11 @@ impl<const SSL: bool> NewSocket<SSL> {
pub fn shutdown(
this: &Self,
_global: &JSGlobalObject,
callframe: &CallFrame,
_callframe: &CallFrame,
) -> JsResult<JSValue> {
jsc::mark_binding!();
let [arg] = callframe.arguments_as_array::<1>();
if callframe.arguments_count() > 0 && arg.to_boolean() {
this.socket.get().shutdown_read();
} else {
this.socket.get().shutdown();
}

// `halfClose` is accepted and ignored; every form is SHUT_WR.
this.socket.get().shutdown();
Ok(JSValue::UNDEFINED)
}

Expand Down
73 changes: 73 additions & 0 deletions test/js/bun/net/socket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3330,3 +3330,76 @@ describe("TLS handshake callback throw", () => {
}
});
});

// end(), shutdown(), shutdown(false) and shutdown(true) all half-close the
// write side (SHUT_WR / TCP FIN) and leave the socket readable. Prior behavior
// mapped end() to close(2) and shutdown(true) to SHUT_RD, so a peer's reply
// after the half-close was lost. Pin the observable contract: the client can
// still receive the server's full reply after each call.
describe("Socket.end() / Socket.shutdown() are a write-side half-close", () => {
// Small enough to fit in one non-blocking send() on every target's loopback
// buffer so the server's write-on-end never needs a drain cycle.
const PAYLOAD = Buffer.alloc(16 * 1024, 0x61);

type Call = "end()" | "end(data)" | "shutdown()" | "shutdown(false)" | "shutdown(true)";

async function halfClose(call: Call) {
let received = 0;
let writeAfter = 0;
let readyState: number | undefined;
const { promise, resolve } = Promise.withResolvers<void>();

using server = Bun.listen({
hostname: "127.0.0.1",
port: 0,
allowHalfOpen: true,
socket: {
data() {},
// Client's FIN arrived: reply, then half-close back.
end(socket) {
socket.write(PAYLOAD);
socket.end();
},
close() {},
},
});

await Bun.connect({
hostname: "127.0.0.1",
port: server.port,
socket: {
open(socket) {
if (call === "end(data)") socket.end("hi");
else {
socket.write("hi");
if (call === "end()") socket.end();
else if (call === "shutdown()") socket.shutdown();
else if (call === "shutdown(false)") socket.shutdown(false);
else socket.shutdown(true);
}
readyState = socket.readyState;
writeAfter = socket.write("x");
},
data(_socket, chunk) {
received += chunk.length;
},
end() {},
close() {
resolve();
},
},
});

await promise;
return { received, writeAfter, readyState };
}

for (const call of ["end()", "end(data)", "shutdown()", "shutdown(false)", "shutdown(true)"] as const) {
it.concurrent(`${call} sends FIN and keeps the read side open`, async () => {
// readyState 1: socket is still established (not detached).
// writeAfter -1: further writes on the half-closed side are rejected.
// received: the full reply made it through the still-open read side.
expect(await halfClose(call)).toEqual({ received: PAYLOAD.length, writeAfter: -1, readyState: 1 });
});
}
});
Loading