From a9fb3d3e7f70d1c9b204b908b20100ea47406fe0 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 16 Aug 2026 20:07:31 +0100 Subject: [PATCH 1/6] feat(lib-rt-core): recognise a client acknowledging a message A client answers an acknowledgement with a message whose route is reserved by the protocol. It names that route with `event`, which is fixed, so against an API that routes on anything else the message carries no route the runtime knows and falls through to the default handler. An application with a default handler was being handed every acknowledgement its clients sent, as though a client had sent it something. Both encodings are now taken out of the way before routing, alongside the heartbeat, which is the same kind of message and already handled there. Nothing waits on these yet. Recognising them is what the tracking of server sent messages will need, and until that exists an acknowledgement is noted and dropped. The test covers this against an API that routes on something other than `event` and has a default handler, since that is the shape where the difference shows. Against the default route key an acknowledgement resolves to a route no handler serves and goes nowhere either way, so a test built that way passes whether or not any of this is here. --- libs/runtime/core/src/websocket.rs | 86 +++++++++++++++++++ ...ipc-websocket-default-route.blueprint.yaml | 70 +++++++++++++++ .../runtime/core/tests/ipc_end_to_end_test.rs | 59 +++++++++++++ 3 files changed, 215 insertions(+) create mode 100644 libs/runtime/core/tests/data/fixtures/ipc-websocket-default-route.blueprint.yaml diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 970bf83e..17dbffa6 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -381,6 +381,17 @@ async fn handle_socket( continue; } + // A client acknowledging something the runtime sent it. This is + // handled before routing, to avoid getting it confused with a routed message + // that would otherwise fallback to the default handler. + if let Some(acknowledged) = detect_client_ack(&msg) { + debug!( + "client {connection_id} acknowledged message {acknowledged}, \ + which nothing is waiting on yet" + ); + continue; + } + if !is_authenticated { // Connection is in unauthenticated state (authMessage strategy). // Only accept an "authenticate" message; reject everything else. @@ -1264,6 +1275,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 +1322,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 +1648,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..758a2974 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1569,6 +1569,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( From 48c0068f6a351780b93fe54db048b80e5ade0f70 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 16 Aug 2026 21:07:06 +0100 Subject: [PATCH 2/6] feat(lib-rt-core): wait for a client to acknowledge what it was sent A message can say it wants an acknowledgement, in either direction. A client saying so has been answered since the last change, but nothing was done about a server message saying the same, so an application had no way to find out whether what it sent ever arrived. The runtime now reads the opt in from the message it is given, in whichever encoding, and waits for the client. A message that goes unanswered is sent again, and after enough attempts is treated as lost and the clients named by the send are told so. An acknowledgement from the client settles it. Read from the message rather than asked for alongside it, because that is where the protocol puts it and where the other direction already reads it from. One statement of intent, one id, and the id a client names when it answers is the id the message is tracked under, so the two cannot come apart. Nothing the application composed is altered on the way out. The worker that tracks this is started for every deployment, unlike the one for acknowledgements between nodes, since a client acknowledges to the node holding its connection and a single node has clients just the same. --- libs/runtime/core/src/application.rs | 4 + libs/runtime/core/src/websocket.rs | 6 +- .../ws/ws-registry/src/message_helpers.rs | 83 ++++- libs/runtime/ws/ws-registry/src/registry.rs | 334 +++++++++++++++++- 4 files changed, 420 insertions(+), 7 deletions(-) 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 17dbffa6..112e3af4 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -385,10 +385,8 @@ async fn handle_socket( // handled before routing, to avoid getting it confused with a routed message // that would otherwise fallback to the default handler. if let Some(acknowledged) = detect_client_ack(&msg) { - debug!( - "client {connection_id} acknowledged message {acknowledged}, \ - which nothing is waiting on yet" - ); + debug!("client {connection_id} acknowledged message {acknowledged}"); + state.connections.record_client_ack(acknowledged).await; continue; } 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..890fd11a 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -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,13 @@ 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. + client_ack_sender: Mutex>>, // 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 +111,137 @@ impl WebSocketConnRegistry { ack_worker_config: config.ack_worker_config, connections: Arc::new(RwLock::new(HashMap::new())), ack_sender: Mutex::new(None), + client_ack_sender: Mutex::new(None), 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); + + tokio::spawn(async move { + { + let mut sender = self.client_ack_sender.lock().await; + sender.replace(ack_tx); + } + + 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, 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; + } + }; + let mut sender = connection.lock().await; + if let Err(err) = sender.send(message).await { + debug!( + connection_id = %resend.client_id, + message_id = %resend.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.lock().await.as_ref() { + 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. + pub async fn record_client_ack(&self, message_id: String) { + if let Some(sender) = self.client_ack_sender.lock().await.as_ref() { + let _ = sender + .send(AckWorkerMessage::Status(message_id, AckStatus::Received)) + .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,10 +536,27 @@ 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); + 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)?; + let ws_message = create_ws_message(message_type.clone(), message.clone())?; connection.send(ws_message).await?; + drop(connection); + + if let Some(ack_id) = awaiting_ack { + self.record_pending_client_ack( + connection_id, + ack_id, + message_type, + message, + send_ctx.inform_clients, + send_ctx.caller, + ) + .await; + } } else if let Some(broadcaster) = &self.broadcaster { let send_ctx = ctx.unwrap_or_default(); debug!(connection_id = %connection_id, "connection not found locally, preparing to send message to broadcaster"); @@ -479,6 +629,7 @@ mod tests { use std::{ future::Future, net::{Ipv4Addr, SocketAddr}, + time::Duration, }; use super::*; @@ -489,6 +640,7 @@ mod tests { Router, }; + use base64::Engine as _; use futures::{FutureExt, SinkExt, StreamExt}; use nanoid::nanoid; use serde::{Deserialize, Serialize}; @@ -931,6 +1083,184 @@ 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, + "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("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, + "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("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 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 From 31b3f94e728d05505dab6dda0607871cfcd57de7 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 10:51:46 +0100 Subject: [PATCH 3/6] fix(lib-rt-ws-registry): hand out the client ack channel before the worker runs The channel a send uses to say a message is waiting on its client was being published from inside the spawned worker, so starting the worker returned before there was anything to publish to. A send arriving in that window found nothing there and took the quiet branch, leaving a message that asked to be acknowledged untracked, never resent and never reported lost. The channel is now handed out before the worker is spawned, which closes the window by construction rather than by the timing of when a task first gets polled. Writing it once also means a send no longer takes a lock to read it, and there is no guard left to hold across the send that follows. --- libs/runtime/ws/ws-registry/src/registry.rs | 23 ++++++++++++--------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 890fd11a..6e34c74b 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; @@ -89,7 +89,10 @@ pub struct WebSocketConnRegistry { // 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. - client_ack_sender: Mutex>>, + // + // 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 @@ -111,7 +114,7 @@ impl WebSocketConnRegistry { ack_worker_config: config.ack_worker_config, connections: Arc::new(RwLock::new(HashMap::new())), ack_sender: Mutex::new(None), - client_ack_sender: Mutex::new(None), + client_ack_sender: OnceLock::new(), broadcaster, server_node_name: config.server_node_name, } @@ -128,12 +131,12 @@ impl WebSocketConnRegistry { 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); - tokio::spawn(async move { - { - let mut sender = self.client_ack_sender.lock().await; - sender.replace(ack_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) => { @@ -192,7 +195,7 @@ impl WebSocketConnRegistry { inform_clients: Vec, caller: Option, ) { - if let Some(sender) = self.client_ack_sender.lock().await.as_ref() { + if let Some(sender) = self.client_ack_sender.get() { let _ = sender .send(AckWorkerMessage::Status( message_id, @@ -210,7 +213,7 @@ impl WebSocketConnRegistry { /// Records that a client acknowledged a message, so it stops being tracked. pub async fn record_client_ack(&self, message_id: String) { - if let Some(sender) = self.client_ack_sender.lock().await.as_ref() { + if let Some(sender) = self.client_ack_sender.get() { let _ = sender .send(AckWorkerMessage::Status(message_id, AckStatus::Received)) .await; From 94cca183fa73f112ea2fb099a97f332857537033 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 11:03:48 +0100 Subject: [PATCH 4/6] fix(lib-rt-ws-registry): take a message as settled only from the client it was sent to Messages waiting on a client are tracked by their id alone, and an acknowledgement arriving from a connection carried no sign of where it came from, so whichever client answered first settled the message for everyone. An id is chosen by the application, which means it says nothing about who the message went to, the same id may be in flight to several clients at once, and an id worth guessing is usually guessable. A client could therefore call off a resend, and the loss event that follows it, for a message it was never sent. An acknowledgement now names the connection it came from and settles a message only when that connection is the one owed it. Anything else is noted and dropped, leaving the attempt count and timing as they were, since nothing about them has changed. Acknowledgements are also read after the authentication gate rather than before it, so a client that has yet to prove who it is can no longer reach any of this. Taking them out of the way early was about keeping them from being routed as ordinary messages, and doing that inside the authenticated path serves the same purpose without the reach. --- libs/runtime/core/src/websocket.rs | 26 ++++--- .../runtime/core/tests/ipc_end_to_end_test.rs | 54 ++++++++++++++ libs/runtime/ws/ws-registry/src/acks.rs | 48 ++++++++++++ libs/runtime/ws/ws-registry/src/registry.rs | 74 +++++++++++++++++-- 4 files changed, 187 insertions(+), 15 deletions(-) diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 112e3af4..d01c160d 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -381,15 +381,6 @@ async fn handle_socket( continue; } - // A client acknowledging something the runtime sent it. This is - // handled before routing, to avoid getting it confused with a routed message - // that would otherwise fallback to the default handler. - if let Some(acknowledged) = detect_client_ack(&msg) { - debug!("client {connection_id} acknowledged message {acknowledged}"); - state.connections.record_client_ack(acknowledged).await; - continue; - } - if !is_authenticated { // Connection is in unauthenticated state (authMessage strategy). // Only accept an "authenticate" message; reject everything else. @@ -426,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 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 758a2974..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( 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/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 6e34c74b..7606aaed 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -212,10 +212,16 @@ impl WebSocketConnRegistry { } /// Records that a client acknowledged a message, so it stops being tracked. - pub async fn record_client_ack(&self, message_id: String) { + /// + /// 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::Status(message_id, AckStatus::Received)) + .send(AckWorkerMessage::ClientAck { + message_id, + connection_id, + }) .await; } } @@ -1143,7 +1149,7 @@ mod tests { registry .send_message( - connection_id, + connection_id.clone(), "m-1".to_string(), MessageType::Json, r#"{"event":"update","data":{"value":1},"messageId":"m-1","ack":true}"#.to_string(), @@ -1166,7 +1172,9 @@ mod tests { assert_eq!(received["messageId"], "m-1"); assert_eq!(received["ack"], true); - registry.record_client_ack("m-1".to_string()).await; + 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. @@ -1193,7 +1201,7 @@ mod tests { registry .send_message( - connection_id, + connection_id.clone(), "m-bin".to_string(), MessageType::Binary, base64::prelude::BASE64_STANDARD.encode(&original), @@ -1215,7 +1223,9 @@ mod tests { // opt in, it does not add or change one. assert_eq!(&received[..], original.as_slice()); - registry.record_client_ack("m-bin".to_string()).await; + 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(), @@ -1223,6 +1233,58 @@ mod tests { ); } + /// 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() { From be807dced288810f624908c1e24476ef6332bcbd Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 11:18:07 +0100 Subject: [PATCH 5/6] fix(lib-rt-ws-registry): note a message as waiting before it goes out A message that asked to be acknowledged was noted as waiting only after it had been handed to the socket, which left the answer able to arrive first. A client quick enough to reply in that window was heard by the worker while nothing was being tracked, so its acknowledgement settled nothing and was dropped. The note then landed, and the message was chased through every attempt and finally declared lost despite having arrived the first time. The note is now made before the send, which is the only order in which an answer always finds something waiting for it. One consequence worth knowing about. A send that fails now leaves the message tracked, so the caller is given its error and the clients named by the send are later told the message was lost. That reports one failure by two routes, but both are true, and the alternative of withdrawing the note afterwards is more machinery than the fix is worth. --- libs/runtime/ws/ws-registry/src/registry.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 7606aaed..723483a4 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -549,23 +549,22 @@ impl WebSocketRegistrySend for WebSocketConnRegistry { let send_ctx = ctx.unwrap_or_default(); let awaiting_ack = client_ack_request(&message_type, &message); - 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.clone(), message.clone())?; - connection.send(ws_message).await?; - drop(connection); - if let Some(ack_id) = awaiting_ack { self.record_pending_client_ack( - connection_id, + connection_id.clone(), ack_id, - message_type, - message, + 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)?; + connection.send(ws_message).await?; } else if let Some(broadcaster) = &self.broadcaster { let send_ctx = ctx.unwrap_or_default(); debug!(connection_id = %connection_id, "connection not found locally, preparing to send message to broadcaster"); From 6781caf9fa514cff47f694173cd759b9bb4fec24 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 11:33:57 +0100 Subject: [PATCH 6/6] fix(lib-rt-ws-registry): count a resend to a client as an attempt A message resent to a client was sent again without being noted again, so the attempt count stayed where it started and the clock never restarted. That left the timeout permanently expired and the limit permanently out of reach, which meant a message nobody answered was sent again on every check for as long as the connection lived and was never given up on. The clients named by the send were waiting to hear that it went missing and never could, because that outcome was unreachable. The resend now notes the message again before it goes back out, which counts the attempt and restarts the clock, so a message nobody answers reaches the end of its attempts and is declared lost. Noted in the client worker rather than in the check shared by both workers, because a message travelling between nodes is resent through the send path, which records it on the way past. Counting in the shared check would count that one twice and halve the attempts it is allowed. A client's resend goes straight to the socket, so it is the one that has to note the attempt itself. --- libs/runtime/ws/ws-registry/src/registry.rs | 97 ++++++++++++++++++--- 1 file changed, 84 insertions(+), 13 deletions(-) diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 723483a4..cba242da 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -148,22 +148,45 @@ impl WebSocketConnRegistry { ); continue; }; - let message = - match create_ws_message(resend.message_type, 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; - } - }; + 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 = %resend.client_id, - message_id = %resend.message_id, + connection_id = %client_id, + message_id = %message_id, "failed to resend a message to a client: {err:?}" ); } @@ -1232,6 +1255,54 @@ mod tests { ); } + /// 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