diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 4b0e555d..c8b50a32 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -386,8 +386,8 @@ impl Application { WebSocketConnRegistryConfig { ack_worker_config: Some(AckWorkerConfig { message_action_check_interval_ms: None, - message_timeout_ms: None, - max_attempts: None, + message_timeout_ms: self.runtime_config.ws_ack_timeout_ms, + max_attempts: self.runtime_config.ws_ack_max_attempts, }), server_node_name: "node1".to_string(), }, @@ -443,8 +443,7 @@ impl Application { .as_ref() .map(|_| websocket_config.auth_strategy.clone()), connection_auth_guard_names: websocket_config.connection_auth_guard.clone(), - connection_auth_guards: self - .get_custom_auth_guards_blocking(&websocket_config.connection_auth_guard), + connection_auth_guards: self.custom_auth_guards.clone(), cors: api_config.cors.clone(), resource_store: resource_store.clone(), }), @@ -505,30 +504,6 @@ impl Application { Ok(http_server_app) } - fn get_custom_auth_guards_blocking( - &self, - guard_names: &Option>, - ) -> HashMap> { - let mut guards = HashMap::new(); - if let Some(names) = guard_names { - // Taken without blocking. Setup is the only thing touching this map - // at this point, so the lock is always free, and a blocking take - // panics outright when setup is called from inside a runtime, which - // is how an application with connection auth guards is started from - // an async context. - let Ok(all_guards) = self.custom_auth_guards.try_lock() else { - error!("custom auth guards were unavailable while setting up the server"); - return guards; - }; - for name in names { - if let Some(guard) = all_guards.get(name) { - guards.insert(name.clone(), guard.clone()); - } - } - } - guards - } - /// Adds the endpoint that invokes a handler directly by name, which exists /// so that a handler can be exercised while developing or testing. /// diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index 2cf0d40d..df5b387a 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -181,6 +181,19 @@ pub struct RuntimeConfig { /// /// Set via `CELERITY_DEPLOY_TARGET`. pub deploy_target: Option, + /// How long the runtime waits for a client to acknowledge a message that + /// asked to be acknowledged, before sending it again. + /// + /// Leave unset for the suggested default the WebSocket runtime protocol names, + /// which is 10 seconds. Set via `CELERITY_WS_ACK_TIMEOUT_MS`. + pub ws_ack_timeout_ms: Option, + /// How many times a message asking to be acknowledged is sent before it is + /// considered lost and the clients waiting on it are told so. + /// + /// Counts the first send, so 3 means the original and two more. Leave unset + /// for the suggested default the WebSocket runtime protocol names, which is 3. + /// Set via `CELERITY_WS_ACK_MAX_ATTEMPTS`. + pub ws_ack_max_attempts: Option, } impl RuntimeConfig { @@ -348,6 +361,9 @@ impl RuntimeConfig { let deploy_target = env.var("CELERITY_DEPLOY_TARGET").ok(); + let ws_ack_timeout_ms = ws_ack_timeout_ms_from_env(env); + let ws_ack_max_attempts = ws_ack_max_attempts_from_env(env); + RuntimeConfig { blueprint_config_path, runtime_call_mode, @@ -375,6 +391,8 @@ impl RuntimeConfig { metrics_enabled, trace_sample_ratio, deploy_target, + ws_ack_timeout_ms, + ws_ack_max_attempts, } } @@ -397,6 +415,41 @@ impl RuntimeConfig { } } +/// Reads the WebSocket acknowledgement timeout from the environment. +/// +/// Separate from [`RuntimeConfig::from_env`] so that the SDKs, which rebuild a +/// runtime configuration from their own, read it the same way rather than each +/// deciding what the variable is called. +pub fn ws_ack_timeout_ms_from_env(env: &impl EnvVars) -> Option { + env.var("CELERITY_WS_ACK_TIMEOUT_MS").ok().map(|val| { + let timeout: u64 = val + .parse() + .expect("Invalid WebSocket ack timeout, must be a whole number of milliseconds"); + assert!( + timeout > 0, + "Invalid WebSocket ack timeout, a client needs some time to answer in" + ); + timeout + }) +} + +/// Reads the WebSocket acknowledgement attempt limit from the environment. +/// +/// See [`ws_ack_timeout_ms_from_env`] for why this is not only read in +/// [`RuntimeConfig::from_env`]. +pub fn ws_ack_max_attempts_from_env(env: &impl EnvVars) -> Option { + env.var("CELERITY_WS_ACK_MAX_ATTEMPTS").ok().map(|val| { + let attempts: u32 = val + .parse() + .expect("Invalid WebSocket ack max attempts, must be a whole number"); + assert!( + attempts > 0, + "Invalid WebSocket ack max attempts, a message has to be sent at least once" + ); + attempts + }) +} + #[derive(Debug)] pub struct AppConfig { pub api: Option, @@ -760,4 +813,48 @@ mod tests { assert_eq!(config.runtime_socket_fallback_port, 0); assert!(!config.runtime_socket_fallback_enabled); } + + /// Unset means the good defaults the protocol names, which the worker + /// applies, rather than a value chosen here. + #[test] + fn test_ack_timings_are_left_to_the_worker_when_unset() { + let config = RuntimeConfig::from_env(&env(&[])); + + assert_eq!(config.ws_ack_timeout_ms, None); + assert_eq!(config.ws_ack_max_attempts, None); + } + + #[test] + fn test_ack_timings_are_read_from_the_environment() { + let config = RuntimeConfig::from_env(&env(&[ + ("CELERITY_WS_ACK_TIMEOUT_MS", "2500"), + ("CELERITY_WS_ACK_MAX_ATTEMPTS", "5"), + ])); + + assert_eq!(config.ws_ack_timeout_ms, Some(2500)); + assert_eq!(config.ws_ack_max_attempts, Some(5)); + } + + /// A message has to be sent once before it can be resent, so no attempts at + /// all is a configuration that cannot be honoured rather than one meaning + /// never send. + #[test] + #[should_panic(expected = "sent at least once")] + fn test_no_ack_attempts_at_all_is_refused() { + RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_MAX_ATTEMPTS", "0")])); + } + + /// No time at all leaves every message overdue as soon as it is sent, so + /// the first check resends it and the attempts run out in milliseconds. + #[test] + #[should_panic(expected = "some time to answer in")] + fn test_an_ack_timeout_of_nothing_is_refused() { + RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_TIMEOUT_MS", "0")])); + } + + #[test] + #[should_panic(expected = "whole number of milliseconds")] + fn test_an_ack_timeout_that_is_not_a_number_is_refused() { + RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_TIMEOUT_MS", "ten seconds")])); + } } diff --git a/libs/runtime/core/src/transform_config.rs b/libs/runtime/core/src/transform_config.rs index 1f71e7ee..2b2850a4 100644 --- a/libs/runtime/core/src/transform_config.rs +++ b/libs/runtime/core/src/transform_config.rs @@ -1494,6 +1494,8 @@ mod tests { metrics_enabled: false, trace_sample_ratio: 1.0, deploy_target: None, + ws_ack_timeout_ms: None, + ws_ack_max_attempts: None, } } diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index e9c688dd..175fc03b 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -76,7 +76,8 @@ pub(crate) struct WebSocketAppState { pub api_auth: Option, pub auth_strategy: Option, pub connection_auth_guard_names: Option>, - pub connection_auth_guards: HashMap>, + pub connection_auth_guards: + Arc>>>, pub cors: Option, pub resource_store: Arc, // What the node has already seen from its clients, so a message resent @@ -313,7 +314,7 @@ async fn handle_socket( .add_connection(connection_id.clone(), socket_ref.clone()); ws_connections_counter().add(1, &[]); - // Send the capabilities signal — a binary frame that indicates the server + // Send the capabilities signal, this is a binary frame that indicates the server // supports full protocol capabilities (binary messages, custom close codes, // binary control frames). In environments where binary frames are not // supported (e.g., managed WebSocket gateways that proxy via text-only APIs), @@ -328,6 +329,20 @@ async fn handle_socket( .await; } + // Authentication happened during the upgrade for the connect strategy, so + // the client doesn't know about the auth status at this point. + if matches!(&state.auth_strategy, Some(WebSocketAuthStrategy::Connect)) { + let response = create_auth_response( + true, + Some(&auth_result_data).filter(|data| !data.is_null()), + Some("Authenticated successfully"), + ); + let mut sock = socket_ref.lock().await; + if let Err(err) = sock.send(Message::Text(response.into())).await { + error!("failed to tell client {connection_id} it was authenticated: {err}"); + } + } + // For Connect strategy, only reached after successful auth (with auth data). // For AuthMessage / no auth, fires immediately with null auth data. if let ControlFlow::Break(_) = on_connect( @@ -365,7 +380,7 @@ async fn handle_socket( // rather than growing a queue without limit. Once the buffer is full // this loop does wait, which is the intended answer to a flood, and a // different situation from one slow handler. - let (work_tx, work_rx) = mpsc::channel::<(Message, WebSocketRequestContext)>( + let (work_tx, work_rx) = mpsc::channel::<(Message, Option, WebSocketRequestContext)>( WS_CONNECTION_WORK_BUFFER, ); let mut worker = spawn_message_worker( @@ -378,10 +393,22 @@ async fn handle_socket( let mut connection_alive = true; while connection_alive { if let Some(Ok(msg)) = socket_rx.next().await { + // Parsed once here and carried from here on. A JSON string + // may escape any character, so only a parse can tell what a + // message says. Held as the parse result rather than the value + // so that a failure is still reported where it was, past the + // authentication gate. + let parsed = match &msg { + Message::Text(text) => Some(serde_json::from_str::(text)), + _ => None, + }; + // Handle Celerity application-level heartbeat pings before // route resolution. These are distinct from WebSocket protocol-level // Ping frames (handled by tungstenite automatically). - if let Some(pong) = detect_heartbeat_ping(&msg) { + if let Some(pong) = + detect_heartbeat_ping(&msg, parsed.as_ref().and_then(|res| res.as_ref().ok())) + { let _ = socket_ref.lock().await.send(pong).await; continue; } @@ -422,6 +449,18 @@ async fn handle_socket( } } } else { + let parsed = match parsed { + Some(Ok(value)) => Some(value), + Some(Err(err)) => { + error!( + "failed to parse JSON message from client \ + {connection_id}: {err}" + ); + None + } + None => None, + }; + // 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. @@ -430,7 +469,7 @@ async fn handle_socket( // 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) { + if let Some(acknowledged) = detect_client_ack(&msg, parsed.as_ref()) { debug!("client {connection_id} acknowledged message {acknowledged}"); state .connections @@ -453,11 +492,11 @@ async fn handle_socket( // 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); + let ack = ack_request(&msg, parsed.as_ref()); match work_tx .send_timeout( - (msg, request_ctx.clone()), + (msg, parsed, request_ctx.clone()), Duration::from_millis(WS_CONNECTION_WORK_SHED_GRACE_MS), ) .await @@ -589,7 +628,10 @@ async fn authenticate_connection( } } CelerityApiAuthGuardType::Custom => { - let guard_handler = state.connection_auth_guards.get(guard_name).cloned(); + let guard_handler = { + let guards = state.connection_auth_guards.lock().await; + guards.get(guard_name).cloned() + }; match validate_custom_auth_on_connect( auth_guard_config, CustomAuthRequestContext { @@ -685,14 +727,14 @@ fn create_connect_message( /// Runs a connection's messages, one at a time, off its read loop. fn spawn_message_worker( - mut work_rx: mpsc::Receiver<(Message, WebSocketRequestContext)>, + mut work_rx: mpsc::Receiver<(Message, Option, WebSocketRequestContext)>, socket_ref: Arc>, connection_id: String, state: WebSocketAppState, ) -> JoinHandle<()> { tokio::spawn(async move { - while let Some((message, request_ctx)) = work_rx.recv().await { - if process_message(message, connection_id.clone(), request_ctx, &state) + while let Some((message, parsed, request_ctx)) = work_rx.recv().await { + if process_message(message, parsed, connection_id.clone(), request_ctx, &state) .await .is_break() { @@ -1025,7 +1067,10 @@ async fn validate_auth_message_token_with_guards( } } CelerityApiAuthGuardType::Custom => { - let guard_handler = state.connection_auth_guards.get(guard_name).cloned(); + let guard_handler = { + let guards = state.connection_auth_guards.lock().await; + guards.get(guard_name).cloned() + }; match validate_custom_auth_on_connect( auth_guard_config, CustomAuthRequestContext { @@ -1094,17 +1139,14 @@ async fn already_acted_on( async fn process_message( msg: Message, + parsed: Option, connection_id: String, request_ctx: WebSocketRequestContext, state: &WebSocketAppState, ) -> ControlFlow<(), ()> { match msg { - Message::Text(text) => { - let resolved = resolve_route( - text.to_string(), - connection_id.clone(), - state.route_key.clone(), - )?; + Message::Text(_) => { + let resolved = resolve_route(parsed, connection_id.clone(), state.route_key.clone())?; if let Some((route, message_id, _requires_ack, data)) = resolved { if already_acted_on(&message_id, &connection_id, state).await { return ControlFlow::Continue(()); @@ -1184,14 +1226,12 @@ async fn process_message( /// Supported formats: /// - JSON: `{"ping": true}` → responds with `{"pong": true}` /// - Binary: `[0x1, 0x1, 0x0, 0x0]` → responds with `[0x1, 0x2, 0x0, 0x0]` -fn detect_heartbeat_ping(msg: &Message) -> Option { +fn detect_heartbeat_ping(msg: &Message, parsed: Option<&Value>) -> Option { match msg { - Message::Text(text) => { - if let Ok(val) = serde_json::from_str::(text.as_ref()) { - if val.get("ping") == Some(&serde_json::Value::Bool(true)) { - let pong = serde_json::json!({"pong": true}).to_string(); - return Some(Message::Text(pong.into())); - } + Message::Text(_) => { + if parsed?.get("ping") == Some(&Value::Bool(true)) { + let pong = serde_json::json!({"pong": true}).to_string(); + return Some(Message::Text(pong.into())); } None } @@ -1334,7 +1374,7 @@ enum AckFormat { /// 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 { +fn detect_client_ack(msg: &Message, parsed: Option<&Value>) -> Option { let body = match msg { Message::Binary(bytes) => { if !bytes.starts_with(&CELERITY_WS_ACK_SIGNAL) { @@ -1343,13 +1383,8 @@ fn detect_client_ack(msg: &Message) -> Option { 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()?; + Message::Text(_) => { + let value = parsed?; if value.get("event").and_then(Value::as_str) != Some("ack") { return None; } @@ -1363,17 +1398,6 @@ fn detect_client_ack(msg: &Message) -> Option { .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 -/// 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(':')) -} - /// Recognises a message asking to be acknowledged, returning the id to /// acknowledge it by and the encoding to answer in. /// @@ -1381,20 +1405,10 @@ fn has_ack_key(text: &str) -> bool { /// 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)> { +fn ack_request(msg: &Message, parsed: Option<&Value>) -> 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()?; + Message::Text(_) => { + let object = parsed?.as_object()?; if object.get("ack").and_then(Value::as_bool) != Some(true) { return None; } @@ -1456,19 +1470,13 @@ async fn acknowledge( type JsonRouteData = (String, Option, bool, Value); fn resolve_route( - msg_text: String, + parsed: Option, connection_id: String, route_key: String, ) -> ControlFlow<(), Option> { - let data: Value = match serde_json::from_str(&msg_text) { - Ok(data) => data, - Err(e) => { - error!( - "failed to parse JSON message from client {}: {}", - connection_id, e - ); - return ControlFlow::Continue(None); - } + // A failed parse is reported by the read loop. + let Some(data) = parsed else { + return ControlFlow::Continue(None); }; let data_obj = match &data { Value::Object(obj) => obj, @@ -1701,6 +1709,14 @@ mod tests { // outside the tests matches on it. use crate::consts::CELERITY_WS_CAPABILITIES_SIGNAL; + /// Pairs a text message with its parsed form, as the read loop does. + fn text_message(text: &str) -> (Message, Option) { + ( + Message::Text(text.into()), + serde_json::from_str::(text).ok(), + ) + } + /// The constants are for matching an inbound frame, where a fixed size /// array is what is wanted, and the encoder is for building an outbound /// one. Two spellings of the same four bytes is how the header came to be @@ -1722,13 +1738,14 @@ mod tests { 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())), + detect_client_ack(&Message::Binary(frame.into()), None), Some("m-1".to_string()) ); - let text = r#"{"event":"ack","data":{"messageId":"m-2","timestamp":"1"}}"#; + let (msg, parsed) = + text_message(r#"{"event":"ack","data":{"messageId":"m-2","timestamp":"1"}}"#); assert_eq!( - detect_client_ack(&Message::Text(text.into())), + detect_client_ack(&msg, parsed.as_ref()), Some("m-2".to_string()) ); } @@ -1737,33 +1754,75 @@ mod tests { 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()); + let (msg, parsed) = text_message(r#"{"event":"sendMessage","data":{"kind":"ack"}}"#); + assert!(detect_client_ack(&msg, parsed.as_ref()).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()); + let (msg, parsed) = text_message(r#"{"event":"sendMessage","ack":true,"messageId":"m-3"}"#); + assert!(detect_client_ack(&msg, parsed.as_ref()).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()); + assert!(detect_client_ack(&Message::Binary(frame.into()), None).is_none()); + } + + #[test] + fn test_detect_client_ack_reads_an_escaped_acknowledgement() { + let text = r#"{"event":"\u0061ck","data":{"messageId":"m-4","timestamp":"1"}}"#; + // Holds the fixture to the case, since spelling it plainly would + // pass without the parse being what decides. + assert!(!text.contains(r#""ack""#)); + + let (msg, parsed) = text_message(text); + assert_eq!( + detect_client_ack(&msg, parsed.as_ref()), + Some("m-4".to_string()), + "an acknowledgement missed is a message resent and then declared lost \ + to a client that already confirmed it" + ); + } + + #[test] + fn test_ack_request_reads_an_escaped_opt_in() { + let text = r#"{"\u0061ck":true,"messageId":"m-5"}"#; + assert!(!text.contains(r#""ack""#)); + + let (msg, parsed) = text_message(text); + let request = ack_request(&msg, parsed.as_ref()); + let Some((message_id, AckFormat::Json)) = request else { + panic!("expected a JSON acknowledgement request, got {request:?}"); + }; + assert_eq!(message_id, "m-5"); + } + + /// The protocol reserves `ack` as an event value, so a message carrying it + /// there is an ordinary one rather than an opt in. + #[test] + fn test_ack_request_tells_the_key_from_the_value() { + let (msg, parsed) = text_message(r#"{"event":"ack","data":{}}"#); + assert!(ack_request(&msg, parsed.as_ref()).is_none()); + + let (msg, parsed) = text_message(r#"{"event":"send","data":{"type":"ack"}}"#); + assert!(ack_request(&msg, parsed.as_ref()).is_none()); + + // Present as a value elsewhere as well as a key, which is an opt in. + let (msg, parsed) = text_message(r#"{"event":"ack","ack":true,"messageId":"m-6"}"#); + assert!(ack_request(&msg, parsed.as_ref()).is_some()); } + /// Opting in without an id is ignored, since an acknowledgement names the + /// message it settles and there would be nothing to name. #[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"}}"#)); + fn test_ack_request_ignores_an_opt_in_with_no_id() { + let (msg, parsed) = text_message(r#"{"event":"send","ack":true}"#); + assert!(ack_request(&msg, parsed.as_ref()).is_none()); } #[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}"#)); + fn test_neither_check_reads_a_message_that_is_not_json() { + let msg = Message::Text("not json at all".into()); + assert!(detect_client_ack(&msg, None).is_none()); + assert!(ack_request(&msg, None).is_none()); } #[test] @@ -1776,7 +1835,7 @@ mod tests { frame.extend_from_slice(b"m-1"); frame.extend_from_slice(&[0xff, 0x00]); - let request = ack_request(&Message::Binary(frame.into())); + let request = ack_request(&Message::Binary(frame.into()), None); let Some((message_id, AckFormat::Binary)) = request else { panic!("expected a binary acknowledgement request, got {request:?}"); }; @@ -1791,7 +1850,7 @@ mod tests { frame.push(3); frame.extend_from_slice(b"m-1"); - assert!(ack_request(&Message::Binary(frame.into())).is_none()); + assert!(ack_request(&Message::Binary(frame.into()), None).is_none()); } #[test] @@ -1799,13 +1858,13 @@ mod tests { // 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()); + assert!(ack_request(&Message::Binary(frame.into()), None).is_none()); } #[test] fn test_detect_json_ping() { - let msg = Message::Text(r#"{"ping":true}"#.into()); - let result = detect_heartbeat_ping(&msg); + let (msg, parsed) = text_message(r#"{"ping":true}"#); + let result = detect_heartbeat_ping(&msg, parsed.as_ref()); assert!(result.is_some()); match result.unwrap() { Message::Text(text) => { @@ -1819,7 +1878,7 @@ mod tests { #[test] fn test_detect_binary_ping() { let msg = Message::Binary(vec![0x1, 0x1, 0x0, 0x0].into()); - let result = detect_heartbeat_ping(&msg); + let result = detect_heartbeat_ping(&msg, None); assert!(result.is_some()); match result.unwrap() { Message::Binary(bytes) => { @@ -1831,26 +1890,35 @@ mod tests { #[test] fn test_detect_non_ping_text() { - let msg = Message::Text(r#"{"event":"myAction","data":"hello"}"#.into()); - assert!(detect_heartbeat_ping(&msg).is_none()); + let (msg, parsed) = text_message(r#"{"event":"myAction","data":"hello"}"#); + assert!(detect_heartbeat_ping(&msg, parsed.as_ref()).is_none()); } #[test] fn test_detect_non_ping_binary() { let msg = Message::Binary(vec![0x5, b'h', b'e', b'l', b'l', b'o'].into()); - assert!(detect_heartbeat_ping(&msg).is_none()); + assert!(detect_heartbeat_ping(&msg, None).is_none()); } #[test] fn test_detect_non_ping_close() { let msg = Message::Close(None); - assert!(detect_heartbeat_ping(&msg).is_none()); + assert!(detect_heartbeat_ping(&msg, None).is_none()); + } + + #[test] + fn test_detect_json_ping_written_with_escapes() { + let text = r#"{"\u0070ing":true}"#; + assert!(!text.contains(r#""ping""#)); + + let (msg, parsed) = text_message(text); + assert!(detect_heartbeat_ping(&msg, parsed.as_ref()).is_some()); } #[test] fn test_detect_ping_false_is_not_heartbeat() { - let msg = Message::Text(r#"{"ping":false}"#.into()); - assert!(detect_heartbeat_ping(&msg).is_none()); + let (msg, parsed) = text_message(r#"{"ping":false}"#); + assert!(detect_heartbeat_ping(&msg, parsed.as_ref()).is_none()); } #[test] diff --git a/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-connect.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-connect.blueprint.yaml new file mode 100644 index 00000000..10e0d000 --- /dev/null +++ b/libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-connect.blueprint.yaml @@ -0,0 +1,52 @@ +version: 2025-11-02 +transform: celerity-2026-02-28 +variables: + logLevel: + type: string + description: "The log level to use for logging." + default: "INFO" + allowedValues: + - "DEBUG" + - "INFO" + - "WARNING" + - "ERROR" + +resources: + ordersWebSocketApi: + type: "celerity/api" + description: "A WebSocket API using the connect strategy, where authentication happens during the upgrade." + metadata: + displayName: Orders WebSocket API + linkSelector: + byLabel: + application: "orders" + spec: + protocols: + - websocketConfig: + routeKey: "event" + authStrategy: "connect" + authGuard: "customGuard" + tracingEnabled: false + auth: + guards: + # Registered by the test, which accepts any non-empty token, since + # what is under test is what the runtime says once a guard has passed + # rather than how it decides. + customGuard: + type: custom + tokenSource: "$.headers.Authorization" + + sendMessageHandler: + type: "celerity/handler" + metadata: + displayName: Send Message Handler + labels: + application: "orders" + annotations: + celerity.handler.websocket: true + celerity.handler.websocket.route: "sendMessage" + spec: + handlerName: SendMessage-v1 + codeLocation: "./handlers" + handler: "handlers.send_message" + timeout: 30 diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 35cf84bf..24054dd2 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -84,10 +84,6 @@ async fn routes_a_websocket_message_to_a_handler_over_the_stream() { let _ = tokio::fs::remove_file(&socket).await; } -/// A handler sending binary is held to the format its client can read, and is -/// told which of its messages was refused. -/// - #[test_log::test(tokio::test)] async fn carries_a_binary_websocket_frame_without_corrupting_it() { let (_app, addr, socket) = start_runtime( @@ -134,6 +130,11 @@ async fn carries_a_binary_websocket_frame_without_corrupting_it() { let _ = tokio::fs::remove_file(&socket).await; } +/// A handler sending binary is held to the format its client can read, and is +/// told which of its messages was refused. +/// +/// Failures are per message rather than per batch, so a batch carrying one bad +/// message still delivers the rest and names the one that did not go. #[test_log::test(tokio::test)] async fn refuses_a_binary_websocket_message_that_is_not_framed() { let (_app, addr, socket) = start_runtime( @@ -236,7 +237,11 @@ async fn refuses_a_binary_websocket_message_that_is_not_framed() { /// A message the client sends twice is acted on once, and answered both times. /// - +/// The two halves have to go together. A client resends because it did not receive +/// an acknowledgement, and what went missing may have been the acknowledgement +/// rather than the message, so a duplicate that is met with silence is one the +/// client keeps sending. Acknowledging without deduplicating runs the handler +/// twice; deduplicating without acknowledging never ends. #[test_log::test(tokio::test)] async fn acts_once_on_a_message_the_client_sent_twice_but_answers_both() { let (_app, addr, socket) = start_runtime( @@ -499,11 +504,16 @@ async fn does_not_acknowledge_a_message_that_did_not_ask() { .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. + // The first carries an id but does not opt in, and the second opts in with + // no id for an acknowledgement to name. Neither should be answered. + // + // The third asks properly and is sent last, so its answer is what says the + // runtime was answering at all. Without it this test passes just as well + // against a runtime that acknowledges nothing, which is what it used to do. for message in [ - json!({ "event": "sendMessage", "messageId": "msg-2", "data": {} }), + json!({ "event": "sendMessage", "messageId": "msg-no-opt-in", "data": {} }), json!({ "event": "sendMessage", "ack": true, "data": {} }), + json!({ "event": "sendMessage", "messageId": "msg-asks", "ack": true, "data": {} }), ] { socket_conn .send(tokio_tungstenite::tungstenite::Message::Text( @@ -513,24 +523,38 @@ async fn does_not_acknowledge_a_message_that_did_not_ask() { .unwrap(); } - let unexpected = tokio::time::timeout(Duration::from_secs(2), async { + // Messages are handled in the order they arrive, so by the time the third + // is answered any answer to the first two has had its chance. + let acknowledged = tokio::time::timeout(Duration::from_secs(5), async { + let mut acknowledged = Vec::new(); 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; + let message_id = value["data"]["messageId"] + .as_str() + .unwrap_or("") + .to_string(); + let answered_the_one_that_asked = message_id == "msg-asks"; + acknowledged.push(message_id); + // Everything sent before it has been handled by now, so + // any answer they were going to get has arrived. + if answered_the_one_that_asked { + break; + } } } } } - false + acknowledged }) - .await; + .await + .expect("the message that asked to be acknowledged should have been"); - assert_ne!( - unexpected, - Ok(true), - "acknowledgement is opt in, and an opt in without a message id is ignored" + assert_eq!( + acknowledged, + vec!["msg-asks".to_string()], + "only the message that asked should be answered, and it should be" ); let _ = tokio::fs::remove_file(&socket).await; @@ -595,6 +619,13 @@ async fn does_not_route_a_client_acknowledgement_to_a_handler() { 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( @@ -689,10 +720,6 @@ 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. -/// - #[test_log::test(tokio::test)] async fn answers_heartbeats_while_a_handler_is_still_running() { let (_app, addr, socket) = start_runtime( @@ -1018,3 +1045,352 @@ async fn fires_the_disconnect_handler_once_for_a_client_that_sends_a_close_frame let _ = tokio::fs::remove_file(&socket).await; } + +/// A message the client never acknowledges is declared lost, on the timings the +/// deployment configured rather than the ones compiled in. +/// +/// The acknowledgement timeout and the attempt limit are what the protocol asks +/// to be configurable, and until now they were fixed at whatever the worker +/// defaulted to. This drives the whole path with both set small, so what it +/// proves is not only that a message can be declared lost but that the +/// configured values are the ones being used. On the defaults the loss would +/// come after about half a minute, three resends ten seconds apart, so the five +/// second bound below is what says the configured values reached the worker. +#[test_log::test(tokio::test)] +async fn declares_a_message_lost_on_the_timings_it_was_configured_with() { + let socket = socket_path("ipc-ws-ack-timings"); + let env_vars = ipc_env( + "ipc-ws-ack-timings", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + &socket, + &[ + ("CELERITY_WS_ACK_TIMEOUT_MS", "200"), + ("CELERITY_WS_ACK_MAX_ATTEMPTS", "1"), + ], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + // Sent only so the handler learns the connection id, which is what it + // addresses the message below to. + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + let dispatch = handler + .next_dispatch() + .await + .expect("the message should reach the handler"); + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + let connection_id = message.connection_id; + + // [routeLength][route][requireAck][messageIdLength][messageId][payload], + // this one asking to be acknowledged under the id the loss event will name. + let mut framed = vec![7u8]; + framed.extend_from_slice(b"updates"); + framed.push(0x1); + framed.push(5u8); + framed.extend_from_slice(b"m-ack"); + framed.extend_from_slice(&[0xde, 0xad]); + + handler + .send_ws( + "batch-1", + vec![proto::WsOutbound { + connection_id: connection_id.clone(), + message: framed, + is_binary: true, + message_id: "m-ack".to_string(), + // Without this nobody is told, since a loss event goes to the + // clients the sender named rather than to the one that missed + // the message. + inform_clients_on_loss: vec![connection_id.clone()], + ..Default::default() + }], + ) + .await; + + // The client reads the message and deliberately does not acknowledge it, + // which is the case a resend and then a loss event exist for. + let lost = 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 { + // A reserved frame, route 0x3, with no ack asked for and no id. + if bytes.len() > 4 && bytes[..4] == [0x1, 0x3, 0x0, 0x0] { + return Some(bytes[4..].to_vec()); + } + } + } + None + }) + .await + .expect( + "a message nobody acknowledged should be declared lost, and within the configured \ + timings rather than the compiled in ones", + ); + + let lost = lost.expect("the connection closed before the message was declared lost"); + let lost: serde_json::Value = serde_json::from_slice(&lost).unwrap(); + assert_eq!( + lost["messageId"], "m-ack", + "the loss event should name the message that went unacknowledged" + ); + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} + +/// An acknowledgement written with escapes settles the message it names. +/// +/// JSON lets a string escape any character, so `"\u0061ck"` is `"ack"` to a +/// parser and something else to a search of the raw text. Missing one leaves +/// the message it settles unsettled, and the client is told a message it +/// confirmed was lost. +/// +/// The timings are small so that loss would arrive well inside the window, +/// rather than this passing on slowness. +#[test_log::test(tokio::test)] +async fn settles_a_message_acknowledged_with_an_escaped_event_name() { + let socket = socket_path("ipc-ws-escaped-ack"); + let env_vars = ipc_env( + "ipc-ws-escaped-ack", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + &socket, + &[ + ("CELERITY_WS_ACK_TIMEOUT_MS", "200"), + ("CELERITY_WS_ACK_MAX_ATTEMPTS", "1"), + ], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + 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"); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + let dispatch = handler + .next_dispatch() + .await + .expect("the message should reach the handler"); + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + let connection_id = message.connection_id; + + // [routeLength][route][requireAck][messageIdLength][messageId][payload] + let mut framed = vec![7u8]; + framed.extend_from_slice(b"updates"); + framed.push(0x1); + framed.push(5u8); + framed.extend_from_slice(b"m-esc"); + framed.extend_from_slice(&[0xde, 0xad]); + + handler + .send_ws( + "batch-1", + vec![proto::WsOutbound { + connection_id: connection_id.clone(), + message: framed, + is_binary: true, + message_id: "m-esc".to_string(), + inform_clients_on_loss: vec![connection_id.clone()], + ..Default::default() + }], + ) + .await; + + // A client acknowledges what it has received, and an acknowledgement + // arriving before the message is recorded as waiting settles nothing. + let delivered = 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[..] == CELERITY_WS_CAPABILITIES_SIGNAL[..] { + continue; + } + return Some(bytes.to_vec()); + } + } + None + }) + .await + .expect("the message asking to be acknowledged should reach the client"); + assert!( + delivered.is_some_and(|bytes| bytes.starts_with(&[7u8]) && bytes[8] == 0x1), + "the client should have been sent a message asking to be acknowledged" + ); + + // Escaped the way a conservative serialiser would, carrying no `"ack"`. + let acknowledgement = r#"{"event":"\u0061ck","data":{"messageId":"m-esc","timestamp":"2026-01-01T00:00:00.000Z"}}"#; + assert!(!acknowledgement.contains(r#""ack""#)); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + acknowledgement.into(), + )) + .await + .unwrap(); + + // Nothing should follow. A loss event means the acknowledgement went + // unread, a dispatch means it was routed as an ordinary message. + let outcome = tokio::time::timeout(Duration::from_secs(2), async { + loop { + tokio::select! { + incoming = socket_conn.next() => match incoming { + Some(Ok(tokio_tungstenite::tungstenite::Message::Binary(bytes))) + if bytes.len() > 4 && bytes[..4] == [0x1, 0x3, 0x0, 0x0] => + { + return "the message was declared lost"; + } + Some(Ok(_)) => continue, + _ => return "the connection ended", + }, + dispatched = handler.next_dispatch() => { + if dispatched.is_some() { + return "the acknowledgement was routed to a handler"; + } + } + } + } + }) + .await; + + assert!( + outcome.is_err(), + "an acknowledgement should settle the message it names, instead {}", + outcome.unwrap_or("nothing happened") + ); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} + +/// A guard that lets any non-empty token through, since what is under test is +/// what the runtime says once a guard has passed rather than how it decides. +#[derive(Debug)] +struct AcceptAnyTokenGuard; + +#[async_trait::async_trait] +impl celerity_runtime_core::auth_custom::AuthGuardHandler for AcceptAnyTokenGuard { + async fn validate( + &self, + input: celerity_runtime_core::auth_custom::AuthGuardValidateInput, + ) -> Result { + if input.token.is_empty() { + return Err( + celerity_runtime_core::auth_custom::AuthGuardValidateError::Unauthorised( + "empty token".to_string(), + ), + ); + } + Ok(json!({ "id": "user-1" })) + } +} + +/// A client authenticated during the upgrade is told so afterwards. +/// +/// The connect strategy authenticates before the connection is upgraded, so +/// nothing the client receives says whether it worked. The protocol has the +/// server say so once the connection is up, and a client waits for it: the +/// official one moves into an authenticating state after the capabilities +/// signal and leaves it only when this arrives. Without it, connecting never +/// finishes and nothing the application queued is ever sent. +/// +/// The order matters as much as the message. A client reads this as an answer +/// about authentication only once it knows what the transport can carry, so +/// sending it before the capabilities signal would have it taken for an +/// ordinary message on a route named `authenticated`. +#[test_log::test(tokio::test)] +async fn tells_a_client_authenticated_during_the_upgrade_that_it_was() { + let socket = socket_path("ipc-ws-auth-connect"); + let env_vars = ipc_env( + "ipc-ws-auth-connect", + "tests/data/fixtures/ipc-websocket-auth-connect.blueprint.yaml", + &socket, + &[], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + // Registered after setup, which is the only order an SDK can use, since + // setup is what returns the configuration telling it which guards the + // blueprint asks for. A guard the connection path cannot see is a + // connection refused, so this ordering is part of what the test asserts. + app.register_custom_auth_guard("customGuard", AcceptAnyTokenGuard) + .await; + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + let _handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let mut request = + tokio_tungstenite::tungstenite::client::IntoClientRequest::into_client_request(format!( + "ws://{addr}/" + )) + .unwrap(); + request + .headers_mut() + .insert("Authorization", "Bearer a-token".parse().unwrap()); + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(request) + .await + .expect("a connection carrying a token the guard accepts should be upgraded"); + + let mut saw_capabilities = false; + let authenticated = tokio::time::timeout(Duration::from_secs(5), async { + while let Some(Ok(message)) = socket_conn.next().await { + match message { + tokio_tungstenite::tungstenite::Message::Binary(bytes) + if bytes[..] == CELERITY_WS_CAPABILITIES_SIGNAL[..] => + { + saw_capabilities = true; + } + tokio_tungstenite::tungstenite::Message::Text(text) => { + if let Ok(value) = serde_json::from_str::(&text) { + if value["event"] == "authenticated" { + return Some(value); + } + } + } + _ => {} + } + } + None + }) + .await + .expect("a client authenticated during the upgrade should be told so"); + + let authenticated = authenticated.expect("the connection closed before saying anything"); + assert!( + saw_capabilities, + "the capabilities signal should come first, or a client takes this for an ordinary message" + ); + assert_eq!(authenticated["data"]["success"], true); + // Claims are collected under the name of the guard that produced them, so + // an API with more than one can tell them apart. + assert_eq!( + authenticated["data"]["userInfo"]["customGuard"]["id"], "user-1", + "what the guard returned should reach the client" + ); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} diff --git a/libs/runtime/sdk/bindgen-ffi/src/application.rs b/libs/runtime/sdk/bindgen-ffi/src/application.rs index f7758eae..fb7bdd7a 100644 --- a/libs/runtime/sdk/bindgen-ffi/src/application.rs +++ b/libs/runtime/sdk/bindgen-ffi/src/application.rs @@ -7,7 +7,9 @@ use celerity_helpers::{ }; use celerity_runtime_core::{ application::Application as RuntimeApp, - config::{ClientIpSource, RuntimeConfig}, + config::{ + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ClientIpSource, RuntimeConfig, + }, errors::{ApplicationStartError, ConfigError}, }; use tokio::select; @@ -65,6 +67,8 @@ pub unsafe fn application_create(core_runtime_config: CoreRuntimeConfig) -> *mut metrics_enabled: false, trace_sample_ratio: 0.1, deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), + ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), + ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), }, Box::new(ProcessEnvVars::new()), ), diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index 58cdcfe7..d9a9ac26 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -30,10 +30,11 @@ use celerity_runtime_core::{ auth_custom::{AuthGuardHandler, AuthGuardValidateError, AuthGuardValidateInput}, auth_http::AuthContext, config::{ - ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, - CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, - GuardHandlerDefinition, GuardsConfig, HttpConfig, HttpHandlerDefinition, RuntimeConfig, - ScheduleConfig, SchedulesConfig, WebSocketConfig, WebSocketHandlerDefinition, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, + ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, + EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, HttpConfig, + HttpHandlerDefinition, RuntimeConfig, ScheduleConfig, SchedulesConfig, WebSocketConfig, + WebSocketHandlerDefinition, }, consts::{ DEFAULT_RESOURCE_STORE_CACHE_ENTRY_TTL, DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL, @@ -1330,6 +1331,8 @@ impl CoreRuntimeApplication { metrics_enabled: runtime_config.metrics_enabled.unwrap_or(false), trace_sample_ratio: runtime_config.trace_sample_ratio.unwrap_or(0.1), deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), + ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), + ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), }; let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); CoreRuntimeApplication { diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index 4c6aa575..e1c93d14 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -25,9 +25,10 @@ use celerity_runtime_core::{ application::Application, auth_http::AuthContext, config::{ - ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, - CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, - GuardHandlerDefinition, GuardsConfig, RuntimeConfig, ScheduleConfig, SchedulesConfig, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, + ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, + EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, RuntimeConfig, + ScheduleConfig, SchedulesConfig, }, request::{MatchedRoute, RequestId, ResolvedClientIp, ResolvedUserAgent}, telemetry_utils::extract_trace_context, @@ -511,6 +512,8 @@ impl CoreRuntimeApplication { metrics_enabled: runtime_config.metrics_enabled, trace_sample_ratio: runtime_config.trace_sample_ratio, deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), + ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), + ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), }; println!("Creating CoreRuntimeApplication with config: {native_runtime_config:?}"); let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); diff --git a/libs/runtime/ws/ws-registry/src/acks.rs b/libs/runtime/ws/ws-registry/src/acks.rs index f3e256cb..3c8b95c4 100644 --- a/libs/runtime/ws/ws-registry/src/acks.rs +++ b/libs/runtime/ws/ws-registry/src/acks.rs @@ -9,16 +9,40 @@ use tracing::{debug, error, info, info_span, Instrument}; use crate::types::{AckWorkerConfig, MessageType}; -/// The default interval at which to check for actions based on ack statuses. -pub const DEFAULT_MESSAGE_ACTION_CHECK_INTERVAL_MS: u64 = 10000; - /// The default timeout in milliseconds for which the caller should consider re-sending /// the message if it has not been acknowledged. -pub const DEFAULT_MESSAGE_TIMEOUT_MS: u64 = 15000; +/// +/// One of the suggested defaults the WebSocket runtime protocol names. +pub const DEFAULT_MESSAGE_TIMEOUT_MS: u64 = 10000; /// The default number of times that a message should be attempted to be sent before it is /// considered lost. -pub const DEFAULT_MAX_ATTEMPTS: u32 = 4; +/// +/// One of the suggested defaults the WebSocket runtime protocol names. +pub const DEFAULT_MAX_ATTEMPTS: u32 = 3; + +/// The longest a message may sit past its timeout before the worker notices, +/// which is what the check interval buys at the cost of waking more often. +const MAX_MESSAGE_ACTION_CHECK_INTERVAL_MS: u64 = 1000; + +/// The shortest the check interval may be derived as, so that a very small +/// timeout does not turn the worker into a busy loop. +const MIN_MESSAGE_ACTION_CHECK_INTERVAL_MS: u64 = 20; + +/// Derives how often to look for messages that have fallen due from the timeout +/// they are due after. +/// +/// The check interval is what the timeout is rounded up to, since a message +/// falling due between two checks waits for the later one. Checking every ten +/// seconds for a message due after ten would resend somewhere between ten and +/// twenty seconds, so the interval has to be a fraction of the timeout for the +/// timeout to be accurate. +fn derive_message_action_check_interval_ms(message_timeout_ms: u64) -> u64 { + (message_timeout_ms / 10).clamp( + MIN_MESSAGE_ACTION_CHECK_INTERVAL_MS, + MAX_MESSAGE_ACTION_CHECK_INTERVAL_MS, + ) +} /// The default interval in milliseconds to check for the acknowledgement status of a message. pub const ACK_WAIT_CHECK_INTERVAL_MS: u64 = 20; @@ -103,14 +127,15 @@ pub struct Worker { impl Worker { pub fn new(config: AckWorkerConfig) -> Self { + let message_timeout_ms = config + .message_timeout_ms + .unwrap_or(DEFAULT_MESSAGE_TIMEOUT_MS); Self { acks: Arc::new(Mutex::new(HashMap::new())), message_action_check_interval_ms: config .message_action_check_interval_ms - .unwrap_or(DEFAULT_MESSAGE_ACTION_CHECK_INTERVAL_MS), - message_timeout_ms: config - .message_timeout_ms - .unwrap_or(DEFAULT_MESSAGE_TIMEOUT_MS), + .unwrap_or_else(|| derive_message_action_check_interval_ms(message_timeout_ms)), + message_timeout_ms, max_attempts: config.max_attempts.unwrap_or(DEFAULT_MAX_ATTEMPTS), } } @@ -420,4 +445,51 @@ mod tests { assert_eq!(resend.client_id, "connection-1"); assert_eq!(resend.message_id, "message-1"); } + + /// A timeout only means what it says if the worker looks often enough to + /// notice, so the interval is derived from it rather than set beside it. + #[test] + fn test_the_check_interval_is_a_fraction_of_the_timeout_it_is_derived_from() { + assert_eq!( + derive_message_action_check_interval_ms(DEFAULT_MESSAGE_TIMEOUT_MS), + 1_000 + ); + assert_eq!(derive_message_action_check_interval_ms(2_000), 200); + } + + /// Bounded at both ends. A long timeout does not buy a proportionally + /// coarse check, and a very short one does not turn the worker into a busy + /// loop. + #[test] + fn test_the_derived_check_interval_stays_within_its_bounds() { + assert_eq!(derive_message_action_check_interval_ms(600_000), 1_000); + assert_eq!(derive_message_action_check_interval_ms(100), 20); + assert_eq!(derive_message_action_check_interval_ms(0), 20); + } + + /// An interval given explicitly is used as given, which is what lets a test + /// watch a resend without waiting on the production timings. + #[test] + fn test_an_explicit_check_interval_is_kept() { + let worker = Worker::new(AckWorkerConfig { + message_action_check_interval_ms: Some(50), + message_timeout_ms: Some(100), + max_attempts: Some(2), + }); + + assert_eq!(worker.message_action_check_interval_ms, 50); + assert_eq!(worker.message_timeout_ms, 100); + assert_eq!(worker.max_attempts, 2); + } + + /// The good defaults the WebSocket runtime protocol names, which a + /// deployment gets by configuring nothing. + #[test] + fn test_the_defaults_are_the_ones_the_protocol_names() { + let worker = Worker::new(AckWorkerConfig::default()); + + assert_eq!(worker.message_timeout_ms, 10_000); + assert_eq!(worker.max_attempts, 3); + assert_eq!(worker.message_action_check_interval_ms, 1_000); + } } diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index cba242da..c50e2c12 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -1245,13 +1245,27 @@ mod tests { // opt in, it does not add or change one. assert_eq!(&received[..], original.as_slice()); + // Sent again while it goes unanswered, which is what says the opt in was + // read at all. Without waiting for this the test passes just as well + // against a runtime that never reads the byte, since a message nothing + // is waiting on is also a message that is never resent. + let resent = tokio::time::timeout(Duration::from_millis(400), socket.next()) + .await + .expect("a binary message asking to be acknowledged should be sent again") + .unwrap() + .unwrap(); + match resent { + tungstenite::Message::Binary(bytes) => assert_eq!(&bytes[..], original.as_slice()), + other => panic!("Unexpected message but got {other:?}"), + } + registry .record_client_ack(connection_id, "m-bin".to_string()) .await; - let resent = tokio::time::timeout(Duration::from_millis(400), socket.next()).await; + let after_ack = tokio::time::timeout(Duration::from_millis(400), socket.next()).await; assert!( - resent.is_err(), - "an acknowledged message should not be resent" + after_ack.is_err(), + "an acknowledged message should not be resent, got {after_ack:?}" ); }