Skip to content
14 changes: 14 additions & 0 deletions packages/bun-uws/src/App.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
// clang-format off


#include <algorithm>
#include <string>
#include <charconv>
#include <string_view>
Expand Down Expand Up @@ -389,6 +390,19 @@ struct TemplatedApp {
/* close_all() walks head_listen_sockets first, so listeners are closed
* here without us holding raw pointers to them across loop ticks. */
us_socket_group_close_all(httpContext->getSocketGroup());
/* Write out queued publish() messages and corked frames while the
* websocket fds are still open. onClose frees each subscriber without
* draining it and discards the cork buffer. */
if (topicTree) {
topicTree->drain();
}
LoopData *loopData = (LoopData *) us_loop_ext((us_loop_t *) Loop::get());
for (int slot = 0; slot < 2; slot++) {
auto *corked = (us_socket_t *) loopData->getCorkSlot(slot)->socket;
if (corked && std::find(webSocketGroups.begin(), webSocketGroups.end(), us_socket_group(corked)) != webSocketGroups.end()) {
((AsyncSocket<SSL> *) corked)->uncork();
}
}
for (us_socket_group_t *g : webSocketGroups) {
us_socket_group_close_all(g);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Expand Down
6 changes: 6 additions & 0 deletions packages/bun-uws/src/Loop.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ struct Loop {
return (LoopData *) us_loop_ext(loop);
}

/* What the next tick's pre handler would do: commit pub/sub batches and
* write out leftover corks. For a caller that will not tick again. */
void flushPendingWrites() {
preCb((us_loop_t *) this);
}

void addPostHandler(void *key, MoveOnlyFunction<void(Loop *)> &&handler) {
LoopData *loopData = (LoopData *) us_loop_ext((us_loop_t *) this);

Expand Down
24 changes: 22 additions & 2 deletions packages/bun-uws/src/WebSocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ struct WebSocket : AsyncSocket<SSL> {
using Super::getNativeHandle;

/* WebSocket close cannot be an alias to AsyncSocket::close since
* we need to check first if it was shut down by remote peer */
us_socket_t *close() {
* we need to check first if it was shut down by remote peer.
* flush = false drops what publish() queued and what a handler corked. An
* open handler that threw needs it: after a synchronous upgrade the cork
* still holds the 101, and that handshake must not complete. */
us_socket_t *close(bool flush = true) {
if (us_socket_is_closed((us_socket_t *) this)) {
return nullptr;
}
Expand All @@ -73,9 +76,26 @@ struct WebSocket : AsyncSocket<SSL> {
return nullptr;
}

if (flush) {
flushBeforeForcedClose();
}
return us_socket_close((us_socket_t *) this, 0, nullptr);
}

/* Write out what publish() queued for this socket and what a handler
* corked, while the fd is still open. onClose runs after the fd is gone:
* freeSubscriber there cannot write, and the cork buffer is discarded. */
void flushBeforeForcedClose() {
if (us_socket_is_closed((us_socket_t *) this)) {
return;
}
WebSocketData *webSocketData = (WebSocketData *) Super::getAsyncSocketData();
if (webSocketData->subscriber) {
getContextData()->topicTree->drain(webSocketData->subscriber);
}
Super::uncork();
}

enum SendStatus : int {
BACKPRESSURE,
SUCCESS,
Expand Down
2 changes: 2 additions & 0 deletions packages/bun-uws/src/WebSocketContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ struct WebSocketContext {
}

static void forceClose(WebSocketState<isServer> */*wState*/, void *s, std::string_view reason = {}) {
/* An earlier frame in this read may have sent or published already. */
((WebSocket<SSL, isServer, USERDATA> *) s)->flushBeforeForcedClose();
us_socket_close((us_socket_t *) s, (int) reason.length(), (void *) reason.data());
}

Expand Down
9 changes: 9 additions & 0 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2299,6 +2299,15 @@ impl VirtualMachine {
self.is_inside_deferred_task_queue.set(false);
}

// The loop will not tick again, so its pre handler never commits the
// `publish()` batches and corked frames the last turn left behind.
// Write them out now, while the sockets are still open. Not through
// `uws_loop()`: a spawnSync loop it can point at has no uWS LoopData.
Comment thread
robobun marked this conversation as resolved.
Resolved
if self.script_allowed() {
// SAFETY: `uws::Loop::get()` returns the live per-thread uws loop.
unsafe { (*uws::Loop::get()).flush_pending_writes() };
}

self.is_shutting_down = true;

// Node's FreeEnvironment sets `is_stopping` before `RunCleanup`: the
Expand Down
6 changes: 4 additions & 2 deletions src/runtime/server/ServerWebSocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,9 +472,11 @@ impl ServerWebSocket {
// we un-gracefully close the connection if there was an exception
// we don't want any event handlers to fire after this for anything other than error()
// https://github.com/oven-sh/bun/issues/1480
// (`close()` re-enters `on_close`, which skips its own
// (The close re-enters `on_close`, which skips its own
// accounting because the closed flag is already set.)
self.websocket().close();
// No flush: after a synchronous upgrade the cork still holds
// the 101, and a client whose open() threw must not see "open".
Comment thread
robobun marked this conversation as resolved.
Resolved
self.websocket().close_without_flush();
closed_here = true;
this_value.unprotect();
}
Expand Down
14 changes: 14 additions & 0 deletions src/uws_sys/Loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,14 @@ impl PosixLoop {
unsafe { c::us_internal_free_closed_sockets(self) };
}

/// Write out what the next tick's pre handler would have: queued
/// `publish()` batches and leftover corks. For the exit path, where no
/// tick follows.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn flush_pending_writes(&mut self) {
// SAFETY: self is a valid loop pointer
unsafe { c::uws_loop_flush_pending_writes(self) };
}

/// `us_socket_group_close_all()` on every group currently linked to this
/// loop — covers Listener/App-owned groups that `RareData`'s static field
/// list doesn't enumerate. Returns whether any group was linked.
Expand Down Expand Up @@ -454,6 +462,11 @@ impl WindowsLoop {
unsafe { c::us_internal_free_closed_sockets(self) };
}

pub fn flush_pending_writes(&mut self) {
// SAFETY: self is a valid loop pointer
unsafe { c::uws_loop_flush_pending_writes(self) };
}

pub fn close_all_groups(&mut self) -> bool {
// SAFETY: self is a valid loop pointer
unsafe { c::us_loop_close_all_groups(self) != 0 }
Expand Down Expand Up @@ -522,6 +535,7 @@ mod c {
#[cfg(windows)]
pub(super) fn uws_get_loop_with_native(native: *mut c_void) -> *mut WindowsLoop;
pub(super) fn uws_loop_date_header_timer_update(loop_: *mut Loop);
pub(super) fn uws_loop_flush_pending_writes(loop_: *mut Loop);
}
}
// Re-exported raw externs for cross-thread callers (e.g. bun_http's
Expand Down
14 changes: 12 additions & 2 deletions src/uws_sys/WebSocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,19 @@ impl AnyWebSocket {
ws.memory_cost(ssl)
}

/// Forced close. Writes out what `publish()` queued for this socket and
/// what a handler corked, then closes.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn close(self) {
let (ssl, ws) = self.split();
c::uws_ws_close(ssl, ws)
c::uws_ws_close(ssl, ws, true)
}

/// Forced close that drops the queued publishes and the cork buffer. After
/// a synchronous upgrade the cork still holds the 101 response, so this
/// close fails the handshake.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn close_without_flush(self) {
let (ssl, ws) = self.split();
c::uws_ws_close(ssl, ws, false)
}

pub fn send(self, message: &[u8], opcode: Opcode, compress: bool, fin: bool) -> SendStatus {
Expand Down Expand Up @@ -525,7 +535,7 @@ pub mod c {
behavior: *const WebSocketBehavior,
);
pub(crate) safe fn uws_ws_get_user_data(ssl: i32, ws: &mut RawWebSocket) -> *mut c_void;
pub(crate) safe fn uws_ws_close(ssl: i32, ws: &mut RawWebSocket);
pub(crate) safe fn uws_ws_close(ssl: i32, ws: &mut RawWebSocket, flush: bool);
pub(crate) fn uws_ws_send_with_options(
ssl: i32,
ws: *mut RawWebSocket,
Expand Down
10 changes: 7 additions & 3 deletions src/uws_sys/libuwsockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ extern "C"
loopData->updateDate();
}

void uws_loop_flush_pending_writes(us_loop_t *loop) {
((uWS::Loop *) loop)->flushPendingWrites();
}

uws_app_t *uws_create_app(int ssl, struct us_bun_socket_context_options_t options)
{
uWS::SocketContextOptions socket_context_options;
Expand Down Expand Up @@ -734,19 +738,19 @@ extern "C"
return *uws->getUserData();
}

void uws_ws_close(int ssl, uws_websocket_t *ws)
void uws_ws_close(int ssl, uws_websocket_t *ws, bool flush)
{
if (ssl)
{
TLSWebSocket *uws =
(TLSWebSocket *)ws;
uws->close();
uws->close(flush);
}
else
{
TCPWebSocket *uws =
(TCPWebSocket *)ws;
uws->close();
uws->close(flush);
}
}

Expand Down
Loading
Loading