From 76202fff9e9edc2170c67155ddb54affa924e894 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Thu, 13 Aug 2026 19:26:44 +0100 Subject: [PATCH 1/6] fix(lib-rt-core): stop a websocket handler blocking its connection A message was handled inline in the loop that reads frames, so nothing was read while a handler ran. The application heartbeat is answered from that same loop and the protocol level one is only answered when the stream is polled, so neither reached a client waiting on them, and a close frame went unnoticed. A client with a ten second heartbeat and a handler taking longer than that concludes the connection is dead and reconnects, tearing down work still in progress. The test added here fails before the change, waiting three seconds for a pong that never arrives while a handler is running. Messages now go to a worker for the connection through a bounded channel, so reading never waits for handling. The worker takes one message at a time, because a WebSocket delivers frames in order and an application may depend on being given them that way; the point is only that reading does not wait, not that handling becomes concurrent. The read loop closes the channel and waits for the worker before firing the disconnect handler, so it runs after the messages that came before it rather than alongside them, and the worker reports whether it has already fired it for a close frame it saw in sequence. A worker that decides the connection is finished closes the socket, which is what wakes the read loop. The channel is bounded, so a client that outruns its own handlers is pushed back on rather than growing a queue without limit. That does mean a flood stalls the heartbeat again, which is the intended answer to a flood and a different situation from the one slow handler this fixes. Co-Authored-By: Claude Opus 5 (1M context) --- libs/runtime/core/src/consts.rs | 10 ++ libs/runtime/core/src/websocket.rs | 90 ++++++++++++--- .../runtime/core/tests/ipc_end_to_end_test.rs | 103 ++++++++++++++++++ 3 files changed, 187 insertions(+), 16 deletions(-) diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index 4f026988..a15bcd74 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -97,6 +97,16 @@ pub const DEFAULT_DRAIN_TIMEOUT_SECS: u64 = 30; // hints that arrive too late to be worth anything. pub const CANCELLATION_BUFFER: usize = 256; +// How many messages may be waiting to be processed for one WebSocket connection +// before its read loop waits for room. +// +// Messages are handled off the read loop so that a slow handler cannot stop the +// connection answering heartbeats or noticing a close. This bounds how far a +// client can run ahead of its own handlers before it is pushed back on, which +// is a different situation from one handler being slow and deserves the +// backpressure. +pub const WS_CONNECTION_WORK_BUFFER: usize = 64; + // How many dispatcher commands may be queued before a handler stream waits. // Commands are small and are drained by a single task, so this only needs to // absorb bursts of results arriving together. diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 5e634e5d..30713428 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -31,7 +31,11 @@ use celerity_ws_registry::registry::WebSocketConnRegistry; use nanoid::nanoid; use serde::{Deserialize, Serialize}; use serde_json::Value; -use tokio::{sync::Mutex, time::sleep}; +use tokio::{ + sync::{mpsc, Mutex}, + task::JoinHandle, + time::sleep, +}; use tracing::{debug, error, field, info, info_span, warn, Instrument}; use crate::{ @@ -44,6 +48,7 @@ use crate::{ CELERITY_WS_CAPABILITIES_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, CELERITY_WS_DEFAULT_MESSAGE_HANDLER_ROUTE, CELERITY_WS_DISCONNECT_HANDLER_ROUTE, CELERITY_WS_FORBIDDEN_ERROR_CODE, CELERITY_WS_UNAUTHORISED_ERROR_CODE, + WS_CONNECTION_WORK_BUFFER, }, errors::WebSocketsMessageError, request::{HttpProtocolVersion, RequestId}, @@ -325,6 +330,25 @@ async fn handle_socket( return; } + // Messages are processed off this loop, one at a time, by a worker for + // this connection. Sequentially, because a WebSocket delivers frames in + // order and an application may depend on being given them that way; + // the point here is only that reading does not wait for handling. + // + // Bounded, so a client that outruns its handlers is pushed back on + // rather than growing a queue without limit. Once the buffer is full + // this loop does wait, which is the intended answer to a flood, and a + // different situation from one slow handler. + let (work_tx, work_rx) = mpsc::channel::<(Message, WebSocketRequestContext)>( + WS_CONNECTION_WORK_BUFFER, + ); + let worker = spawn_message_worker( + work_rx, + socket_ref.clone(), + connection_id.clone(), + state.clone(), + ); + let mut connection_alive = true; while connection_alive { // Wait some time before acquiring the lock again to allow other tasks to write @@ -358,8 +382,6 @@ async fn handle_socket( request_ctx.auth_data = Some(data); } AuthMessageResult::Failed => { - state.connections.remove_connection(connection_id.clone()); - ws_connections_counter().add(-1, &[]); connection_alive = false; } AuthMessageResult::NotAuthMessage => { @@ -374,30 +396,38 @@ async fn handle_socket( } } } else { - // Release lock before processing to allow other tasks - // (e.g. cluster relay) to write to the socket. + // Release the lock before handing the message on, so other + // tasks (a cluster relay, say) can write to the socket. drop(acquired_socket); - if process_message(msg, connection_id.clone(), request_ctx.clone(), &state) - .await - .is_break() - { - state.connections.remove_connection(connection_id.clone()); - ws_connections_counter().add(-1, &[]); + // Handed to the worker rather than run here. A handler that + // takes a while must not stop this loop reading, or the + // heartbeat above goes unanswered and a close frame goes + // unnoticed, and the client concludes the connection is + // dead while its work is still in progress. + if work_tx.send((msg, request_ctx.clone())).await.is_err() { connection_alive = false; } } } else { // recv() returned None — the underlying connection was dropped // without a WebSocket close handshake (e.g. TCP reset, client - // killed). Fire the disconnect handler so the application can - // clean up connection state. + // killed). info!("connection lost, client {connection_id} disconnected without close frame"); - let _ = on_disconnect(connection_id.clone(), &state, &request_ctx).await; - state.connections.remove_connection(connection_id.clone()); - ws_connections_counter().add(-1, &[]); connection_alive = false; } } + + // Closing the channel ends the worker once it has finished whatever it + // was given, so the disconnect handler runs after the messages that + // preceded it rather than alongside them. + drop(work_tx); + let disconnect_handled = worker.await.unwrap_or(false); + + if !disconnect_handled { + let _ = on_disconnect(connection_id.clone(), &state, &request_ctx).await; + } + state.connections.remove_connection(connection_id.clone()); + ws_connections_counter().add(-1, &[]); } .instrument(info_span!("websocket_connection", connection_id = %connection_id)) .await @@ -550,6 +580,34 @@ fn create_connect_message( } } +/// Runs a connection's messages, one at a time, off its read loop. +/// +/// Returns whether the disconnect handler has already been fired, which happens +/// when the client sent a close frame and the worker saw it in sequence. The +/// read loop fires it otherwise, for a connection that simply went away. +fn spawn_message_worker( + mut work_rx: mpsc::Receiver<(Message, WebSocketRequestContext)>, + socket_ref: Arc>, + connection_id: String, + state: WebSocketAppState, +) -> JoinHandle { + tokio::spawn(async move { + while let Some((message, request_ctx)) = work_rx.recv().await { + if process_message(message, connection_id.clone(), request_ctx, &state) + .await + .is_break() + { + // The connection is finished, and the read loop is waiting on a + // socket that may never produce anything again. Closing it is + // what wakes the loop so the connection can be torn down. + close_connection(socket_ref.clone()).await; + return true; + } + } + false + }) +} + async fn on_disconnect( connection_id: String, state: &WebSocketAppState, diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index baf803eb..dc69f7ba 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1061,6 +1061,109 @@ async fn routes_a_websocket_message_to_a_handler_over_the_stream() { let _ = tokio::fs::remove_file(&socket).await; } +#[test_log::test(tokio::test)] +async fn answers_heartbeats_while_a_handler_is_still_running() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-heartbeat", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + // Withhold every result, standing in for a handler that takes a while. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + // Once this arrives the handler is running and has not answered. + handler + .next_dispatch() + .await + .expect("the message should reach the handler"); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "ping": true }).to_string(), + )) + .await + .unwrap(); + + // A client whose heartbeat goes unanswered concludes the connection is + // dead and reconnects, tearing down work that is still in progress. The + // handler's own timeout is far longer than any heartbeat interval, so the + // pong cannot wait on it. + let pong = tokio::time::timeout(Duration::from_secs(3), async { + while let Some(Ok(message)) = socket_conn.next().await { + if let tokio_tungstenite::tungstenite::Message::Text(text) = message { + if let Ok(value) = serde_json::from_str::(&text) { + if value.get("pong") == Some(&serde_json::Value::Bool(true)) { + return true; + } + } + } + } + false + }) + .await; + + assert_eq!( + pong, + Ok(true), + "the heartbeat should be answered while the handler is still running" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn keeps_messages_from_one_connection_in_order() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-order", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + for index in 0..5 { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "index": index } }).to_string(), + )) + .await + .unwrap(); + } + + // Handling messages off the read loop must not reorder them: a WebSocket + // delivers frames in order and an application may depend on being given + // them that way. + let mut seen = Vec::new(); + for _ in 0..5 { + let dispatch = handler + .next_dispatch() + .await + .expect("every message should reach the handler"); + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + let body: serde_json::Value = serde_json::from_slice(&message.message).unwrap(); + seen.push(body["data"]["index"].as_i64().unwrap()); + } + assert_eq!(seen, vec![0, 1, 2, 3, 4]); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} + #[test_log::test(tokio::test)] async fn carries_a_binary_websocket_frame_without_corrupting_it() { let (_app, addr, socket) = start_runtime( From 59bd51a2bf58c97320a92f1e8d434c3d9493dbf3 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sat, 15 Aug 2026 10:00:21 +0100 Subject: [PATCH 2/6] fix(lib-rt-core): stop a websocket connection waiting on a lock to read Reading a connection held a lock over the whole socket, which anything sending to that connection had to wait behind. The read loop then slept ten milliseconds on every pass so senders could get a turn, which capped one connection at about a hundred messages a second whatever its handlers were doing. The socket is now split, so the registry holds only the sending half and the receiving half stays with the task reading it. Reading takes no lock at all, the sleep is gone with the reason for it, and a sender can no longer end up waiting behind a read that is itself waiting on a client. A connection whose client outruns its handlers is now shed rather than left to stall. The read loop waits a bounded moment for room and then closes with a retry hint, which is the server initiated backoff the protocol already describes. Waiting in silence is what makes a client give up on a connection it could have kept, since the heartbeat is answered on this loop and a client that hears nothing concludes the connection is dead. Messages are still handled one at a time. That is how they were handled before, when they ran inline in the read loop, and a fix for the loop stalling should not quietly start running an application's messages in parallel. Ordering is not a promise the platform makes, a serverless target runs a function per message with nothing sequencing them, so the test that covers it says what this runtime does rather than what applications may rely on. One registry test asserted that a handler's own lost message notification arrives before the registry's. It only did so because the read loop held the socket while it worked, so both are now accepted in either order. --- libs/runtime/core/src/consts.rs | 19 +++ libs/runtime/core/src/websocket.rs | 110 ++++++++---- .../runtime/core/tests/ipc_end_to_end_test.rs | 117 ++++++++++++- libs/runtime/ws/ws-registry/Cargo.toml | 1 + libs/runtime/ws/ws-registry/src/registry.rs | 158 ++++++++++-------- 5 files changed, 300 insertions(+), 105 deletions(-) diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index a15bcd74..ce63d1bd 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -107,6 +107,25 @@ pub const CANCELLATION_BUFFER: usize = 256; // backpressure. pub const WS_CONNECTION_WORK_BUFFER: usize = 64; +// How long a connection's read loop waits for room in that buffer before it +// gives up on the client and closes the connection. +// +// The read loop answers heartbeats, so any time spent waiting here is time the +// connection appears dead to its client. The protocol's default heartbeat +// timeout is 5 seconds, so this stays well inside it: a burst gets a moment to +// drain, and a client that is genuinely outrunning its handlers is shed long +// before it would have concluded the connection was gone. +pub const WS_CONNECTION_WORK_SHED_GRACE_MS: u64 = 1_000; + +// The `retryAfter` hint sent in the close frame when a connection is shed for +// outrunning its handlers. +// +// The protocol has a server-initiated backoff, so the client waits at least this +// long before reconnecting rather than coming straight back into the same +// saturation. Clients take the greater of this and their own backoff and add +// their own jitter. +pub const WS_CONNECTION_SATURATED_RETRY_AFTER_MS: u64 = 5_000; + // How many dispatcher commands may be queued before a handler stream waits. // Commands are small and are drained by a single task, so this only needs to // absorb bursts of results arriving together. diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 30713428..feef106d 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -10,7 +10,7 @@ use std::{ use async_trait::async_trait; use axum::{ extract::{ - ws::{CloseFrame, Message, WebSocket}, + ws::{close_code, CloseFrame, Message, WebSocket}, FromRequestParts, Request, State, WebSocketUpgrade, }, http::{HeaderMap, StatusCode}, @@ -27,14 +27,14 @@ use celerity_helpers::{ http::ResourceStore, request::{headers_to_hashmap, query_from_uri}, }; -use celerity_ws_registry::registry::WebSocketConnRegistry; +use celerity_ws_registry::registry::{WebSocketConnRegistry, WebSocketConnSender}; +use futures::{SinkExt, StreamExt}; use nanoid::nanoid; use serde::{Deserialize, Serialize}; use serde_json::Value; use tokio::{ - sync::{mpsc, Mutex}, + sync::{mpsc, mpsc::error::SendTimeoutError, Mutex}, task::JoinHandle, - time::sleep, }; use tracing::{debug, error, field, info, info_span, warn, Instrument}; @@ -48,7 +48,8 @@ use crate::{ CELERITY_WS_CAPABILITIES_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, CELERITY_WS_DEFAULT_MESSAGE_HANDLER_ROUTE, CELERITY_WS_DISCONNECT_HANDLER_ROUTE, CELERITY_WS_FORBIDDEN_ERROR_CODE, CELERITY_WS_UNAUTHORISED_ERROR_CODE, - WS_CONNECTION_WORK_BUFFER, + WS_CONNECTION_SATURATED_RETRY_AFTER_MS, WS_CONNECTION_WORK_BUFFER, + WS_CONNECTION_WORK_SHED_GRACE_MS, }, errors::WebSocketsMessageError, request::{HttpProtocolVersion, RequestId}, @@ -243,7 +244,13 @@ async fn handle_socket( mut request_ctx: WebSocketRequestContext, state: WebSocketAppState, ) { - let socket_ref = Arc::new(Mutex::new(socket)); + // Split so that reading and writing are owned separately. Only the sending + // half is shared, which is all anything other than this task ever needs, + // and the receiving half stays here. Reading therefore never holds a lock, + // so a task sending to this connection cannot delay it and it cannot delay + // them. + let (socket_tx, mut socket_rx) = socket.split(); + let socket_ref = Arc::new(Mutex::new(socket_tx)); async { info!("websocket connection received: {}", connection_id); @@ -331,9 +338,13 @@ async fn handle_socket( } // Messages are processed off this loop, one at a time, by a worker for - // this connection. Sequentially, because a WebSocket delivers frames in - // order and an application may depend on being given them that way; - // the point here is only that reading does not wait for handling. + // this connection. One at a time because that is how they were handled + // before, inline in this loop, and a fix for the loop stalling should + // not quietly start running an application's messages in parallel. + // Ordering is not something the platform promises, a serverless target + // runs a function per message with nothing between them, so this is + // about leaving behaviour alone rather than a guarantee being made. + // The point here is only that reading no longer waits for handling. // // Bounded, so a client that outruns its handlers is pushed back on // rather than growing a queue without limit. Once the buffer is full @@ -351,17 +362,12 @@ async fn handle_socket( let mut connection_alive = true; while connection_alive { - // Wait some time before acquiring the lock again to allow other tasks to write - // to the socket. (i.e. a message received from another node in the cluster) - sleep(Duration::from_millis(10)).await; - let mut acquired_socket = socket_ref.lock().await; - - if let Some(Ok(msg)) = acquired_socket.recv().await { + if let Some(Ok(msg)) = socket_rx.next().await { // Handle Celerity application-level heartbeat pings before // route resolution. These are distinct from WebSocket protocol-level // Ping frames (handled by tungstenite automatically). if let Some(pong) = detect_heartbeat_ping(&msg) { - let _ = acquired_socket.send(pong).await; + let _ = socket_ref.lock().await.send(pong).await; continue; } @@ -373,7 +379,7 @@ async fn handle_socket( &connection_id, &state, &request_ctx, - &mut acquired_socket, + &mut *socket_ref.lock().await, ) .await { @@ -392,20 +398,49 @@ async fn handle_socket( } }) .to_string(); - let _ = acquired_socket.send(Message::Text(reject.into())).await; + let _ = socket_ref + .lock() + .await + .send(Message::Text(reject.into())) + .await; } } } else { - // Release the lock before handing the message on, so other - // tasks (a cluster relay, say) can write to the socket. - drop(acquired_socket); // Handed to the worker rather than run here. A handler that // takes a while must not stop this loop reading, or the // heartbeat above goes unanswered and a close frame goes // unnoticed, and the client concludes the connection is // dead while its work is still in progress. - if work_tx.send((msg, request_ctx.clone())).await.is_err() { - connection_alive = false; + // + // The wait is bounded. A brief burst is absorbed by the + // buffer and by this grace, but a client that stays ahead + // of its handlers for longer than this is not going to be + // served by waiting for it in silence, since waiting is + // what stops the heartbeat being answered. It is shed + // instead, with a hint for when to come back. + match work_tx + .send_timeout( + (msg, request_ctx.clone()), + Duration::from_millis(WS_CONNECTION_WORK_SHED_GRACE_MS), + ) + .await + { + Ok(()) => {} + Err(SendTimeoutError::Timeout(_)) => { + warn!( + "client {connection_id} is sending faster than its handlers can \ + keep up, closing the connection with a retry hint" + ); + close_with_retry_after( + socket_ref.clone(), + WS_CONNECTION_SATURATED_RETRY_AFTER_MS, + ) + .await; + connection_alive = false; + } + Err(SendTimeoutError::Closed(_)) => { + connection_alive = false; + } } } } else { @@ -434,7 +469,7 @@ async fn handle_socket( } async fn authenticate_connection( - socket_ref: Arc>, + socket_ref: Arc>, state: &WebSocketAppState, request_ctx: &WebSocketRequestContext, ) -> ControlFlow<(), serde_json::Value> { @@ -526,7 +561,7 @@ async fn authenticate_connection( } async fn on_connect( - socket_ref: Arc>, + socket_ref: Arc>, connection_id: String, state: &WebSocketAppState, request_ctx: &WebSocketRequestContext, @@ -587,7 +622,7 @@ fn create_connect_message( /// read loop fires it otherwise, for a connection that simply went away. fn spawn_message_worker( mut work_rx: mpsc::Receiver<(Message, WebSocketRequestContext)>, - socket_ref: Arc>, + socket_ref: Arc>, connection_id: String, state: WebSocketAppState, ) -> JoinHandle { @@ -699,7 +734,7 @@ impl Display for ValidateAuthError { } async fn handle_validate_auth_on_connect_error( - socket_ref: Arc>, + socket_ref: Arc>, validate_error: ValidateAuthError, token_type: &str, ) -> ControlFlow<(), serde_json::Value> { @@ -774,7 +809,7 @@ async fn handle_auth_message( connection_id: &str, state: &WebSocketAppState, request_ctx: &WebSocketRequestContext, - socket: &mut WebSocket, + socket: &mut WebSocketConnSender, ) -> AuthMessageResult { let text = match msg { Message::Text(t) => t.to_string(), @@ -1353,19 +1388,34 @@ fn check_cors_origin( // Per RFC 6455 §4.1, browser clients MUST send the Origin header // on WebSocket upgrade requests; non-browser clients MAY omit it. // A missing Origin header therefore indicates a server-side client - // (CLI tool, SDK, service-to-service) — allow the connection. + // (CLI tool, SDK, service-to-service) so allow the connection. Ok(()) } } } -async fn close_connection(socket_ref: Arc>) { +async fn close_connection(socket_ref: Arc>) { let mut socket = socket_ref.lock().await; if let Err(err) = socket.send(Message::Close(None)).await { error!("failed to send close frame to client: {err}"); } } +/// Closes a connection with the protocol's server-initiated backoff hint, so +/// the client waits before reconnecting rather than returning immediately into +/// whatever made the runtime shed it. +async fn close_with_retry_after(socket_ref: Arc>, retry_after_ms: u64) { + let reason = serde_json::json!({ "retryAfter": retry_after_ms }).to_string(); + let frame = CloseFrame { + code: close_code::AGAIN, + reason: reason.into(), + }; + let mut socket = socket_ref.lock().await; + if let Err(err) = socket.send(Message::Close(Some(frame))).await { + error!("failed to send close frame to client: {err}"); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index dc69f7ba..132e343f 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1122,7 +1122,110 @@ async fn answers_heartbeats_while_a_handler_is_still_running() { } #[test_log::test(tokio::test)] -async fn keeps_messages_from_one_connection_in_order() { +async fn sheds_a_connection_that_outruns_its_handlers_with_a_retry_hint() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-saturate", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + // Answer nothing, so the worker is stuck on the first message and every + // message after it piles up behind it. + let _handler = HandlerStub::attach(&socket, |_| None).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + // Comfortably more than the buffer holds, so the read loop reaches the + // point where it would otherwise wait in silence. + for index in 0..256 { + if socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "index": index } }).to_string(), + )) + .await + .is_err() + { + // The runtime shed the connection part way through, which is the + // behaviour under test. + break; + } + } + + // Stalling in silence is what makes a client give up on a connection it + // could have kept. Closing says the same thing in a way the client can act + // on, and the hint stops it returning straight into the same saturation. + let close = tokio::time::timeout(Duration::from_secs(10), async { + while let Some(Ok(message)) = socket_conn.next().await { + if let tokio_tungstenite::tungstenite::Message::Close(frame) = message { + return frame; + } + } + None + }) + .await + .expect("the runtime should close the connection rather than stall in silence"); + + let frame = close.expect("the close should carry a frame rather than be bare"); + assert_eq!( + u16::from(frame.code), + 1013, + "expected a try again later code" + ); + let reason: serde_json::Value = + serde_json::from_str(&frame.reason).expect("the reason should carry the retry hint"); + assert!( + reason["retryAfter"].as_u64().is_some_and(|ms| ms > 0), + "expected a retryAfter hint, got {reason}" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn reads_faster_than_one_message_every_ten_milliseconds() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-throughput", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + // The read loop used to sleep 10ms per message to yield a lock it held + // across every read, capping one connection at about 100 messages a + // second whatever the handlers did. Reading no longer takes that lock, so + // 50 messages must not take the 500ms that cap would have cost. + let started = tokio::time::Instant::now(); + for index in 0..50 { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "index": index } }).to_string(), + )) + .await + .unwrap(); + } + for _ in 0..50 { + handler + .next_dispatch() + .await + .expect("every message should reach the handler"); + } + let elapsed = started.elapsed(); + + assert!( + elapsed < Duration::from_millis(400), + "50 messages took {elapsed:?}, which suggests the read loop is still rate limited" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn does_not_reorder_messages_when_handling_them_off_the_read_loop() { let (_app, addr, socket) = start_runtime( "ipc-ws-order", "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", @@ -1143,9 +1246,15 @@ async fn keeps_messages_from_one_connection_in_order() { .unwrap(); } - // Handling messages off the read loop must not reorder them: a WebSocket - // delivers frames in order and an application may depend on being given - // them that way. + // Moving handling off the read loop must not reorder what was already in + // order, which is what pins the worker to one message at a time. + // + // This is the behaviour of this runtime rather than a promise the platform + // makes. The same API deployed to a serverless target invokes a function + // per message with no ordering between them, and a client resending after + // a lost acknowledgement reorders its own messages anyway. An application + // that needs ordering has to carry its own sequence. So this test exists to + // keep the runtime's behaviour deliberate, not to stop it ever changing. let mut seen = Vec::new(); for _ in 0..5 { let dispatch = handler diff --git a/libs/runtime/ws/ws-registry/Cargo.toml b/libs/runtime/ws/ws-registry/Cargo.toml index 6cee3cce..70ee0136 100644 --- a/libs/runtime/ws/ws-registry/Cargo.toml +++ b/libs/runtime/ws/ws-registry/Cargo.toml @@ -12,6 +12,7 @@ jsonpath-rust = "0.7.1" async-trait = "0.1.88" tokio = { version = "1.45.1", features = ["full"] } axum = { version = "0.8.4", features = ["ws", "http2"] } +futures = "0.3.30" tracing = "0.1.40" base64 = "0.22.1" diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 549859d4..25fb3cee 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -6,6 +6,7 @@ use std::{ use async_trait::async_trait; use axum::extract::ws::{Message, WebSocket}; +use futures::{stream::SplitSink, SinkExt}; use tokio::sync::{ mpsc::{Receiver, Sender}, Mutex, @@ -21,6 +22,13 @@ use crate::{ }, }; +/// The sending half of a connection, which is all a registry ever needs. +/// +/// A connection's receiving half belongs to the task reading it, so that +/// reading never waits on a lock a sender holds. Holding only this half here +/// makes that ownership impossible to get wrong. +pub type WebSocketConnSender = SplitSink; + // Additional context for sending messages to a connection in a WebSocket registry. #[derive(Default)] pub struct SendContext { @@ -72,7 +80,7 @@ pub struct WebSocketConnRegistry { ack_worker_config: Option, // WebSockets do not implement Sync so we need to wrap them in Arc> // to safely send messages to WebSocket connections from multiple threads. - connections: Arc>>>>, + connections: Arc>>>>, // A channel for sending messages to the ack worker. ack_sender: Mutex>>, // This is called "broadcaster" because it is used to send messages to all @@ -245,7 +253,7 @@ impl WebSocketConnRegistry { }); } - pub fn add_connection(&self, connection_id: String, ws: Arc>) { + pub fn add_connection(&self, connection_id: String, ws: Arc>) { self.connections.write().unwrap().insert(connection_id, ws); } @@ -253,7 +261,7 @@ impl WebSocketConnRegistry { self.connections.write().unwrap().remove(&connection_id); } - fn get_connection(&self, connection_id: String) -> Option>> { + fn get_connection(&self, connection_id: String) -> Option>> { let conn = self .connections .read() @@ -265,7 +273,7 @@ impl WebSocketConnRegistry { /// Returns an iterable vector of connections in the registry. #[allow(dead_code)] - pub fn get_connections(&self) -> Vec<(String, Arc>)> { + pub fn get_connections(&self) -> Vec<(String, Arc>)> { self.connections .read() .unwrap() @@ -451,7 +459,6 @@ mod tests { use std::{ future::Future, net::{Ipv4Addr, SocketAddr}, - time::Duration, }; use super::*; @@ -465,7 +472,6 @@ mod tests { use futures::{FutureExt, SinkExt, StreamExt}; use nanoid::nanoid; use serde::{Deserialize, Serialize}; - use tokio::time::sleep; use tokio_tungstenite::tungstenite; #[derive(Clone)] @@ -505,67 +511,73 @@ mod tests { let other_connection_id = conn_info.other_connection_id.clone(); let missing_connection_id = conn_info.missing_connection_id.clone(); async move { - let protected_socket = Arc::new(Mutex::new(socket)); + // Split as the runtime does, so the registry holds only the + // sending half and reading never contends with a sender. + let (socket_tx, mut socket_rx) = socket.split(); + let protected_socket = Arc::new(Mutex::new(socket_tx)); let protected_socket_clone = protected_socket.clone(); registry.add_connection(connection_id.clone(), protected_socket_clone); let mut connection_alive = true; while connection_alive { - // Wait some time before acquiring the lock again to allow other tasks to write - // to the socket. (i.e. a message received from another node in the cluster) - sleep(Duration::from_millis(10)).await; - let mut socket_lock = protected_socket.lock().await; - tokio::select! { - msg_wrapped = socket_lock.recv() => { - if let Some(Ok(msg)) = msg_wrapped { - if let Message::Text(msg) = msg { - // Broadcast received message to other connection or missing connection. - if let Some(other_connection_id) = &other_connection_id { - let _ = registry - .send_message(other_connection_id.clone(), nanoid!(), MessageType::Json, msg.to_string(), None) - .await; - } else if let Some(missing_connection_id) = &missing_connection_id { - let msg_payload = serde_json::from_str::(&msg).unwrap(); - let wait_result = registry - .send_message( - missing_connection_id.clone(), - msg_payload.message_id, - MessageType::Json, - msg.to_string(), - Some(SendContext { - wait_for_ack: true, - caller: None, - inform_clients: vec![connection_id.clone()], - }), - ) - .await; - if let Err(WebSocketConnError::MessageLost(message_id)) = - wait_result - { - // Message was lost, inform the client that sent the message - // to get full coverage on behaviour to manually wait for the ack. - socket_lock.send(Message::Text(format!("Custom message lost event: {message_id}").into())).await.unwrap(); - } - } else { - // When "other connection" is not statically set, - // broadcast to all other connections. - for (id, conn) in registry.get_connections().iter() { - if *id != connection_id { - let mut conn = conn.lock().await; - conn.send(Message::Text(msg.clone())).await.unwrap(); - } - } - } + let msg_wrapped = socket_rx.next().await; + if let Some(Ok(msg)) = msg_wrapped { + if let Message::Text(msg) = msg { + // Broadcast received message to other connection or missing connection. + if let Some(other_connection_id) = &other_connection_id { + let _ = registry + .send_message( + other_connection_id.clone(), + nanoid!(), + MessageType::Json, + msg.to_string(), + None, + ) + .await; + } else if let Some(missing_connection_id) = &missing_connection_id { + let msg_payload = + serde_json::from_str::(&msg).unwrap(); + let wait_result = registry + .send_message( + missing_connection_id.clone(), + msg_payload.message_id, + MessageType::Json, + msg.to_string(), + Some(SendContext { + wait_for_ack: true, + caller: None, + inform_clients: vec![connection_id.clone()], + }), + ) + .await; + if let Err(WebSocketConnError::MessageLost(message_id)) = + wait_result + { + // Message was lost, inform the client that sent the message + // to get full coverage on behaviour to manually wait for the ack. + protected_socket + .lock() + .await + .send(Message::Text( + format!("Custom message lost event: {message_id}") + .into(), + )) + .await + .unwrap(); } } else { - connection_alive = false; + // When "other connection" is not statically set, + // broadcast to all other connections. + for (id, conn) in registry.get_connections().iter() { + if *id != connection_id { + let mut conn = conn.lock().await; + conn.send(Message::Text(msg.clone())).await.unwrap(); + } + } } } - // Timeout to allow other tasks to write to the socket - // at an interval. - _ = sleep(Duration::from_secs(5)) => { - // Skip to next iteration of the loop to release the lock. - }, + } else { + connection_alive = false; } } registry.remove_connection(connection_id.clone()); @@ -737,26 +749,30 @@ mod tests { .await .unwrap(); - // The custom message lost event should be received first as is called by the test handler - // while it holds a lock on the socket, when this is released, the protocol-level message lost - // message will be sent to the socket by the registry in response to ack worker events. - let node1_manual_wait_for_ack_msg_received = match socket1.next().await.unwrap().unwrap() { - tungstenite::Message::Text(msg) => msg, - other => panic!("Unexpected message but got {other:?}"), - }; + // Both notifications arrive, one from the handler waiting on the ack + // itself and one from the registry acting on the ack worker's event. + // Their order is not guaranteed. They come from separate tasks, and + // nothing sequences them now that reading a connection no longer holds + // a lock the senders have to wait behind. + let mut manual_msg = None; + let mut lost_event = None; + for _ in 0..2 { + match socket1.next().await.unwrap().unwrap() { + tungstenite::Message::Text(msg) => manual_msg = Some(msg), + tungstenite::Message::Binary(msg) => lost_event = Some(msg), + other => panic!("Unexpected message but got {other:?}"), + } + } assert_eq!( - node1_manual_wait_for_ack_msg_received, + manual_msg.expect("the handler should report the lost message itself"), "Custom message lost event: test-message-1" ); - let node1_msg_received = match socket1.next().await.unwrap().unwrap() { - tungstenite::Message::Binary(msg) => msg, - other => panic!("Unexpected message but got {other:?}"), - }; - // After a number of retry attempts, the message will be considered lost // and client should be informed with a message lost event. + let node1_msg_received = + lost_event.expect("the registry should send a protocol-level lost message event"); assert_eq!(node1_msg_received[0], 0x1); // Route length should be 1 assert_eq!(node1_msg_received[1], 0x3); // Route should be 0x3 (message lost) let json_msg = String::from_utf8(node1_msg_received[2..].to_vec()).unwrap(); From cd2d5db68ea82f952fdf6f7877e90fe91b037f1a Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sat, 15 Aug 2026 10:59:23 +0100 Subject: [PATCH 3/6] fix(lib-rt-core): close a websocket connection out without waiting on its queue Handling messages off the read loop left teardown waiting for the worker to finish everything it was still holding. Each of those messages waits on its own handler timeout and they run one after another, so a connection could sit in the registry, counted by the connection gauge, with its disconnect handler unfired, for the sum of those timeouts. At the default of sixty seconds and a full buffer that is around an hour. Teardown now stops waiting after a few seconds. The work itself carries on, because a message the client already sent is closer to a queue message than to a request and a handler part way through persisting one should finish whether or not anyone is still there to hear about it. What ends is the waiting, not the work. Firing the disconnect handler moved out of message processing and into teardown, which owns it now. It used to fire from whichever path noticed the connection had ended, and once teardown could return while the worker was still running, that became two paths that could each fire it. One place that always runs means it happens exactly once however a connection ends. A connection refused by its connect handler was left in the registry. It is registered before the handler runs so the handler can send to it, and the refusal path returned without undoing that, so the runtime held a sender for a connection nobody could reach and counted it as active for the life of the process. No disconnect handler runs for it, since the connect handler turned it down and from the application's side it never connected. --- libs/runtime/core/src/consts.rs | 10 +++ libs/runtime/core/src/websocket.rs | 56 +++++++++---- .../ipc-websocket-disconnect.blueprint.yaml | 68 +++++++++++++++ .../runtime/core/tests/ipc_end_to_end_test.rs | 84 +++++++++++++++++++ libs/runtime/ws/ws-registry/src/registry.rs | 73 ++++++++++++++++ 5 files changed, 276 insertions(+), 15 deletions(-) create mode 100644 libs/runtime/core/tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index ce63d1bd..17a45ec6 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -117,6 +117,16 @@ pub const WS_CONNECTION_WORK_BUFFER: usize = 64; // before it would have concluded the connection was gone. pub const WS_CONNECTION_WORK_SHED_GRACE_MS: u64 = 1_000; +// How long a closing connection waits for the messages it already accepted to +// finish before it abandons them and completes teardown. +// +// Until teardown completes the connection is still in the registry, still +// counted by the connection gauge, and its disconnect handler has not run, so +// this cannot wait on the queue draining at its own pace. Each queued message +// waits on its own handler timeout, and those add up, whereas a few seconds is +// enough for work that is nearly done to land. +pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; + // The `retryAfter` hint sent in the close frame when a connection is shed for // outrunning its handlers. // diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index feef106d..2a25bbb8 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -48,8 +48,8 @@ use crate::{ CELERITY_WS_CAPABILITIES_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, CELERITY_WS_DEFAULT_MESSAGE_HANDLER_ROUTE, CELERITY_WS_DISCONNECT_HANDLER_ROUTE, CELERITY_WS_FORBIDDEN_ERROR_CODE, CELERITY_WS_UNAUTHORISED_ERROR_CODE, - WS_CONNECTION_SATURATED_RETRY_AFTER_MS, WS_CONNECTION_WORK_BUFFER, - WS_CONNECTION_WORK_SHED_GRACE_MS, + WS_CONNECTION_DRAIN_GRACE_MS, WS_CONNECTION_SATURATED_RETRY_AFTER_MS, + WS_CONNECTION_WORK_BUFFER, WS_CONNECTION_WORK_SHED_GRACE_MS, }, errors::WebSocketsMessageError, request::{HttpProtocolVersion, RequestId}, @@ -334,6 +334,16 @@ async fn handle_socket( ) .await { + // Registered above so the connect handler could send to it, so the + // registration has to be undone here. Left in place it would hold a + // sender for a connection that was refused and count towards the + // active connection gauge for the life of the process. + // + // No disconnect handler runs. The connect handler turned this + // connection down, so from the application's side it never + // connected. + state.connections.remove_connection(connection_id.clone()); + ws_connections_counter().add(-1, &[]); return; } @@ -353,7 +363,7 @@ async fn handle_socket( let (work_tx, work_rx) = mpsc::channel::<(Message, WebSocketRequestContext)>( WS_CONNECTION_WORK_BUFFER, ); - let worker = spawn_message_worker( + let mut worker = spawn_message_worker( work_rx, socket_ref.clone(), connection_id.clone(), @@ -455,12 +465,31 @@ async fn handle_socket( // Closing the channel ends the worker once it has finished whatever it // was given, so the disconnect handler runs after the messages that // preceded it rather than alongside them. + // + // The wait is bounded but the work is not cut short. Each message the + // worker still holds waits on its own handler timeout, and waiting for + // all of them in turn would leave a connection that has already gone + // sitting in the registry, counted by the gauge, with its disconnect + // handler unfired. So this stops waiting and lets the worker carry on + // in its own time. A message the client already sent is closer to a + // queue message than to a request, and a handler part way through + // persisting one should finish whether or not anyone is still there to + // hear about it. drop(work_tx); - let disconnect_handled = worker.await.unwrap_or(false); - - if !disconnect_handled { - let _ = on_disconnect(connection_id.clone(), &state, &request_ctx).await; + if tokio::time::timeout( + Duration::from_millis(WS_CONNECTION_DRAIN_GRACE_MS), + &mut worker, + ) + .await + .is_err() + { + warn!( + "client {connection_id} left work still running after the drain window, \ + closing the connection out while it finishes" + ); } + + let _ = on_disconnect(connection_id.clone(), &state, &request_ctx).await; state.connections.remove_connection(connection_id.clone()); ws_connections_counter().add(-1, &[]); } @@ -616,16 +645,12 @@ fn create_connect_message( } /// Runs a connection's messages, one at a time, off its read loop. -/// -/// Returns whether the disconnect handler has already been fired, which happens -/// when the client sent a close frame and the worker saw it in sequence. The -/// read loop fires it otherwise, for a connection that simply went away. fn spawn_message_worker( mut work_rx: mpsc::Receiver<(Message, WebSocketRequestContext)>, socket_ref: Arc>, connection_id: String, state: WebSocketAppState, -) -> JoinHandle { +) -> JoinHandle<()> { tokio::spawn(async move { while let Some((message, request_ctx)) = work_rx.recv().await { if process_message(message, connection_id.clone(), request_ctx, &state) @@ -636,10 +661,9 @@ fn spawn_message_worker( // socket that may never produce anything again. Closing it is // what wakes the loop so the connection can be torn down. close_connection(socket_ref.clone()).await; - return true; + return; } } - false }) } @@ -1064,7 +1088,9 @@ async fn process_message( } }; info!(info_msg); - let _ = on_disconnect(connection_id.clone(), state, &request_ctx).await; + // The disconnect handler is fired by the connection's teardown + // rather than here, so that it runs exactly once however the + // connection ends and whether or not this worker is still going. return ControlFlow::Break(()); } Message::Ping(_) | Message::Pong(_) => { diff --git a/libs/runtime/core/tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml new file mode 100644 index 00000000..d96967ff --- /dev/null +++ b/libs/runtime/core/tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml @@ -0,0 +1,68 @@ +version: 2025-11-02 +transform: celerity-2026-02-28 +variables: + logLevel: + type: string + description: "The log level to use for logging." + default: "INFO" + allowedValues: + - "DEBUG" + - "INFO" + - "WARNING" + - "ERROR" + +resources: + ordersWebSocketApi: + type: "celerity/api" + description: "A WebSocket API with a disconnect handler, so that closing a connection can be observed from the outside." + metadata: + displayName: Orders WebSocket API + linkSelector: + byLabel: + application: "orders" + spec: + protocols: ["websocket"] + tracingEnabled: false + + sendMessageHandler: + type: "celerity/handler" + metadata: + displayName: Send Message Handler + labels: + application: "orders" + annotations: + celerity.handler.websocket: true + celerity.handler.websocket.route: "sendMessage" + spec: + handlerName: Orders-SendMessageHandler-v1 + codeLocation: "./orders" + handler: "handlers.send_message" + runtime: "python3.12.x" + memory: 1024 + # Deliberately short. A test that covers teardown has to outlast the + # queued messages the connection is holding, so their timeouts are what + # sets how long it runs for. + timeout: 1 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" + + disconnectHandler: + type: "celerity/handler" + metadata: + displayName: Disconnect Handler + labels: + application: "orders" + annotations: + celerity.handler.websocket: true + celerity.handler.websocket.route: "$disconnect" + spec: + handlerName: Orders-DisconnectHandler-v1 + codeLocation: "./orders" + handler: "handlers.disconnect" + runtime: "python3.12.x" + memory: 1024 + timeout: 1 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index 132e343f..eb9d9ff0 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1224,6 +1224,90 @@ async fn reads_faster_than_one_message_every_ten_milliseconds() { let _ = tokio::fs::remove_file(&socket).await; } +#[test_log::test(tokio::test)] +async fn closes_a_connection_out_without_waiting_for_all_the_work_it_queued() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-drain", + "tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml", + ) + .await; + // Answer nothing, so every queued message runs its timeout out in turn. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + // Eight messages against a one second handler timeout, so draining every + // one of them would take longer than the connection is given to close. + for index in 0..8 { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "index": index } }).to_string(), + )) + .await + .unwrap(); + } + handler + .next_dispatch() + .await + .expect("the first message should reach the handler"); + + let closed_at = tokio::time::Instant::now(); + socket_conn + .close(None) + .await + .expect("the client should be able to close"); + + // The disconnect handler running is what says teardown finished, and until + // it does the connection is still in the registry and still counted. It + // must not wait for messages the client is no longer there to hear about. + let disconnected = tokio::time::timeout(Duration::from_secs(7), async { + while let Some(dispatch) = handler.next_dispatch().await { + if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { + if message.route == "$disconnect" { + return true; + } + } + } + false + }) + .await; + + assert_eq!( + disconnected, + Ok(true), + "the disconnect handler should run once the drain window passes" + ); + assert!( + closed_at.elapsed() < Duration::from_secs(7), + "teardown took {:?}, which suggests it waited for the whole queue", + closed_at.elapsed() + ); + + // Teardown owns the disconnect handler outright. The worker used to fire it + // too, when it reached a close frame in sequence, which is a second one + // waiting to happen for any connection whose worker outlives its teardown. + let second = tokio::time::timeout(Duration::from_secs(2), async { + while let Some(dispatch) = handler.next_dispatch().await { + if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { + if message.route == "$disconnect" { + return true; + } + } + } + false + }) + .await; + assert_ne!( + second, + Ok(true), + "the disconnect handler should run once, not once per path that can end a connection" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + #[test_log::test(tokio::test)] async fn does_not_reorder_messages_when_handling_them_off_the_read_loop() { let (_app, addr, socket) = start_runtime( diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 25fb3cee..3ebb3073 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -831,4 +831,77 @@ mod tests { assert_eq!(socket2_msg_received, "Hello, forward this to Connection 2!"); } + + /// A connection that is registered and then removed leaves nothing behind. + /// + /// The registry holds a sender for every connection in it, and callers + /// broadcast by walking that set, so an entry that outlives its connection + /// is a sender nothing can deliver through and a connection that still + /// counts as present. Every path that ends a connection has to reach + /// `remove_connection`, including the ones that refuse a connection after + /// registering it, which is why this covers the primitive they all rely on. + #[test_log::test(tokio::test)] + async fn test_ws_conn_registry_removes_connections() { + let (tx, _) = tokio::sync::mpsc::channel(1024); + let registry = Arc::new(WebSocketConnRegistry::new( + WebSocketConnRegistryConfig { + ack_worker_config: None, + server_node_name: "node1".to_string(), + }, + Some(tx), + )); + + let app: Router = Router::new() + .route("/ws", get(testable_handler)) + .with_state(ConnectionInfo { + connection_id: None, + other_connection_id: None, + missing_connection_id: None, + registry: registry.clone(), + }); + + let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) + .await + .unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let (mut socket1, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + let (_socket2, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + + wait_for_connection_count(®istry, 2).await; + + socket1.close(None).await.unwrap(); + + wait_for_connection_count(®istry, 1).await; + + let remaining = registry.get_connections(); + assert_eq!( + remaining.len(), + 1, + "closing one connection should leave the other registered" + ); + } + + /// Waits for the registry to hold the given number of connections. + /// + /// Registration and removal happen on the connection's own task, so a test + /// that looks straight after connecting or closing races that task. + async fn wait_for_connection_count(registry: &Arc, expected: usize) { + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); + while registry.get_connections().len() != expected { + assert!( + tokio::time::Instant::now() < deadline, + "expected {expected} connections, registry has {}", + registry.get_connections().len() + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + } } From 4daf1368eb7bdb18d209c02e26371dfe4c24eb74 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sat, 15 Aug 2026 11:56:04 +0100 Subject: [PATCH 4/6] fix(lib-rt-core): answer a client that has not authenticated yet A connection using the authMessage strategy would hang the moment its client sent anything before authenticating. The lock on the connection was taken in the expression being matched on, and a lock taken there is held until the end of the match, so the arm that answers the client waited on a lock its own match was still holding. Nothing broke the wait. The connection task stopped there for good, holding the lock, and anything trying to send to that client queued up behind it. Taking the lock in a scope of its own releases it before the arms run, so the client gets told to authenticate first. Starting an application whose websocket connections are guarded also panicked when setup ran inside a runtime, since the guards were read with a blocking take. Setup is the only thing touching that map at the time, so the lock is always free and there was never anything to block on. Taking it without blocking gets the guards just the same and leaves an async caller alone. Covered by the first websocket auth test in this crate. It sends an ordinary message to a connection that has not authenticated and requires the refusal to come back, which is a wait of five seconds against the old code. --- libs/runtime/core/src/application.rs | 13 ++-- libs/runtime/core/src/websocket.rs | 19 +++--- .../ipc-websocket-auth-message.blueprint.yaml | 60 +++++++++++++++++++ .../runtime/core/tests/ipc_end_to_end_test.rs | 52 +++++++++++++++- 4 files changed, 130 insertions(+), 14 deletions(-) create mode 100644 libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 2be89a19..5c811f7e 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -449,10 +449,15 @@ impl Application { ) -> HashMap> { let mut guards = HashMap::new(); if let Some(names) = guard_names { - // This is only called in the setup phase, so using a thread-blocking lock is safe - // as the setup http server method will be the only caller accessing - // the custom auth guards map at this point. - let all_guards = self.custom_auth_guards.blocking_lock(); + // Taken without blocking. Setup is the only thing touching this map + // at this point, so the lock is always free, and a blocking take + // panics outright when setup is called from inside a runtime, which + // is how an application with connection auth guards is started from + // an async context. + let Ok(all_guards) = self.custom_auth_guards.try_lock() else { + error!("custom auth guards were unavailable while setting up the server"); + return guards; + }; for name in names { if let Some(guard) = all_guards.get(name) { guards.insert(name.clone(), guard.clone()); diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 2a25bbb8..7f594b7a 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -384,15 +384,16 @@ async fn handle_socket( if !is_authenticated { // Connection is in unauthenticated state (authMessage strategy). // Only accept an "authenticate" message; reject everything else. - match handle_auth_message( - &msg, - &connection_id, - &state, - &request_ctx, - &mut *socket_ref.lock().await, - ) - .await - { + // Scoped so the guard is dropped before the arms run. A + // guard taken in the arm lives until the end of the + // match, and an arm below takes the same lock, which does + // not nest. + let auth_result = { + let mut socket = socket_ref.lock().await; + handle_auth_message(&msg, &connection_id, &state, &request_ctx, &mut socket) + .await + }; + match auth_result { AuthMessageResult::Authenticated(data) => { is_authenticated = true; request_ctx.auth_data = Some(data); diff --git a/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml new file mode 100644 index 00000000..ee22ec05 --- /dev/null +++ b/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml @@ -0,0 +1,60 @@ +version: 2025-11-02 +transform: celerity-2026-02-28 +variables: + logLevel: + type: string + description: "The log level to use for logging." + default: "INFO" + allowedValues: + - "DEBUG" + - "INFO" + - "WARNING" + - "ERROR" + +resources: + ordersWebSocketApi: + type: "celerity/api" + description: "A WebSocket API using the authMessage strategy, so the unauthenticated path can be exercised." + metadata: + displayName: Orders WebSocket API + linkSelector: + byLabel: + application: "orders" + spec: + protocols: + - websocketConfig: + routeKey: "event" + authStrategy: "authMessage" + authGuard: "jwt" + tracingEnabled: false + auth: + guards: + # Never reached by the case under test. A message that is not an + # authenticate message is refused before any guard runs, which is the + # whole point of the path being covered. + jwt: + type: jwt + issuer: "https://identity.newstack.cloud/oauth2/v1/" + tokenSource: "$.data.token" + audience: + - "https://identity.newstack.cloud/api/manage/v1/" + + sendMessageHandler: + type: "celerity/handler" + metadata: + displayName: Send Message Handler + labels: + application: "orders" + annotations: + celerity.handler.websocket: true + celerity.handler.websocket.route: "sendMessage" + spec: + handlerName: Orders-SendMessageHandler-v1 + codeLocation: "./orders" + handler: "handlers.send_message" + runtime: "python3.12.x" + memory: 1024 + timeout: 10 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index eb9d9ff0..6ab5fc57 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1216,14 +1216,64 @@ async fn reads_faster_than_one_message_every_ten_milliseconds() { } let elapsed = started.elapsed(); + // Below the 500ms the old cap would have cost, with enough room above the + // handful of milliseconds this actually takes that a loaded machine does + // not fail it for being busy. assert!( - elapsed < Duration::from_millis(400), + elapsed < Duration::from_millis(450), "50 messages took {elapsed:?}, which suggests the read loop is still rate limited" ); let _ = tokio::fs::remove_file(&socket).await; } +#[test_log::test(tokio::test)] +async fn tells_an_unauthenticated_client_to_authenticate_first() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-auth-message", + "tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml", + ) + .await; + let _handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the authMessage strategy should let the connection upgrade"); + + // Anything that is not an authenticate message, sent before the connection + // has authenticated. The runtime answers on the same socket it just read + // from, so this is the path where taking the lock twice would wedge the + // connection rather than refuse the message. + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + let rejected = tokio::time::timeout(Duration::from_secs(5), async { + while let Some(Ok(message)) = socket_conn.next().await { + if let tokio_tungstenite::tungstenite::Message::Text(text) = message { + if let Ok(value) = serde_json::from_str::(&text) { + if value["event"] == "error" { + return true; + } + } + } + } + false + }) + .await; + + assert_eq!( + rejected, + Ok(true), + "an unauthenticated message should be refused rather than leave the connection hanging" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + #[test_log::test(tokio::test)] async fn closes_a_connection_out_without_waiting_for_all_the_work_it_queued() { let (_app, addr, socket) = start_runtime( From 5969120976d0a9dc4368aa17bafda5465117b635 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 16 Aug 2026 00:53:18 +0100 Subject: [PATCH 5/6] test(lib-rt-core): cover the disconnect handler running once for real The test that claimed to hold the disconnect handler to a single run could not fail. It watched for a second one after a client that closes through the handshake, and closing that way never surfaces a frame to the application at all, so the path that would fire the second is not reached from there. The assertion passed whether or not the problem it named was present. A client that sends a close frame outright does reach that path. The frame arrives as an ordinary message, message processing sees it, and the read loop sees the stream end, so both of the paths that could end a connection run. Counting the disconnects a client gets that way holds the behaviour to one, and reports two against the arrangement it replaced. The assertion that could not fail is gone from the drain test, which keeps what it does cover, that closing a connection out does not wait on the messages it queued. --- .../runtime/core/tests/ipc_end_to_end_test.rs | 67 +++++++++++++------ 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index 6ab5fc57..e5fe0a3c 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1312,6 +1312,11 @@ async fn closes_a_connection_out_without_waiting_for_all_the_work_it_queued() { // The disconnect handler running is what says teardown finished, and until // it does the connection is still in the registry and still counted. It // must not wait for messages the client is no longer there to hear about. + // + // That it runs exactly once is covered separately, by a client that sends + // a close frame outright. Closing the way this one does drives the whole + // handshake and never surfaces a frame to the application, so the second + // path that could fire a disconnect is not reached from here. let disconnected = tokio::time::timeout(Duration::from_secs(7), async { while let Some(dispatch) = handler.next_dispatch().await { if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { @@ -1335,26 +1340,6 @@ async fn closes_a_connection_out_without_waiting_for_all_the_work_it_queued() { closed_at.elapsed() ); - // Teardown owns the disconnect handler outright. The worker used to fire it - // too, when it reached a close frame in sequence, which is a second one - // waiting to happen for any connection whose worker outlives its teardown. - let second = tokio::time::timeout(Duration::from_secs(2), async { - while let Some(dispatch) = handler.next_dispatch().await { - if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { - if message.route == "$disconnect" { - return true; - } - } - } - false - }) - .await; - assert_ne!( - second, - Ok(true), - "the disconnect handler should run once, not once per path that can end a connection" - ); - let _ = tokio::fs::remove_file(&socket).await; } @@ -1450,3 +1435,45 @@ async fn carries_a_binary_websocket_frame_without_corrupting_it() { let _ = socket_conn.close(None).await; let _ = tokio::fs::remove_file(&socket).await; } + +#[test_log::test(tokio::test)] +async fn fires_the_disconnect_handler_once_for_a_client_that_sends_a_close_frame() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-close-once", + "tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + // Sent as an ordinary frame rather than through close(), which drives the + // whole handshake and never surfaces the frame to the application. Sent + // this way it reaches message processing, which is the path that could + // once fire a disconnect of its own alongside the one teardown fires. + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Close(None)) + .await + .unwrap(); + + let mut disconnects = 0; + let _ = tokio::time::timeout(Duration::from_secs(4), async { + while let Some(dispatch) = handler.next_dispatch().await { + if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { + if message.route == "$disconnect" { + disconnects += 1; + } + } + } + }) + .await; + + assert_eq!( + disconnects, 1, + "the disconnect handler should run once, not once per path that can end a connection" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} From f47913f8b2fa0f049d413c9dc261d1c539458eeb Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 16 Aug 2026 01:20:51 +0100 Subject: [PATCH 6/6] test(lib-rt-ws-registry): name the connection a registry is expected to drop Counting what the registry held after a connection closed said only that it held one of something. A registry that dropped the wrong connection would have satisfied that just as well, which is the mistake worth catching, since the entry left behind is a sender for a client nobody can reach and the one removed belongs to a client still connected. The connections are made one at a time now, so the id each was given can be read back between them, and the registry is held to leaving exactly the connection that stayed open. Removing the wrong one fails it and says which id was found in place of which. --- libs/runtime/ws/ws-registry/src/registry.rs | 27 +++++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 3ebb3073..05cd9af9 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -868,24 +868,41 @@ mod tests { axum::serve(listener, app).await.unwrap(); }); + // Connected one at a time, because the handler names each connection + // itself and reading the registry between the two is the only way to + // tell which id belongs to which socket. let (mut socket1, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) .await .unwrap(); + wait_for_connection_count(®istry, 1).await; + let first_id = registry.get_connections()[0].0.clone(); + let (_socket2, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) .await .unwrap(); - wait_for_connection_count(®istry, 2).await; + let second_id = registry + .get_connections() + .into_iter() + .map(|(id, _)| id) + .find(|id| *id != first_id) + .expect("the second connection should have an id of its own"); socket1.close(None).await.unwrap(); wait_for_connection_count(®istry, 1).await; - let remaining = registry.get_connections(); + // Named rather than counted. A registry that dropped the wrong + // connection would hold one either way. + let remaining: Vec = registry + .get_connections() + .into_iter() + .map(|(id, _)| id) + .collect(); assert_eq!( - remaining.len(), - 1, - "closing one connection should leave the other registered" + remaining, + vec![second_id], + "closing one connection should remove that one and leave the other" ); }