diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 5c811f7e..28aeb9df 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -341,6 +341,10 @@ impl Application { )); self.ws_connections = Some(conn_registry.clone()); + // Tracks the messages that asked their client to acknowledge them, + // resending and eventually giving up on the ones that go unanswered. + conn_registry.clone().start_client_ack_worker(); + // As with HTTP routes, the FFI call mode has the SDK register these // as it binds each in-process handler. In the IPC call mode the // runtime registers one per blueprint handler, so that messages diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 970bf83e..d01c160d 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -417,6 +417,23 @@ async fn handle_socket( } } } else { + // A client acknowledging something the runtime sent it, + // taken before routing so it is not mistaken for a routed + // message and handed to the default handler. + // + // Only from a connection that has authenticated, since an + // acknowledgement calls off a resend and the loss event + // that follows it, and that is not something an unproven + // client should be able to do to a message. + if let Some(acknowledged) = detect_client_ack(&msg) { + debug!("client {connection_id} acknowledged message {acknowledged}"); + state + .connections + .record_client_ack(connection_id.clone(), acknowledged) + .await; + continue; + } + // 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 @@ -1264,6 +1281,42 @@ enum AckFormat { Binary, } +/// Recognises a client acknowledging something the runtime sent it, returning +/// the id of the message being acknowledged. +/// +/// Reads both encodings, the reserved `0x4` binary frame and the JSON form +/// carrying `ack` as the value of `event`. That key is fixed by the protocol +/// rather than being the API's configured route key, which is what makes these +/// messages unroutable and why they have to be recognised here. +fn detect_client_ack(msg: &Message) -> Option { + let body = match msg { + Message::Binary(bytes) => { + if !bytes.starts_with(&CELERITY_WS_ACK_SIGNAL) { + return None; + } + let value: Value = serde_json::from_slice(bytes.get(4..)?).ok()?; + value + } + Message::Text(text) => { + // A reserved acknowledgement always names itself, so anything that + // does not mention it is passed over before it is parsed. + if !text.contains("\"ack\"") { + return None; + } + let value: Value = serde_json::from_str(text).ok()?; + if value.get("event").and_then(Value::as_str) != Some("ack") { + return None; + } + value.get("data")?.clone() + } + _ => return None, + }; + + body.get("messageId") + .and_then(Value::as_str) + .map(str::to_string) +} + /// Whether a JSON text carries `ack` as an object key. /// /// A prefilter, not a parser. It is allowed to say yes to a message that turns @@ -1275,6 +1328,13 @@ fn has_ack_key(text: &str) -> bool { .any(|(index, matched)| text[index + matched.len()..].trim_start().starts_with(':')) } +/// Recognises a message asking to be acknowledged, returning the id to +/// acknowledge it by and the encoding to answer in. +/// +/// Read off the frame rather than out of the routing, so a message can be +/// answered as soon as it is taken in. Asking without a message id returns +/// nothing, since an acknowledgement names the message it is for and there +/// would be nothing to name. fn ack_request(msg: &Message) -> Option<(String, AckFormat)> { match msg { Message::Text(text) => { @@ -1594,6 +1654,38 @@ async fn close_with_retry_after(socket_ref: Arc>, ret mod tests { use super::*; + #[test] + fn test_detect_client_ack_reads_both_encodings() { + let mut frame = CELERITY_WS_ACK_SIGNAL.to_vec(); + frame.extend_from_slice(br#"{"messageId":"m-1","timestamp":"1"}"#); + assert_eq!( + detect_client_ack(&Message::Binary(frame.into())), + Some("m-1".to_string()) + ); + + let text = r#"{"event":"ack","data":{"messageId":"m-2","timestamp":"1"}}"#; + assert_eq!( + detect_client_ack(&Message::Text(text.into())), + Some("m-2".to_string()) + ); + } + + #[test] + fn test_detect_client_ack_leaves_application_messages_alone() { + // Carries the word but is an ordinary message, and the runtime must not + // swallow it on the way to its handler. + let text = r#"{"event":"sendMessage","data":{"kind":"ack"}}"#; + assert!(detect_client_ack(&Message::Text(text.into())).is_none()); + + // An acknowledgement request, which travels the other way. + let text = r#"{"event":"sendMessage","ack":true,"messageId":"m-3"}"#; + assert!(detect_client_ack(&Message::Text(text.into())).is_none()); + + // A binary application message whose route happens to be one byte. + let frame = vec![0x1, 0x9, 0x0, 0x0, 0xff]; + assert!(detect_client_ack(&Message::Binary(frame.into())).is_none()); + } + #[test] fn test_has_ack_key_ignores_ack_as_a_value() { // Reserved as an event value by the protocol itself, so a message diff --git a/libs/runtime/core/tests/data/fixtures/ipc-websocket-default-route.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-websocket-default-route.blueprint.yaml new file mode 100644 index 00000000..37d3f841 --- /dev/null +++ b/libs/runtime/core/tests/data/fixtures/ipc-websocket-default-route.blueprint.yaml @@ -0,0 +1,70 @@ +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 custom route key and a default handler, where anything the runtime does not take out of the way reaches the application." + metadata: + displayName: Orders WebSocket API + linkSelector: + byLabel: + application: "orders" + spec: + protocols: + - websocketConfig: + # Deliberately not the default. A reserved message names its route + # with `event`, so against a different route key it carries no route + # the runtime recognises and falls through to the default handler. + routeKey: "action" + 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 + timeout: 10 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" + + defaultHandler: + type: "celerity/handler" + metadata: + displayName: Default Handler + labels: + application: "orders" + annotations: + celerity.handler.websocket: true + celerity.handler.websocket.route: "$default" + spec: + handlerName: Orders-DefaultHandler-v1 + codeLocation: "./orders" + handler: "handlers.default" + 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 f96efacc..eb42265b 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1274,6 +1274,60 @@ async fn tells_an_unauthenticated_client_to_authenticate_first() { let _ = tokio::fs::remove_file(&socket).await; } +/// An acknowledgement is a message like any other until the client has proved +/// who it is. +/// +/// Acknowledgements are taken out of the way before routing, and that used to +/// happen ahead of the authentication gate, so an unauthenticated client could +/// still settle a message and call off the resend and loss event that follow +/// it. The refusal below is the gate doing its job. +#[test_log::test(tokio::test)] +async fn refuses_an_acknowledgement_from_a_client_that_has_not_authenticated() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-auth-message-ack", + "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"); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ + "event": "ack", + "data": { "messageId": "m-1", "timestamp": "2026-01-01T00:00:00.000Z" } + }) + .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 acknowledgement before authentication should be refused rather than settle a message" + ); + + 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( @@ -1569,6 +1623,65 @@ async fn acknowledges_a_message_queued_behind_a_handler_that_is_still_running() let _ = tokio::fs::remove_file(&socket).await; } +#[test_log::test(tokio::test)] +async fn does_not_route_a_client_acknowledgement_to_a_handler() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-inbound-ack", + "tests/data/fixtures/ipc-websocket-default-route.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"); + + // What a client sends to acknowledge something the runtime sent it. A + // reserved message names its route with `event`, and this API routes on + // `action`, so left alone it carries no route the runtime knows and lands + // on the default handler as though the application had been sent it. + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ + "event": "ack", + "data": { "messageId": "m-1", "timestamp": "1" }, + }) + .to_string(), + )) + .await + .unwrap(); + let mut binary = vec![0x1, 0x4, 0x0, 0x0]; + binary.extend_from_slice(br#"{"messageId":"m-2","timestamp":"1"}"#); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Binary(binary)) + .await + .unwrap(); + + // Sent last and expected first, since anything the runtime failed to take + // out of the way would have reached the handler ahead of it. + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "action": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + let dispatch = handler + .next_dispatch() + .await + .expect("the ordinary 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(); + assert_eq!( + body["data"]["text"], "hello", + "an acknowledgement reached the handler ahead of the message that followed it" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + #[test_log::test(tokio::test)] async fn does_not_acknowledge_a_message_that_did_not_ask() { let (_app, addr, socket) = start_runtime( diff --git a/libs/runtime/ws/ws-registry/src/acks.rs b/libs/runtime/ws/ws-registry/src/acks.rs index f0e693e1..f3e256cb 100644 --- a/libs/runtime/ws/ws-registry/src/acks.rs +++ b/libs/runtime/ws/ws-registry/src/acks.rs @@ -71,6 +71,10 @@ pub enum MessageAction { pub enum AckWorkerMessage { Status(String, AckStatus), + ClientAck { + message_id: String, + connection_id: String, + }, Check(String, Sender), Wait(String, Sender), } @@ -160,6 +164,12 @@ impl Worker { Some(AckWorkerMessage::Status(message_id, ack_status)) => { self.record_ack(message_id, ack_status).await; } + Some(AckWorkerMessage::ClientAck { + message_id, + connection_id, + }) => { + self.record_client_ack(message_id, connection_id).await; + } Some(AckWorkerMessage::Check(message_id, tx)) => { let acks_guard = self.acks.lock().await; let detailed_ack_status = acks_guard.get(&message_id).cloned(); @@ -221,6 +231,44 @@ impl Worker { acks_guard.insert(message_id, new_detailed_ack_status); } + + /// Settles a message on the word of the client it was sent to. + /// + /// An acknowledgement naming a message that is waiting on a different + /// connection is ignored, so one client cannot call off the delivery + /// guarantees another is relying on. + async fn record_client_ack(&mut self, message_id: String, connection_id: String) { + let mut acks_guard = self.acks.lock().await; + let Some(existing) = acks_guard.get_mut(&message_id) else { + debug!( + message_id = %message_id, + connection_id = %connection_id, + "a client acknowledged a message nothing is waiting on, ignoring it" + ); + return; + }; + + let owed_by = match &existing.status { + AckStatus::Pending { + connection_id: pending_connection_id, + .. + } => pending_connection_id, + // Already settled one way or the other, so there is nothing left to + // say about it. + _ => return, + }; + + if *owed_by != connection_id { + debug!( + message_id = %message_id, + connection_id = %connection_id, + "a client acknowledged a message owed by another connection, ignoring it" + ); + return; + } + + existing.status = AckStatus::Received; + } } async fn check_for_actions_periodic( diff --git a/libs/runtime/ws/ws-registry/src/message_helpers.rs b/libs/runtime/ws/ws-registry/src/message_helpers.rs index 8ec94751..a12e87e4 100644 --- a/libs/runtime/ws/ws-registry/src/message_helpers.rs +++ b/libs/runtime/ws/ws-registry/src/message_helpers.rs @@ -1,6 +1,6 @@ use axum::extract::ws::Message; use base64::{prelude::BASE64_STANDARD, DecodeError, Engine}; -use serde_json::json; +use serde_json::{json, Value}; use crate::types::MessageType; @@ -45,3 +45,84 @@ pub fn create_ws_message( } } } + +pub fn client_ack_request(message_type: &MessageType, message: &str) -> Option { + match message_type { + MessageType::Json => { + let value: Value = serde_json::from_str(message).ok()?; + let object = value.as_object()?; + if object.get("ack").and_then(Value::as_bool) != Some(true) { + return None; + } + object + .get("messageId") + .and_then(Value::as_str) + .map(str::to_string) + } + MessageType::Binary => { + let bytes = BASE64_STANDARD.decode(message).ok()?; + // [routeLength][route][requireAck][messageIdLength][messageId] + let route_length = *bytes.first()? as usize; + if *bytes.get(1 + route_length)? != 0x1 { + return None; + } + let id_length = *bytes.get(route_length + 2)? as usize; + if id_length == 0 { + return None; + } + let start = route_length + 3; + let id = bytes.get(start..start + id_length)?; + std::str::from_utf8(id).ok().map(str::to_string) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(route: &[u8], requires_ack: u8, message_id: &[u8], payload: &[u8]) -> String { + let mut bytes = vec![route.len() as u8]; + bytes.extend_from_slice(route); + bytes.push(requires_ack); + bytes.push(message_id.len() as u8); + bytes.extend_from_slice(message_id); + bytes.extend_from_slice(payload); + BASE64_STANDARD.encode(bytes) + } + + #[test] + fn test_client_ack_request_reads_the_opt_in_from_the_message() { + assert_eq!( + client_ack_request( + &MessageType::Json, + r#"{"event":"update","ack":true,"messageId":"m-1"}"# + ), + Some("m-1".to_string()) + ); + assert_eq!( + client_ack_request( + &MessageType::Binary, + &frame(b"updates", 0x1, b"m-2", &[0xff]) + ), + Some("m-2".to_string()) + ); + } + + #[test] + fn test_client_ack_request_ignores_messages_that_did_not_ask() { + // Carries an id but does not opt in. + assert!(client_ack_request(&MessageType::Json, r#"{"messageId":"m-1"}"#).is_none()); + // Opts in with no id, so there is nothing an acknowledgement could name. + assert!(client_ack_request(&MessageType::Json, r#"{"ack":true}"#).is_none()); + assert!(client_ack_request( + &MessageType::Binary, + &frame(b"updates", 0x0, b"m-2", &[0xff]) + ) + .is_none()); + assert!( + client_ack_request(&MessageType::Binary, &frame(b"updates", 0x1, b"", &[0xff])) + .is_none() + ); + } +} diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index ae6efe8e..cba242da 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, fmt::{Debug, Display}, - sync::{Arc, RwLock}, + sync::{Arc, OnceLock, RwLock}, }; use async_trait::async_trait; @@ -16,7 +16,7 @@ use tracing::{debug, error, info}; use crate::{ acks::{AckStatus, AckWorkerMessage, MessageAction, Worker}, errors::WebSocketConnError, - message_helpers::{create_message_lost_event, create_ws_message}, + message_helpers::{client_ack_request, create_message_lost_event, create_ws_message}, types::{ AckMessage, AckWorkerConfig, Message as RegistryMessage, MessageType, WebSocketMessage, }, @@ -83,6 +83,16 @@ pub struct WebSocketConnRegistry { connections: Arc>>>>, // A channel for sending messages to the ack worker. ack_sender: Mutex>>, + // A channel for the worker that tracks acknowledgements from clients, as + // distinct from the one above, which tracks them from other nodes. + // + // Held separately because the two answer different questions. A node + // confirming it took a message on is not a client confirming it received + // one, and only the node holding a connection can be told the second. + // + // Written once, before the worker is spawned, so a send can never find it + // empty and drop the tracking for a message that asked to be acknowledged. + client_ack_sender: OnceLock>, // This is called "broadcaster" because it is used to send messages to all // other nodes in a cluster, however, it should not be confused with a broadcast::Sender // for in-process broadcasting. Typically, there will be a single receiver in the same process @@ -104,11 +114,166 @@ impl WebSocketConnRegistry { ack_worker_config: config.ack_worker_config, connections: Arc::new(RwLock::new(HashMap::new())), ack_sender: Mutex::new(None), + client_ack_sender: OnceLock::new(), broadcaster, server_node_name: config.server_node_name, } } + /// Starts the worker that tracks acknowledgements from clients. + /// + /// Started whatever the deployment, unlike the worker for acknowledgements + /// between nodes, because a client acknowledges to the node holding its + /// connection and a single node has clients just the same as a cluster + /// does. + pub fn start_client_ack_worker(self: Arc) { + let (ack_tx, ack_rx) = tokio::sync::mpsc::channel(1024); + let (action_tx, mut action_rx) = tokio::sync::mpsc::channel(1024); + Worker::new(self.ack_worker_config.clone().unwrap_or_default()).start(ack_rx, action_tx); + + // Published before the worker is spawned rather than from inside it, so + // that a send arriving between this returning and the task first being + // polled is still tracked. + let _ = self.client_ack_sender.set(ack_tx); + + tokio::spawn(async move { + while let Some(action) = action_rx.recv().await { + match action { + MessageAction::Resend(resend) => { + let Some(connection) = self.get_connection(resend.client_id.clone()) else { + debug!( + connection_id = %resend.client_id, + message_id = %resend.message_id, + "client has gone, so a message waiting on it is left to be declared lost" + ); + continue; + }; + let message = match create_ws_message( + resend.message_type.clone(), + resend.message.clone(), + ) { + Ok(message) => message, + Err(err) => { + error!( + message_id = %resend.message_id, + "could not rebuild a message to resend to a client: {err:?}" + ); + continue; + } + }; + + // Noted again, which counts the attempt and restarts the + // clock. Without it the attempt that has just been made + // is never counted, so a message nobody answers is sent + // again on every check and never reaches the point of + // being declared lost. A message sent between nodes + // gets this from being resent through the send path, + // which records it on the way past, but a client's + // resend goes straight to the socket. + let client_id = resend.client_id.clone(); + let message_id = resend.message_id.clone(); + self.record_pending_client_ack( + resend.client_id, + resend.message_id, + resend.message_type, + resend.message, + resend.inform_clients_on_loss, + resend.caller, + ) + .await; + + let mut sender = connection.lock().await; + if let Err(err) = sender.send(message).await { + debug!( + connection_id = %client_id, + message_id = %message_id, + "failed to resend a message to a client: {err:?}" + ); + } + } + MessageAction::Lost { + message_id, + inform_clients, + caller, + } => { + info!( + message_id = %message_id, + "a client did not acknowledge a message, treating it as lost" + ); + self.inform_clients_of_loss(message_id, inform_clients, caller) + .await; + } + } + } + }); + } + + /// Notes that a message is waiting on its client to acknowledge it. + async fn record_pending_client_ack( + &self, + connection_id: String, + message_id: String, + message_type: MessageType, + message: String, + inform_clients: Vec, + caller: Option, + ) { + if let Some(sender) = self.client_ack_sender.get() { + let _ = sender + .send(AckWorkerMessage::Status( + message_id, + AckStatus::Pending { + connection_id, + message, + message_type, + inform_clients, + caller, + }, + )) + .await; + } + } + + /// Records that a client acknowledged a message, so it stops being tracked. + /// + /// Named by the connection it came from, since a message is only settled by + /// the client it was sent to. + pub async fn record_client_ack(&self, connection_id: String, message_id: String) { + if let Some(sender) = self.client_ack_sender.get() { + let _ = sender + .send(AckWorkerMessage::ClientAck { + message_id, + connection_id, + }) + .await; + } + } + + /// Tells the clients named by a send that its message may not have arrived. + /// + /// Only those connected to this node are reachable from here, which is the + /// best effort the protocol asks for. + async fn inform_clients_of_loss( + &self, + message_id: String, + inform_clients: Vec, + caller: Option, + ) { + for client_id in inform_clients { + let Some(connection) = self.get_connection(client_id.clone()) else { + continue; + }; + let event = create_message_lost_event(message_id.clone(), caller.clone()); + let mut sender = connection.lock().await; + if let Err(err) = sender.send(Message::Binary(event.into())).await { + debug!( + connection_id = %client_id, + "failed to tell a client about a lost message: {err:?}" + ); + } + } + } + /// Starts the ack worker if a broadcaster is present in the registry. /// When the current node is a part of a cluster and messages will be broadcast /// to other nodes in the cluster, this must be called before setting up the listener @@ -403,6 +568,22 @@ impl WebSocketRegistrySend for WebSocketConnRegistry { "acquiring lock to send message to connection: {}", connection_id ); + + let send_ctx = ctx.unwrap_or_default(); + let awaiting_ack = client_ack_request(&message_type, &message); + + if let Some(ack_id) = awaiting_ack { + self.record_pending_client_ack( + connection_id.clone(), + ack_id, + message_type.clone(), + message.clone(), + send_ctx.inform_clients, + send_ctx.caller, + ) + .await; + } + let mut connection = connection.lock().await; debug!(connection_id = %connection_id, "sending message to connection: {}", connection_id); let ws_message = create_ws_message(message_type, message)?; @@ -479,6 +660,7 @@ mod tests { use std::{ future::Future, net::{Ipv4Addr, SocketAddr}, + time::Duration, }; use super::*; @@ -489,6 +671,7 @@ mod tests { Router, }; + use base64::Engine as _; use futures::{FutureExt, SinkExt, StreamExt}; use nanoid::nanoid; use serde::{Deserialize, Serialize}; @@ -931,6 +1114,288 @@ mod tests { ); } + /// Sets up a registry serving one client, with acknowledgement timings + /// short enough for a test to watch a resend happen. + async fn registry_with_one_client() -> ( + Arc, + String, + tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + ) { + let (tx, _) = tokio::sync::mpsc::channel(1024); + let registry = Arc::new(WebSocketConnRegistry::new( + WebSocketConnRegistryConfig { + ack_worker_config: Some(AckWorkerConfig { + message_action_check_interval_ms: Some(50), + message_timeout_ms: Some(100), + max_attempts: Some(3), + }), + server_node_name: "node1".to_string(), + }, + Some(tx), + )); + registry.clone().start_client_ack_worker(); + + 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 (socket, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + wait_for_connection_count(®istry, 1).await; + let connection_id = registry.get_connections()[0].0.clone(); + + (registry, connection_id, socket) + } + + /// A message that asks to be acknowledged is chased until the client + /// answers, and stops once it does. + #[test_log::test(tokio::test)] + async fn test_a_message_asking_to_be_acknowledged_is_settled_by_the_client() { + let (registry, connection_id, mut socket) = registry_with_one_client().await; + + registry + .send_message( + connection_id.clone(), + "m-1".to_string(), + MessageType::Json, + r#"{"event":"update","data":{"value":1},"messageId":"m-1","ack":true}"#.to_string(), + Some(SendContext { + wait_for_ack: false, + caller: None, + inform_clients: vec![], + }), + ) + .await + .unwrap(); + + let received = match socket.next().await.unwrap().unwrap() { + tungstenite::Message::Text(msg) => msg, + other => panic!("Unexpected message but got {other:?}"), + }; + let received: serde_json::Value = serde_json::from_str(&received).unwrap(); + // Delivered as composed, opt in and all. + assert_eq!(received["data"]["value"], 1); + assert_eq!(received["messageId"], "m-1"); + assert_eq!(received["ack"], true); + + registry + .record_client_ack(connection_id, "m-1".to_string()) + .await; + + // Long enough for several rounds of the worker's checks, so a message + // still being chased would show up here. + let resent = tokio::time::timeout(Duration::from_millis(400), socket.next()).await; + assert!( + resent.is_err(), + "an acknowledged message should stop being resent, got {resent:?}" + ); + } + + /// Binary messages ask to be acknowledged the same way JSON ones do, by + /// saying so in the frame the application composed. + #[test_log::test(tokio::test)] + async fn test_a_binary_message_can_ask_to_be_acknowledged() { + let (registry, connection_id, mut socket) = registry_with_one_client().await; + + // [routeLength][route][requireAck][messageIdLength][messageId][payload] + let mut original = vec![7u8]; + original.extend_from_slice(b"updates"); + original.push(0x1); + original.push(5); + original.extend_from_slice(b"m-bin"); + original.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + + registry + .send_message( + connection_id.clone(), + "m-bin".to_string(), + MessageType::Binary, + base64::prelude::BASE64_STANDARD.encode(&original), + Some(SendContext { + wait_for_ack: false, + caller: None, + inform_clients: vec![], + }), + ) + .await + .unwrap(); + + let received = match socket.next().await.unwrap().unwrap() { + tungstenite::Message::Binary(bytes) => bytes, + other => panic!("Unexpected message but got {other:?}"), + }; + + // Delivered exactly as the application framed it. The runtime reads the + // opt in, it does not add or change one. + assert_eq!(&received[..], original.as_slice()); + + registry + .record_client_ack(connection_id, "m-bin".to_string()) + .await; + let resent = tokio::time::timeout(Duration::from_millis(400), socket.next()).await; + assert!( + resent.is_err(), + "an acknowledged message should not be resent" + ); + } + + /// A message nobody ever acknowledges is eventually given up on. + /// + /// Each resend has to count as an attempt, or the message is sent again on + /// every check for as long as the connection lives and the clients waiting + /// to hear that it went missing never do. + #[test_log::test(tokio::test)] + async fn test_a_message_nobody_acknowledges_is_declared_lost() { + let (registry, connection_id, mut socket) = registry_with_one_client().await; + + registry + .send_message( + connection_id.clone(), + "m-4".to_string(), + MessageType::Json, + r#"{"event":"update","data":{"value":4},"messageId":"m-4","ack":true}"#.to_string(), + Some(SendContext { + wait_for_ack: false, + caller: Some("caller-route".to_string()), + // Told to itself, so the loss event lands somewhere this + // test can watch. + inform_clients: vec![connection_id], + }), + ) + .await + .unwrap(); + + // Three attempts at 100ms apart, checked every 50ms, so a second or so + // covers the escalation with room for a loaded machine. + let lost = tokio::time::timeout(Duration::from_secs(3), async { + while let Some(Ok(message)) = socket.next().await { + if let tungstenite::Message::Binary(bytes) = message { + if bytes.starts_with(&[0x1, 0x3, 0x0, 0x0]) { + let payload: serde_json::Value = + serde_json::from_slice(&bytes[4..]).unwrap(); + return Some(payload); + } + } + } + None + }) + .await + .expect("a message nobody acknowledges should be declared lost rather than resent forever"); + + let payload = lost.expect("the connection closed before the loss event arrived"); + assert_eq!(payload["messageId"], "m-4"); + assert_eq!(payload["caller"], "caller-route"); + } + + /// A message is only settled by the client it was sent to. + /// + /// A message id is chosen by the application, so it says nothing about who + /// the message went to, and the same id may be in flight to several clients + /// at once. An acknowledgement from anyone else has to count for nothing, + /// or one client can call off the resend and the loss event another is + /// relying on. + #[test_log::test(tokio::test)] + async fn test_a_message_is_not_settled_by_a_different_connection() { + let (registry, connection_id, mut socket) = registry_with_one_client().await; + + registry + .send_message( + connection_id, + "m-3".to_string(), + MessageType::Json, + r#"{"event":"update","data":{"value":3},"messageId":"m-3","ack":true}"#.to_string(), + Some(SendContext { + wait_for_ack: false, + caller: None, + inform_clients: vec![], + }), + ) + .await + .unwrap(); + + registry + .record_client_ack("another-connection".to_string(), "m-3".to_string()) + .await; + + let mut deliveries = 0; + while let Ok(Some(Ok(message))) = + tokio::time::timeout(Duration::from_millis(400), socket.next()).await + { + if let tungstenite::Message::Text(text) = message { + let value: serde_json::Value = serde_json::from_str(&text).unwrap(); + if value["messageId"] == "m-3" { + deliveries += 1; + } + } + if deliveries > 1 { + break; + } + } + + assert!( + deliveries > 1, + "an acknowledgement from another connection should settle nothing, \ + but the message stopped being resent after {deliveries} delivery(s)" + ); + } + + /// A message the client never acknowledges is sent again. + #[test_log::test(tokio::test)] + async fn test_a_message_asking_to_be_acknowledged_is_resent_while_unanswered() { + let (registry, connection_id, mut socket) = registry_with_one_client().await; + + registry + .send_message( + connection_id, + "m-2".to_string(), + MessageType::Json, + r#"{"event":"update","data":{"value":2},"messageId":"m-2","ack":true}"#.to_string(), + Some(SendContext { + wait_for_ack: false, + caller: None, + inform_clients: vec![], + }), + ) + .await + .unwrap(); + + let mut deliveries = 0; + while let Ok(Some(Ok(message))) = + tokio::time::timeout(Duration::from_millis(400), socket.next()).await + { + if let tungstenite::Message::Text(text) = message { + let value: serde_json::Value = serde_json::from_str(&text).unwrap(); + if value["messageId"] == "m-2" { + deliveries += 1; + } + } + if deliveries > 1 { + break; + } + } + + assert!( + deliveries > 1, + "a message nobody acknowledged should be sent again, saw it {deliveries} time(s)" + ); + } + /// Waits for the registry to hold the given number of connections. /// /// Registration and removal happen on the connection's own task, so a test