diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 46096c814092..964fe8b8b50f 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -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 * @@ -5904,11 +5899,19 @@ 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 close `close()`} 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 delivered duration is the requested value give or take 4 seconds. + * Pass `0` to disarm the timer. * - * 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; @@ -5925,19 +5928,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 `close` handler runs once the peer closes its side. + * + * 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(); * ``` */ @@ -6232,14 +6236,14 @@ declare module "bun" { readonly bytesWritten: number; /** - * Alias for `socket.end()`. Allows the socket to be used with `using` declarations - * for automatic resource management. + * Alias for {@link close `socket.close()`}. Allows the socket to be used with + * `using` declarations for automatic resource management. * @example * ```ts * async function processSocket() { * using socket = await Bun.connect({ ... }); * socket.write("Data"); - * // socket.end() is called automatically when exiting the scope + * // socket.close() is called automatically when exiting the scope * } * ``` */ @@ -6290,12 +6294,10 @@ declare module "bun" { upgradeTLS(options: TLSUpgradeOptions): [raw: Socket, tls: Socket]; /** - * Closes the socket. - * - * This is a wrapper around `end()` and `shutdown()`. + * Closes the socket immediately in both directions. * - * @see {@link end} - * @see {@link shutdown} + * For a graceful write-side half-close that keeps the read side open, + * use {@link end `end()`} or {@link shutdown `shutdown()`} instead. */ close(): void; diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 03ad37679853..3e316c83bbc6 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -1167,7 +1167,7 @@ function onconnection(err, clientHandle) { remotePort: _socket.remotePort, remoteFamily: _socket.remoteFamily || "IPv4", }; - clientHandle.end(); + clientHandle.close(); self.emit("drop", data); return; } @@ -1182,7 +1182,7 @@ function onconnection(err, clientHandle) { remoteFamily: _socket.remoteFamily || "IPv4", }; - clientHandle.end(); + clientHandle.close(); self.emit("drop", data); return; } diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 23bb15b833a0..ebd7f8c18b52 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -2981,7 +2981,9 @@ impl NewSocket { 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 } @@ -2989,14 +2991,6 @@ impl NewSocket { #[bun_jsc::host_fn(method)] pub fn flush(this: &Self, _global: &JSGlobalObject, _frame: &CallFrame) -> JsResult { 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); } @@ -3038,16 +3032,11 @@ impl NewSocket { pub fn shutdown( this: &Self, _global: &JSGlobalObject, - callframe: &CallFrame, + _callframe: &CallFrame, ) -> JsResult { 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) } diff --git a/src/runtime/socket/sockets.classes.ts b/src/runtime/socket/sockets.classes.ts index 2a2695e2359c..fd5d06e57ae5 100644 --- a/src/runtime/socket/sockets.classes.ts +++ b/src/runtime/socket/sockets.classes.ts @@ -162,7 +162,7 @@ function generate(ssl) { }, "@@dispose": { - fn: "end", + fn: "close", length: 0, }, diff --git a/test/js/bun/net/socket.test.ts b/test/js/bun/net/socket.test.ts index 8b0bfe27de99..a2cc2bbebbcb 100644 --- a/test/js/bun/net/socket.test.ts +++ b/test/js/bun/net/socket.test.ts @@ -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(); + + 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 }); + }); + } +});