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/consts.rs b/libs/runtime/core/src/consts.rs index 4f026988..17a45ec6 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -97,6 +97,45 @@ 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 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; + +// 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. +// +// 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 5e634e5d..7f594b7a 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,11 +27,15 @@ 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::Mutex, time::sleep}; +use tokio::{ + sync::{mpsc, mpsc::error::SendTimeoutError, Mutex}, + task::JoinHandle, +}; use tracing::{debug, error, field, info, info_span, warn, Instrument}; use crate::{ @@ -44,6 +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_DRAIN_GRACE_MS, WS_CONNECTION_SATURATED_RETRY_AFTER_MS, + WS_CONNECTION_WORK_BUFFER, WS_CONNECTION_WORK_SHED_GRACE_MS, }, errors::WebSocketsMessageError, request::{HttpProtocolVersion, RequestId}, @@ -238,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); @@ -322,44 +334,71 @@ 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; } + // Messages are processed off this loop, one at a time, by a worker for + // 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 + // 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 mut 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 - // 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; } 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 acquired_socket, - ) - .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); } AuthMessageResult::Failed => { - state.connections.remove_connection(connection_id.clone()); - ws_connections_counter().add(-1, &[]); connection_alive = false; } AuthMessageResult::NotAuthMessage => { @@ -370,41 +409,97 @@ 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 lock before processing to allow other tasks - // (e.g. cluster relay) to write to the socket. - drop(acquired_socket); - if process_message(msg, connection_id.clone(), request_ctx.clone(), &state) + // 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. + // + // 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 - .is_break() { - state.connections.remove_connection(connection_id.clone()); - ws_connections_counter().add(-1, &[]); - connection_alive = false; + 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 { // 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. + // + // 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); + 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, &[]); } .instrument(info_span!("websocket_connection", connection_id = %connection_id)) .await } async fn authenticate_connection( - socket_ref: Arc>, + socket_ref: Arc>, state: &WebSocketAppState, request_ctx: &WebSocketRequestContext, ) -> ControlFlow<(), serde_json::Value> { @@ -496,7 +591,7 @@ async fn authenticate_connection( } async fn on_connect( - socket_ref: Arc>, + socket_ref: Arc>, connection_id: String, state: &WebSocketAppState, request_ctx: &WebSocketRequestContext, @@ -550,6 +645,29 @@ fn create_connect_message( } } +/// Runs a connection's messages, one at a time, off its read loop. +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; + } + } + }) +} + async fn on_disconnect( connection_id: String, state: &WebSocketAppState, @@ -641,7 +759,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> { @@ -716,7 +834,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(), @@ -971,7 +1089,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(_) => { @@ -1295,19 +1415,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/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/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 baf803eb..e5fe0a3c 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,337 @@ 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 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(); + + // 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(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( + "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. + // + // 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 { + 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() + ); + + 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", + ) + .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(); + } + + // 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 + .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( @@ -1104,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; +} 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..05cd9af9 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(); @@ -815,4 +831,94 @@ 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(); + }); + + // 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; + + // 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, + vec![second_id], + "closing one connection should remove that one and leave the other" + ); + } + + /// 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; + } + } }