diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index 17a45ec6..e130bb82 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -189,6 +189,13 @@ pub const CELERITY_WS_FORBIDDEN_ERROR_CODE: u16 = 4002; // client to fall back to constrained capabilities (text-only). pub const CELERITY_WS_CAPABILITIES_SIGNAL: [u8; 4] = [0x1, 0x5, 0x0, 0x0]; +// The prefix of a binary acknowledgement, route key `0x4`, followed by the JSON +// body naming the message being acknowledged. +// +// A reserved message requires no acknowledgement of its own and carries no +// message id, which is what the two trailing zero bytes say. +pub const CELERITY_WS_ACK_SIGNAL: [u8; 4] = [0x1, 0x4, 0x0, 0x0]; + // The route key for the connect handler for a WebSocket API. // A handler registered with this route key will be called when a client // connects to the WebSocket API server after authentication has been performed diff --git a/libs/runtime/core/src/generated/celerity.runtime.v1.rs b/libs/runtime/core/src/generated/celerity.runtime.v1.rs index e1359b3c..d82cd4fd 100644 --- a/libs/runtime/core/src/generated/celerity.runtime.v1.rs +++ b/libs/runtime/core/src/generated/celerity.runtime.v1.rs @@ -292,6 +292,15 @@ pub struct WebSocketMessage { /// the two frame types as distinct. #[prost(bool, tag = "6")] pub is_binary: bool, + /// The id this message is known by, which is the one the client gave it when + /// it gave one and a runtime generated one otherwise. + /// + /// Distinct from request_id, which identifies the delivery. This identifies + /// the message, so it is what an acknowledgement names and what a lost + /// message notification refers to, and a handler needs it to tie its own + /// instrumentation to what the client sees. + #[prost(string, tag = "7")] + pub message_id: ::prost::alloc::string::String, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct ConsumerBatch { diff --git a/libs/runtime/core/src/ipc_frames.rs b/libs/runtime/core/src/ipc_frames.rs index d23e541a..c7c8aebd 100644 --- a/libs/runtime/core/src/ipc_frames.rs +++ b/libs/runtime/core/src/ipc_frames.rs @@ -115,6 +115,7 @@ fn websocket_message(message: WebSocketEventData) -> proto::WebSocketMessage { request_id: message.request_id.unwrap_or_default(), message: message.message.to_vec(), is_binary: message.is_binary, + message_id: message.message_id.unwrap_or_default(), } } diff --git a/libs/runtime/core/src/ipc_websocket.rs b/libs/runtime/core/src/ipc_websocket.rs index 3b92731c..8b333204 100644 --- a/libs/runtime/core/src/ipc_websocket.rs +++ b/libs/runtime/core/src/ipc_websocket.rs @@ -60,6 +60,7 @@ impl IpcWebSocketHandler { &self, connection_id: String, request_id: Option, + message_id: Option, client_ip: String, message: Bytes, is_binary: bool, @@ -77,6 +78,7 @@ impl IpcWebSocketHandler { connection_id, source_ip: client_ip, request_id, + message_id, message, is_binary, }), @@ -187,6 +189,7 @@ impl WebSocketMessageHandler for IpcWebSocketHandler { .request_ctx .as_ref() .map(|ctx| ctx.request_id.clone()), + Some(message.message_id), message .request_ctx .as_ref() @@ -212,6 +215,7 @@ impl WebSocketMessageHandler for IpcWebSocketHandler { .request_ctx .as_ref() .map(|ctx| ctx.request_id.clone()), + Some(message.message_id), message .request_ctx .as_ref() diff --git a/libs/runtime/core/src/types.rs b/libs/runtime/core/src/types.rs index f7d88e91..a8b1ffe2 100644 --- a/libs/runtime/core/src/types.rs +++ b/libs/runtime/core/src/types.rs @@ -79,6 +79,11 @@ pub struct WebSocketEventData { #[serde(rename = "requestId")] #[serde(skip_serializing_if = "Option::is_none")] pub request_id: Option, + /// The id the client gave this message, as distinct from `request_id`, + /// which the runtime assigns so that every message can be traced. + #[serde(rename = "messageId")] + #[serde(skip_serializing_if = "Option::is_none")] + pub message_id: Option, /// The message exactly as it arrived. pub message: Bytes, /// Whether this arrived as a binary frame rather than a text one. Bytes diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 7f594b7a..970bf83e 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -45,7 +45,7 @@ use crate::{ }, auth_jwt::{validate_jwt_on_ws_connect, ValidateJwtError}, consts::{ - CELERITY_WS_CAPABILITIES_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, + CELERITY_WS_ACK_SIGNAL, 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, @@ -429,6 +429,10 @@ async fn handle_socket( // 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. + // Read before the message is handed on, since handing it on + // gives it away. + let ack = ack_request(&msg); + match work_tx .send_timeout( (msg, request_ctx.clone()), @@ -436,7 +440,19 @@ async fn handle_socket( ) .await { - Ok(()) => {} + Ok(()) => { + // Answered as soon as the message is taken in, since + // that is what an acknowledgement says. Anything + // that happens to it afterwards, however long it + // takes, is not what the client is waiting to hear. + // + // Sent once it is safely queued and not before, so + // nothing is acknowledged that then gets shed to + // process incoming messages. + if let Some((message_id, format)) = ack { + acknowledge(&socket_ref, &connection_id, &message_id, format).await; + } + } Err(SendTimeoutError::Timeout(_)) => { warn!( "client {connection_id} is sending faster than its handlers can \ @@ -1034,7 +1050,7 @@ async fn process_message( connection_id.clone(), state.route_key.clone(), )?; - if let Some((route, message_id, data)) = resolved { + if let Some((route, message_id, _requires_ack, data)) = resolved { if let Some(handler) = get_message_route_handler(&route, state).await { handle_json_message( handler.clone(), @@ -1055,7 +1071,7 @@ async fn process_message( } Message::Binary(bytes) => { let resolved = resolve_binary_route(&bytes, connection_id.clone())?; - if let Some((route, message_id, bytes_stripped)) = resolved { + if let Some((route, message_id, _requires_ack, bytes_stripped)) = resolved { if let Some(handler) = get_message_route_handler(&route, state).await { handle_binary_message( handler.clone(), @@ -1237,7 +1253,103 @@ async fn handle_binary_message( .await; } -type JsonRouteData = (String, Option, Value); +/// Which encoding an acknowledgement goes back in. +/// +/// It mirrors whatever the message being acknowledged arrived as. A client that +/// can send binary can read it, and one that only has text, because its +/// environment gave it no choice, gets text back. +#[derive(Clone, Copy, Debug)] +enum AckFormat { + Json, + Binary, +} + +/// 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 +/// out not to opt in, which costs a parse that then finds nothing. It must not +/// say no to one that does, which is why it looks for the key rather than for +/// the word. +fn has_ack_key(text: &str) -> bool { + text.match_indices("\"ack\"") + .any(|(index, matched)| text[index + matched.len()..].trim_start().starts_with(':')) +} + +fn ack_request(msg: &Message) -> Option<(String, AckFormat)> { + match msg { + Message::Text(text) => { + // Parsing every text message twice to find out that almost none of + // them opt in is not worth it, so a message that does not carry the + // key is passed over before it is parsed at all. + // + // Matched as a key rather than anywhere in the text, since a + // message is free to carry "ack" as a value and many will. + if !has_ack_key(text) { + return None; + } + let value: Value = serde_json::from_str(text).ok()?; + let object = value.as_object()?; + if object.get("ack").and_then(Value::as_bool) != Some(true) { + return None; + } + let message_id = object.get("messageId").and_then(Value::as_str)?; + Some((message_id.to_string(), AckFormat::Json)) + } + Message::Binary(bytes) => { + // `[routeLength][route][requireAck][messageIdLength][messageId]`, + // read far enough to answer and no further. + let route_length = *bytes.first()? as usize; + let requires_ack = *bytes.get(1 + route_length)? == 0x1; + if !requires_ack { + return None; + } + let message_id_length = *bytes.get(route_length + 2)? as usize; + let start = route_length + 3; + let message_id = bytes.get(start..start + message_id_length)?; + let message_id = std::str::from_utf8(message_id).ok()?; + if message_id.is_empty() { + return None; + } + Some((message_id.to_string(), AckFormat::Binary)) + } + _ => None, + } +} + +/// Tells the client its message arrived. +async fn acknowledge( + socket_ref: &Arc>, + connection_id: &str, + message_id: &str, + format: AckFormat, +) { + let timestamp = get_epoch_seconds().to_string(); + let message = match format { + AckFormat::Json => Message::Text( + serde_json::json!({ + "event": "ack", + "data": { "messageId": message_id, "timestamp": timestamp }, + }) + .to_string() + .into(), + ), + AckFormat::Binary => { + let body = + serde_json::json!({ "messageId": message_id, "timestamp": timestamp }).to_string(); + let mut frame = CELERITY_WS_ACK_SIGNAL.to_vec(); + frame.extend_from_slice(body.as_bytes()); + Message::Binary(frame.into()) + } + }; + + if let Err(err) = socket_ref.lock().await.send(message).await { + error!("failed to acknowledge a message from client {connection_id}: {err}"); + } +} + +/// A JSON message's route, its message id, whether it asked to be acknowledged, +/// and the body as it arrived. +type JsonRouteData = (String, Option, bool, Value); fn resolve_route( msg_text: String, @@ -1264,10 +1376,22 @@ fn resolve_route( return ControlFlow::Continue(None); } }; + // The id the application chose, which is what a lost message notification + // has to name for the application to act on it. The runtime falls back to + // one of its own only when a message carries none. + let message_id = data_obj + .get("messageId") + .and_then(Value::as_str) + .map(str::to_string); + // Opting in without an id is ignored, since an acknowledgement has nothing + // to name. + let requires_ack = + message_id.is_some() && data_obj.get("ack").and_then(Value::as_bool) == Some(true); + let route_opt = data_obj.get(&route_key); if let Some(route_val) = route_opt { if let Value::String(route) = route_val { - ControlFlow::Continue(Some((route.clone(), None, data))) + ControlFlow::Continue(Some((route.clone(), message_id, requires_ack, data))) } else { error!( "invalid JSON message from client {}, expected route value to be a string", @@ -1284,29 +1408,44 @@ fn resolve_route( ); ControlFlow::Continue(Some(( CELERITY_WS_DEFAULT_MESSAGE_HANDLER_ROUTE.to_string(), - None, + message_id, + requires_ack, data, ))) } } -type BinaryRouteData<'a> = (String, Option, &'a [u8]); +/// A binary message's route, its message id, whether it asked to be +/// acknowledged, and the payload left once the framing is stripped. +type BinaryRouteData<'a> = (String, Option, bool, &'a [u8]); +/// Splits a binary message into its framing and its payload. +/// +/// The format is ``. +/// Every length is a single byte, so nothing here can read past a message that +/// carries the bytes it says it does, and a message that does not is refused +/// rather than trusted. fn resolve_binary_route<'a>( msg_bytes: &'a [u8], connection_id: String, ) -> ControlFlow<(), Option>> { - let route_length = msg_bytes[0]; - if route_length as usize > msg_bytes.len() - 1 { + let Some(&route_length) = msg_bytes.first() else { + error!("invalid binary message from client {connection_id}, message is empty"); + return ControlFlow::Continue(None); + }; + let route_end = 1 + route_length as usize; + + // The route is followed by the acknowledgement flag and the message id + // length, so both have to be there for the message to be complete. + if msg_bytes.len() < route_end + 2 { error!( - "invalid binary message from client {}, route length exceeds message length", + "invalid binary message from client {}, message is shorter than its own framing", connection_id ); return ControlFlow::Continue(None); } - let route_result = std::str::from_utf8(&msg_bytes[1..=route_length as usize]); - let route = match route_result { + let route = match std::str::from_utf8(&msg_bytes[1..route_end]) { Ok(route) => route, Err(e) => { error!( @@ -1317,8 +1456,12 @@ fn resolve_binary_route<'a>( } }; - let message_id_length = msg_bytes[route_length as usize + 1]; - if message_id_length as usize > msg_bytes.len() - 1 { + let requires_ack = msg_bytes[route_end] == 0x1; + + let message_id_length = msg_bytes[route_end + 1] as usize; + let message_id_start = route_end + 2; + let message_id_end = message_id_start + message_id_length; + if msg_bytes.len() < message_id_end { error!( "invalid binary message from client {}, message id length exceeds message length", connection_id @@ -1327,21 +1470,25 @@ fn resolve_binary_route<'a>( } let message_id = if message_id_length > 0 { - let start_idx = route_length as usize + 2; - let end_idx = start_idx + message_id_length as usize; - let message_id_bytes = &msg_bytes[start_idx..end_idx]; - let message_id_str = std::str::from_utf8(message_id_bytes).unwrap(); - Some(message_id_str.to_string()) + match std::str::from_utf8(&msg_bytes[message_id_start..message_id_end]) { + Ok(message_id) => Some(message_id.to_string()), + Err(e) => { + error!( + "invalid binary message from client {}, failed to parse message id: {}", + connection_id, e + ); + return ControlFlow::Continue(None); + } + } } else { None }; - let data_start_idx = route_length as usize + 2 + message_id_length as usize; - ControlFlow::Continue(Some(( route.to_string(), message_id, - &msg_bytes[data_start_idx..], + requires_ack, + &msg_bytes[message_id_end..], ))) } @@ -1447,6 +1594,59 @@ async fn close_with_retry_after(socket_ref: Arc>, ret mod tests { use super::*; + #[test] + fn test_has_ack_key_ignores_ack_as_a_value() { + // Reserved as an event value by the protocol itself, so a message + // carrying it is ordinary rather than an opt in. + assert!(!has_ack_key(r#"{"event":"ack","data":{}}"#)); + assert!(!has_ack_key(r#"{"event":"send","data":{"type":"ack"}}"#)); + } + + #[test] + fn test_has_ack_key_finds_the_key() { + assert!(has_ack_key(r#"{"ack":true,"messageId":"1"}"#)); + // Whitespace is legal JSON either side of the colon. + assert!(has_ack_key(r#"{"ack" : true}"#)); + // Present as a value elsewhere as well as a key. + assert!(has_ack_key(r#"{"event":"ack","ack":true}"#)); + } + + #[test] + fn test_ack_request_reads_a_binary_frame() { + // [routeLength][route][requireAck][messageIdLength][messageId][payload] + let mut frame = vec![2u8]; + frame.extend_from_slice(b"ab"); + frame.push(0x1); + frame.push(3); + frame.extend_from_slice(b"m-1"); + frame.extend_from_slice(&[0xff, 0x00]); + + let request = ack_request(&Message::Binary(frame.into())); + let Some((message_id, AckFormat::Binary)) = request else { + panic!("expected a binary acknowledgement request, got {request:?}"); + }; + assert_eq!(message_id, "m-1"); + } + + #[test] + fn test_ack_request_ignores_a_binary_frame_that_did_not_ask() { + let mut frame = vec![2u8]; + frame.extend_from_slice(b"ab"); + frame.push(0x0); + frame.push(3); + frame.extend_from_slice(b"m-1"); + + assert!(ack_request(&Message::Binary(frame.into())).is_none()); + } + + #[test] + fn test_ack_request_refuses_a_frame_that_is_shorter_than_it_claims() { + // Claims a route longer than the bytes that follow it, so reading the + // acknowledgement flag would run off the end. + let frame = vec![9u8, b'a', b'b']; + assert!(ack_request(&Message::Binary(frame.into())).is_none()); + } + #[test] fn test_detect_json_ping() { let msg = Message::Text(r#"{"ping":true}"#.into()); 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 e5fe0a3c..f96efacc 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -1392,6 +1392,233 @@ async fn does_not_reorder_messages_when_handling_them_off_the_read_loop() { let _ = tokio::fs::remove_file(&socket).await; } +#[test_log::test(tokio::test)] +async fn acknowledges_a_binary_message_that_asks_to_be_acknowledged() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-ack-binary", + "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"); + + // [routeLength][route][requireAck][messageIdLength][messageId][message], + // built the way the spec defines. + // The message id is what the acknowledgement has to name. + let route = b"sendMessage"; + let message_id = b"msg-1"; + let body: Vec = vec![0xde, 0xad, 0xbe, 0xef]; + let mut payload = vec![route.len() as u8]; + payload.extend_from_slice(route); + payload.push(0x1); + payload.push(message_id.len() as u8); + payload.extend_from_slice(message_id); + payload.extend_from_slice(&body); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Binary(payload)) + .await + .unwrap(); + + let ack = tokio::time::timeout(Duration::from_secs(5), async { + while let Some(Ok(message)) = socket_conn.next().await { + if let tokio_tungstenite::tungstenite::Message::Binary(bytes) = message { + if bytes.starts_with(&[0x1, 0x4, 0x0, 0x0]) { + return Some(bytes[4..].to_vec()); + } + } + } + None + }) + .await + .expect("the acknowledgement should not take five seconds"); + + let ack = ack.expect("a message that asks to be acknowledged should be acknowledged"); + let ack: serde_json::Value = serde_json::from_slice(&ack).unwrap(); + assert_eq!(ack["messageId"], "msg-1"); + assert!( + ack["timestamp"].is_string(), + "the acknowledgement should carry a timestamp, got {ack}" + ); + + let dispatch = handler + .next_dispatch() + .await + .expect("the message should still reach the handler"); + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + assert_eq!(&message.message[..], &body[..]); + // The handler is told the id the client used, so instrumentation on its + // side can be tied to what the client saw acknowledged. + assert_eq!(message.message_id, "msg-1"); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn acknowledges_a_json_message_that_asks_to_be_acknowledged() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-ack-json", + "tests/data/fixtures/ipc-websocket-api.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 WebSocket server should accept the connection"); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ + "event": "sendMessage", + "messageId": "msg-json-1", + "ack": true, + "data": { "text": "hello" }, + }) + .to_string(), + )) + .await + .unwrap(); + + // Answered in the encoding it arrived in, so a client that only has text + // because its environment gave it no choice can still read the reply. + let ack = 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"] == "ack" { + return Some(value); + } + } + } + } + None + }) + .await + .expect("the acknowledgement should not take five seconds"); + + let ack = ack.expect("a message that asks to be acknowledged should be acknowledged"); + assert_eq!(ack["data"]["messageId"], "msg-json-1"); + assert!(ack["data"]["timestamp"].is_string()); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn acknowledges_a_message_queued_behind_a_handler_that_is_still_running() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-ack-queued", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + // Answers nothing, so the first message is still being handled, for the + // whole of the ten second timeout this fixture sets, while the second + // arrives. + 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"); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "first": true } }).to_string(), + )) + .await + .unwrap(); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ + "event": "sendMessage", + "messageId": "queued-1", + "ack": true, + "data": { "second": true }, + }) + .to_string(), + )) + .await + .unwrap(); + + // Acknowledgement follows the message being taken in, not what happens to + // it after. Tying it to handling would leave this one waiting on the + // handler ahead of it, and a client that hears nothing sends it again for a + // message the runtime was holding the entire time. + let ack = 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["event"] == "ack" { + return Some(value); + } + } + } + } + None + }) + .await + .expect("the acknowledgement should not wait for the handler ahead of it"); + + let ack = ack.expect("the queued message should be acknowledged"); + assert_eq!(ack["data"]["messageId"], "queued-1"); + + 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( + "ipc-ws-ack-absent", + "tests/data/fixtures/ipc-websocket-api.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 WebSocket server should accept the connection"); + + // Carries an id but does not opt in, and opting in without an id has + // nothing to name. Neither should be answered. + for message in [ + json!({ "event": "sendMessage", "messageId": "msg-2", "data": {} }), + json!({ "event": "sendMessage", "ack": true, "data": {} }), + ] { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + message.to_string(), + )) + .await + .unwrap(); + } + + let unexpected = tokio::time::timeout(Duration::from_secs(2), 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"] == "ack" { + return true; + } + } + } + } + false + }) + .await; + + assert_ne!( + unexpected, + Ok(true), + "acknowledgement is opt in, and an opt in without a message id is ignored" + ); + + 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( @@ -1405,12 +1632,14 @@ async fn carries_a_binary_websocket_frame_without_corrupting_it() { .await .expect("the WebSocket server should accept the connection"); - // The binary framing is [route_len][route][msg_id_len][msg_id][body]. + // [routeLength][route][requireAck][messageIdLength][messageId][message], + // here with no acknowledgement asked for and no message id. let route = b"sendMessage"; let body: Vec = vec![0xff, 0xfe, 0x00, 0x80, 0x01, 0x02]; let mut payload = vec![route.len() as u8]; payload.extend_from_slice(route); payload.push(0); + payload.push(0); payload.extend_from_slice(&body); socket_conn diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto index 40e03d2a..57f0d79c 100644 --- a/libs/runtime/proto/celerity/runtime/v1/runtime.proto +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -194,6 +194,14 @@ message WebSocketMessage { // alone cannot express the distinction, and the WebSocket protocol treats // the two frame types as distinct. bool is_binary = 6; + // The id this message is known by, which is the one the client gave it when + // it gave one and a runtime generated one otherwise. + // + // Distinct from request_id, which identifies the delivery. This identifies + // the message, so it is what an acknowledgement names and what a lost + // message notification refers to, and a handler needs it to tie its own + // instrumentation to what the client sees. + string message_id = 7; } message ConsumerBatch { diff --git a/libs/runtime/ws/ws-registry/src/acks.rs b/libs/runtime/ws/ws-registry/src/acks.rs index 75b640e2..f0e693e1 100644 --- a/libs/runtime/ws/ws-registry/src/acks.rs +++ b/libs/runtime/ws/ws-registry/src/acks.rs @@ -27,7 +27,15 @@ pub const ACK_WAIT_CHECK_INTERVAL_MS: u64 = 20; pub enum AckStatus { // The message has been sent but no acknowledgement // has been received yet. - Pending(String, MessageType, Vec), + Pending { + connection_id: String, + message: String, + message_type: MessageType, + inform_clients: Vec, + // The context the message was sent from, carried so that a client told + // the message was lost is told what it was for. + caller: Option, + }, // The message has been received by the node that // has the connection that the message was sent for. Received, @@ -42,6 +50,9 @@ pub struct ResendMessageInfo { pub message_type: MessageType, pub message: String, pub inform_clients_on_loss: Vec, + // Carried through the resend so that it is still there if the message is + // eventually declared lost, rather than being dropped on the first retry. + pub caller: Option, } #[derive(Clone, Debug, PartialEq)] @@ -51,7 +62,11 @@ pub enum MessageAction { Resend(ResendMessageInfo), // The message should be considered lost and the caller should be informed that the message // was lost. - Lost(String, Vec), + Lost { + message_id: String, + inform_clients: Vec, + caller: Option, + }, } pub enum AckWorkerMessage { @@ -187,7 +202,7 @@ impl Worker { let mut acks_guard = self.acks.lock().await; let existing_ack_status = acks_guard.get(&message_id).cloned(); - let new_detailed_ack_status = if matches!(ack_status, AckStatus::Pending(_, _, _)) { + let new_detailed_ack_status = if matches!(ack_status, AckStatus::Pending { .. }) { // Only increment the attempts if the message is still pending. DetailedAckStatus { status: ack_status, @@ -221,19 +236,31 @@ async fn check_for_actions_periodic( let mut acks_guard = acks.lock().await; for (message_id, detailed_ack_status) in acks_guard.iter_mut() { - if let AckStatus::Pending(message, message_type, client_ids) = &detailed_ack_status.status { + if let AckStatus::Pending { + connection_id, + message, + message_type, + inform_clients: client_ids, + caller, + } = &detailed_ack_status.status + { if let Some(last_attempt_time) = detailed_ack_status.last_attempt_time { if now.duration_since(last_attempt_time) > Duration::from_millis(message_timeout_ms) { let action = if detailed_ack_status.attempts >= max_attempts { - MessageAction::Lost(message_id.clone(), client_ids.clone()) + MessageAction::Lost { + message_id: message_id.clone(), + inform_clients: client_ids.clone(), + caller: caller.clone(), + } } else { MessageAction::Resend(ResendMessageInfo { - client_id: message_id.clone(), + client_id: connection_id.clone(), message_id: message_id.clone(), message_type: message_type.clone(), message: message.clone(), inform_clients_on_loss: client_ids.clone(), + caller: caller.clone(), }) }; actions.push(action); @@ -247,16 +274,10 @@ async fn check_for_actions_periodic( for action in actions { let message_id = match &action { - MessageAction::Resend(ResendMessageInfo { - message_id, - client_id: _, - message: _, - message_type: _, - inform_clients_on_loss: _, - }) => message_id.clone(), - MessageAction::Lost(message_id, _) => message_id.clone(), + MessageAction::Resend(ResendMessageInfo { message_id, .. }) => message_id.clone(), + MessageAction::Lost { message_id, .. } => message_id.clone(), }; - let is_lost = matches!(action, MessageAction::Lost(_, _)); + let is_lost = matches!(action, MessageAction::Lost { .. }); if message_action_tx.send(action).await.is_err() { error!( @@ -286,7 +307,7 @@ async fn handle_ack_wait( // Check if we have a status for this message let acks_guard = acks.lock().await; if let Some(detailed_ack_status) = acks_guard.get(&message_id) { - let is_pending = matches!(detailed_ack_status.status, AckStatus::Pending(_, _, _)); + let is_pending = matches!(detailed_ack_status.status, AckStatus::Pending { .. }); if !is_pending { // Message is no longer pending, send the final status if tx.send(detailed_ack_status.status.clone()).is_err() { @@ -311,3 +332,44 @@ async fn handle_ack_wait( drop(acks_guard); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A resend has to go to the connection the message was for. + /// + /// Pending acknowledgements are keyed by message id, which says nothing + /// about where the message was headed, so the connection it was for is held + /// alongside. Sending a resend to the message id instead finds no + /// connection anywhere in the cluster and the message reaches nobody, while + /// still counting as an attempt until it is declared lost. + #[test_log::test(tokio::test)] + async fn test_resend_is_addressed_to_the_connection_not_the_message() { + let acks = Arc::new(Mutex::new(HashMap::from([( + "message-1".to_string(), + DetailedAckStatus { + status: AckStatus::Pending { + connection_id: "connection-1".to_string(), + message: "{}".to_string(), + message_type: MessageType::Json, + inform_clients: vec![], + caller: None, + }, + attempts: 0, + // Long enough ago that it is due to be retried. + last_attempt_time: Some(Instant::now() - Duration::from_secs(60)), + }, + )]))); + + let (action_tx, mut action_rx) = tokio::sync::mpsc::channel(4); + check_for_actions_periodic(&acks, &action_tx, 1_000, 3).await; + + let action = action_rx.recv().await.expect("a resend should be due"); + let MessageAction::Resend(resend) = action else { + panic!("expected a resend, got {action:?}"); + }; + assert_eq!(resend.client_id, "connection-1"); + assert_eq!(resend.message_id, "message-1"); + } +} diff --git a/libs/runtime/ws/ws-registry/src/message_helpers.rs b/libs/runtime/ws/ws-registry/src/message_helpers.rs index bebd929e..8ec94751 100644 --- a/libs/runtime/ws/ws-registry/src/message_helpers.rs +++ b/libs/runtime/ws/ws-registry/src/message_helpers.rs @@ -7,20 +7,24 @@ use crate::types::MessageType; /// Creates a message lost event to be sent to a WebSocket connection. /// This follows the Celerity Binary Message Format documented here: /// https://www.celerityframework.io/docs/applications/resources/celerity-api#celerity-binary-message-format -pub fn create_message_lost_event(message_id: String) -> Vec { - let route_len_byte = 0x1_u8; - let route_byte = 0x3_u8; +pub fn create_message_lost_event(message_id: String, caller: Option) -> Vec { let payload = json!({ "messageId": message_id, + // Names the context the lost message came from, so an application can + // tell the client what to retry rather than only that something went + // missing. Absent when the sender named none. + "caller": caller.unwrap_or_default(), }) .to_string(); let payload_bytes = payload.as_bytes(); - // The message is a binary message with the route length, route and payload. - // In this case, the route length is 1 byte, the route is 1 byte and the payload is length of - // the serialised JSON message. - let mut message = Vec::with_capacity(payload_bytes.len() + 2); - message.push(route_len_byte); - message.push(route_byte); + + // `[routeLength][route][requireAck][messageIdLength]` then the payload. A + // reserved message needs no acknowledgement of its own and carries no + // message id of its own, which is what the two zero bytes say. Clients match + // on all four, so a short header is not a shorter version of this message, + // it is one they cannot recognise at all. + let mut message = Vec::with_capacity(payload_bytes.len() + 4); + message.extend_from_slice(&[0x1, 0x3, 0x0, 0x0]); message.extend_from_slice(payload_bytes); message } diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 05cd9af9..ae6efe8e 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -143,7 +143,7 @@ impl WebSocketConnRegistry { resend_message_info.message.clone(), Some(SendContext { wait_for_ack: false, - caller: None, + caller: resend_message_info.caller.clone(), inform_clients: resend_message_info.inform_clients_on_loss, }), ) @@ -156,7 +156,11 @@ impl WebSocketConnRegistry { ); } } - MessageAction::Lost(message_id, inform_clients) => { + MessageAction::Lost { + message_id, + inform_clients, + caller, + } => { for client_id in inform_clients { // Only inform clients that are connected to the current node. if let Some(connection) = self.get_connection(client_id.clone()) { @@ -169,7 +173,11 @@ impl WebSocketConnRegistry { debug!(connection_id = %client_id, "sending message lost event to connection: {}", client_id); conn_lock .send(Message::Binary( - create_message_lost_event(message_id.clone()).into(), + create_message_lost_event( + message_id.clone(), + caller.clone(), + ) + .into(), )) .await .unwrap(); @@ -309,16 +317,24 @@ impl WebSocketConnRegistry { async fn record_pending_ack( &self, + connection_id: String, message_id: String, message_type: MessageType, message: String, inform_clients: Vec, + caller: Option, ) { if let Some(ack_sender) = self.ack_sender.lock().await.as_ref() { ack_sender .send(AckWorkerMessage::Status( message_id, - AckStatus::Pending(message, message_type, inform_clients), + AckStatus::Pending { + connection_id, + message, + message_type, + inform_clients, + caller, + }, )) .await .expect("ack worker channel unexpectedly closed"); @@ -395,10 +411,12 @@ impl WebSocketRegistrySend for WebSocketConnRegistry { let send_ctx = ctx.unwrap_or_default(); debug!(connection_id = %connection_id, "connection not found locally, preparing to send message to broadcaster"); self.record_pending_ack( + connection_id.to_string(), message_id.clone(), message_type.clone(), message.clone(), send_ctx.inform_clients.clone(), + send_ctx.caller.clone(), ) .await; @@ -422,13 +440,15 @@ impl WebSocketRegistrySend for WebSocketConnRegistry { // (no broadcaster), then the message is lost and the provided clients connected to // the current node should be informed. let send_ctx = ctx.unwrap_or_default(); + // Taken before the loop consumes the rest of the context. + let caller = send_ctx.caller; for client_id in send_ctx.inform_clients { if let Some(connection) = self.get_connection(client_id.clone()) { connection .lock() .await .send(Message::Binary( - create_message_lost_event(message_id.clone()).into(), + create_message_lost_event(message_id.clone(), caller.clone()).into(), )) .await?; } @@ -486,6 +506,7 @@ mod tests { struct MessageLostBody { #[serde(rename = "messageId")] message_id: String, + caller: String, } #[derive(Deserialize, Debug, Serialize)] @@ -545,7 +566,7 @@ mod tests { msg.to_string(), Some(SendContext { wait_for_ack: true, - caller: None, + caller: Some("test-caller".to_string()), inform_clients: vec![connection_id.clone()], }), ) @@ -773,11 +794,15 @@ mod tests { // 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(); + // `[routeLength][route][requireAck][messageIdLength]`, all four of which + // a client matches on before it will treat this as a lost message. + assert_eq!(node1_msg_received[..4], [0x1, 0x3, 0x0, 0x0]); + let json_msg = String::from_utf8(node1_msg_received[4..].to_vec()).unwrap(); let message_lost_event: MessageLostBody = serde_json::from_str(&json_msg).unwrap(); assert_eq!(message_lost_event.message_id, "test-message-1"); + // Carried through from the send, so the client is told what the lost + // message was for and not only that one went missing. + assert_eq!(message_lost_event.caller, "test-caller"); } #[test_log::test(tokio::test)]