From 9f22d3a7c5df89c785a24abdcfa487352e81a00b Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 10:33:36 +0100 Subject: [PATCH 01/11] test(lib-rt-core): give the acknowledgement test something to prove Sending two messages that should not be answered and checking that nothing came back is a test that passes against a runtime which answers nothing at all. It was one, and deleting acknowledgement from the runtime entirely left it green. A third message now asks properly and is sent last, so the answer to it is what says the runtime was answering, and the messages before it have been handled by the time that answer arrives. It fails now if acknowledgement stops working and fails if it starts answering messages that did not ask. Three comments are also back on the tests they describe. Splitting this file up cut them in half, because the pattern used to find them expected a space after the slashes and a paragraph break has none, so each lost its second half and the first half stayed behind with whichever test came before. Two of them ended up describing something else entirely. --- libs/runtime/core/tests/ipc_websocket_test.rs | 67 +++++++++++++------ 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 35cf84bf..7615bae2 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( From 209c1efc32356d7877f4d1ebd739ae93e3c4e94f Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 10:33:53 +0100 Subject: [PATCH 02/11] test(lib-rt-ws-registry): wait for the resend that says a binary opt in was read Checking that a binary message arrives as composed and is then not sent again says nothing about whether the runtime read the byte asking it to be acknowledged. A message nothing is waiting on is also a message that is never resent, so the test passed either way, and making the runtime ignore that byte entirely left it green. It now waits for the message to be sent a second time before acknowledging it, which only happens if the opt in was read, and then requires the resending to stop. The JSON path had this all along in a second test that watches a message go unanswered. Binary had no such test, so nothing covered it. --- libs/runtime/ws/ws-registry/src/registry.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) 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:?}" ); } From cc3bc0ba6715a40ffcee482c9f5972124f82d006 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 12:44:31 +0100 Subject: [PATCH 03/11] fix(lib-rt-core): tell a client authenticated during the upgrade that it was Authentication for the connect strategy happens before the connection is upgraded, so nothing the client receives afterwards says whether it worked. The protocol has the server say so once the connection is up, and the runtime never did. A client waits for it rather than taking the upgrade as the answer. The official one moves into an authenticating state once it knows what the transport can carry and leaves that state only when this message arrives, so connecting never finished, and since nothing else marks a connection ready, anything the application queued while connecting was never sent. The connect strategy did not work at all against this runtime. It went unnoticed because the client is tested against a server of its own that does send this, so both sides passed their own tests while disagreeing with each other. The message goes out after the capabilities signal rather than before it. A client reads this as an answer about authentication only once it knows what it is dealing with, and anything arriving earlier is taken for an ordinary message on a route named `authenticated`. Sent in text, as the protocol has no binary form for it, which matters because a client in a constrained environment learns it is constrained by waiting for a binary frame that never comes, so nothing needed to finish connecting can be binary. --- libs/runtime/core/src/websocket.rs | 16 ++- .../ipc-websocket-auth-connect.blueprint.yaml | 52 +++++++++ libs/runtime/core/tests/ipc_websocket_test.rs | 107 ++++++++++++++++++ 3 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 libs/runtime/core/tests/data/fixtures/ipc-websocket-auth-connect.blueprint.yaml diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index e9c688dd..baa60fee 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -313,7 +313,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 +328,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( 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 7615bae2..199b0aae 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -1045,3 +1045,110 @@ async fn fires_the_disconnect_handler_once_for_a_client_that_sends_a_close_frame 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.register_custom_auth_guard("customGuard", AcceptAnyTokenGuard) + .await; + app.setup().unwrap(); + 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; +} From 27eca1a8356f196cafa076469b10d9077fc3f65d Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 12:59:40 +0100 Subject: [PATCH 04/11] fix(lib-rt-core): find a connection auth guard when a client connects A WebSocket API with a custom connection auth guard refused every client it was given through an SDK. The guards the connection path could see were copied out of the application while the server was being set up. An SDK cannot have registered anything by then, because setup is what returns the configuration telling it which guards the blueprint asks for, so it registers afterwards and the copy stays empty. A guard that is asked for and not found is an unexpected error, which closes the connection, so the feature could not work through the only route anyone reaches it by. The Python SDK makes this plainest, registering its guards inside run, well after setup has taken its copy. The connection path now holds the same map the application registers into and reads it when a client connects, which is what the HTTP path has always done. That leaves one place a guard lives rather than two that have to agree about when. The connect strategy test moves its registration to after setup, the order an SDK is forced into, so that test now stands on this. Putting the copy back fails it, and it fails by the connection closing before the client hears anything, which is what an application author would have seen. --- libs/runtime/core/src/application.rs | 27 +------------------ libs/runtime/core/src/websocket.rs | 13 ++++++--- libs/runtime/core/tests/ipc_websocket_test.rs | 6 ++++- 3 files changed, 16 insertions(+), 30 deletions(-) diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 4b0e555d..432bb6a3 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -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/websocket.rs b/libs/runtime/core/src/websocket.rs index baa60fee..93528ac7 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 @@ -603,7 +604,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 { @@ -1039,7 +1043,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 { diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 199b0aae..103ea2f5 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -1092,9 +1092,13 @@ async fn tells_a_client_authenticated_during_the_upgrade_that_it_was() { ); 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; - app.setup().unwrap(); let addr = app.run(false).await.unwrap().http_server_address.unwrap(); let _handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; From a5b53295affadd28d2c2d4638a2b85a7e9dc41c0 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:24:29 +0100 Subject: [PATCH 05/11] fix(lib-rt-core): let a deployment set the acknowledgement timings The protocol asks for the acknowledgement timeout and the attempt limit to be configurable, and the runtime passed neither on, handing the connection registry a configuration of nothing at all and taking whatever the worker defaulted to. Both are now read from the environment, through CELERITY_WS_ACK_TIMEOUT_MS and CELERITY_WS_ACK_MAX_ATTEMPTS, following the drain timeout in where they are read from. No attempts at all is refused, since a message has to be sent once before it can be resent, and a value that is not a number is refused rather than quietly becoming a default. How often the worker looks for messages that have fallen due is left unset deliberately. It is derived from the timeout rather than sat beside it, so a deployment cannot ask for a timeout the worker checks for too rarely to honour. The end to end test drives the whole path with both set small, so a message nobody acknowledges is declared lost in under a second where the defaults would take about half a minute. That bound is what says the values reached the worker rather than only the configuration struct, and removing the two lines that carry them fails it. The SDKs read these where they read the deploy target, which follows in its own commit. --- libs/runtime/core/src/application.rs | 4 +- libs/runtime/core/src/config.rs | 83 ++++++++++++++ libs/runtime/core/src/transform_config.rs | 2 + libs/runtime/core/tests/ipc_websocket_test.rs | 105 ++++++++++++++++++ 4 files changed, 192 insertions(+), 2 deletions(-) diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 432bb6a3..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(), }, diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index 2cf0d40d..e8802311 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,35 @@ 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| { + val.parse() + .expect("Invalid WebSocket ack timeout, must be a whole number of milliseconds") + }) +} + +/// 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 +807,40 @@ 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")])); + } + + #[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/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 103ea2f5..6ad556a6 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -1046,6 +1046,111 @@ 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; +} + /// 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)] From f57691e628641d374aab6b7e3e5e94a771e15a3e Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:32:27 +0100 Subject: [PATCH 06/11] fix(lib-rt-ws-registry): use the acknowledgement timings the protocol names The worker waited fifteen seconds for a client to acknowledge a message and sent it four times before declaring it lost, where the protocol names ten seconds and three attempts as its good defaults. The interval it checks on was the more interesting of the two. It was ten seconds, the same as the timeout it polices, so a message falling due between two ticks waited for the later one and a resend went out anywhere from ten to twenty seconds out. Correcting the timeout alone would not have made the timeout mean what it says. That interval is now derived from the timeout at a tenth of it, bounded at both ends so a long timeout does not buy a proportionally coarse check and a very short one does not turn the worker into a busy loop. Deriving it rather than defaulting it separately means the two can no longer be configured into disagreeing with each other. An interval given explicitly is still used as given, which is what lets a test watch a resend without waiting on the production timings. --- libs/runtime/ws/ws-registry/src/acks.rs | 90 ++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 9 deletions(-) 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); + } } From ef31d2ac68d3a41c542cb95d83736d09e0766432 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:32:44 +0100 Subject: [PATCH 07/11] fix(lib-rt-sdk-ffi): carry the acknowledgement timings through to the runtime An application started over the FFI boundary builds its own runtime configuration rather than reading one from the environment, so the two new acknowledgement settings would have been left unset and every such application would have taken the defaults whatever it asked for. They are read here the way the deploy target is, from the process environment at the point the configuration is built, rather than being added to the configuration the caller passes in. That keeps a runtime level tuning knob out of a surface meant for what an application declares about itself. --- libs/runtime/sdk/bindgen-ffi/src/application.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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()), ), From d960d8761491ab7c3c20c89a02e707b6a6e8b24a Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:32:58 +0100 Subject: [PATCH 08/11] fix(lib-rt-sdk-node): carry the acknowledgement timings through to the runtime The Node SDK rebuilds a runtime configuration from the one it is handed, so the two new acknowledgement settings would have been left unset and a WebSocket application started this way would have taken the defaults whatever its environment asked for. They are read the way the deploy target is, from the process environment at the point the configuration is rebuilt, rather than being added to the config object the caller passes in. That keeps a runtime level tuning knob out of a surface meant for what an application declares about itself, and means the same variables work whichever way the runtime is started. --- libs/runtime/sdk/node/src/lib.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) 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 { From 2dc06aceb0cf4c5033a225e29bfab5f0ec1932ea Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:33:03 +0100 Subject: [PATCH 09/11] fix(lib-rt-sdk-python): carry the acknowledgement timings through to the runtime The Python SDK rebuilds a runtime configuration from the one it is handed, so the two new acknowledgement settings would have been left unset and a WebSocket application started this way would have taken the defaults whatever its environment asked for. They are read the way the deploy target is, from the process environment at the point the configuration is rebuilt, rather than being added to the config object the caller passes in. That keeps a runtime level tuning knob out of a surface meant for what an application declares about itself, and means the same variables work whichever way the runtime is started. --- libs/runtime/sdk/python/src/lib.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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())); From fdfcb2a977b75018d8adbc2f9faa6625e4974a7c Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 18 Aug 2026 13:56:05 +0100 Subject: [PATCH 10/11] fix(lib-rt-core): read an acknowledgement written with escapes A JSON string may escape any character, so a client that writes the letter a of its event name as a unicode escape sends an acknowledgement that is one to any parser and not one to any search of the raw text. The runtime searched the text before parsing it, so an acknowledgement written that way was taken for an ordinary message and routed to a handler, the message it settled stayed unsettled, and the client was told a message it had already confirmed was lost. The same held in the other direction for a message asking to be acknowledged, where the key rather than the value was searched for. That one fails more quietly, since the message goes out untracked and neither a resend nor a loss report follows. Text is now parsed once in the read loop and the value carried to both checks and on through the worker to route resolution, which parsed it again. A text message is parsed exactly once where an opt in used to be parsed twice, so this is less work rather than more. The end to end test drives the whole path, sending an escaped acknowledgement for a message that asks for one and requiring that nothing follows it, neither a loss event nor a dispatch, which are the two halves of the same mistake. Putting the search back fails it by declaring lost a message the client acknowledged. --- libs/runtime/core/src/websocket.rs | 187 ++++++++++-------- libs/runtime/core/tests/ipc_websocket_test.rs | 133 +++++++++++++ 2 files changed, 243 insertions(+), 77 deletions(-) diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 93528ac7..ca4d59d7 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -380,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( @@ -437,6 +437,23 @@ async fn handle_socket( } } } else { + // 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. + let parsed = match &msg { + Message::Text(text) => match serde_json::from_str::(text) { + Ok(value) => Some(value), + Err(err) => { + error!( + "failed to parse JSON message from client \ + {connection_id}: {err}" + ); + 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. @@ -445,7 +462,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 @@ -468,11 +485,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 @@ -703,14 +720,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() { @@ -1115,17 +1132,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(()); @@ -1355,7 +1369,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) { @@ -1364,13 +1378,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; } @@ -1384,17 +1393,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. /// @@ -1402,20 +1400,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; } @@ -1477,19 +1465,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, @@ -1722,6 +1704,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 @@ -1743,13 +1733,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()) ); } @@ -1758,33 +1749,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] @@ -1797,7 +1830,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:?}"); }; @@ -1812,7 +1845,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] @@ -1820,7 +1853,7 @@ 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] diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 6ad556a6..24054dd2 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -1151,6 +1151,139 @@ async fn declares_a_message_lost_on_the_timings_it_was_configured_with() { 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)] From e881b738a9f4bd38369f8d020fa5820bf64e9691 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 10:52:48 +0100 Subject: [PATCH 11/11] fix(lib-rt-core): parse a text message once and refuse a timeout of nothing The heartbeat check parses the text itself and runs ahead of everything else, so a message was parsed there and then parsed again for the acknowledgement checks that follow. The parse moves above the heartbeat and its value is passed in, which makes true what the commit before this one claimed, that a text message is parsed exactly once. The parse result rather than the value is what travels that far, so a failure is still reported where it was reported before, past the authentication gate. Logging it earlier would let a client that has not authenticated draw error level logs out of the runtime, which is not something the fix needs and not something it could do before. The authentication handshake still parses separately, which is a message or two per connection rather than one per message, and is left alone. An acknowledgement timeout of zero is now refused alongside no attempts at all. Zero leaves every message overdue the moment it is sent, so the first check resends it and the attempts run out in milliseconds, which is a configuration that cannot be honoured rather than one asking for promptness. --- libs/runtime/core/src/config.rs | 18 ++++++- libs/runtime/core/src/websocket.rs | 78 ++++++++++++++++++------------ 2 files changed, 62 insertions(+), 34 deletions(-) diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index e8802311..df5b387a 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -422,8 +422,14 @@ impl RuntimeConfig { /// 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| { - val.parse() - .expect("Invalid WebSocket ack timeout, must be a whole number of milliseconds") + 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 }) } @@ -838,6 +844,14 @@ mod tests { 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() { diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index ca4d59d7..175fc03b 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -393,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; } @@ -437,21 +449,16 @@ async fn handle_socket( } } } else { - // 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. - let parsed = match &msg { - Message::Text(text) => match serde_json::from_str::(text) { - Ok(value) => Some(value), - Err(err) => { - error!( - "failed to parse JSON message from client \ - {connection_id}: {err}" - ); - None - } - }, - _ => None, + 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, @@ -1219,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 } @@ -1858,8 +1863,8 @@ mod tests { #[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) => { @@ -1873,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) => { @@ -1885,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]