From e70491e2f9f57170dc811c9c91296245c21a199e Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 11:58:53 +0100 Subject: [PATCH 01/10] feat(lib-rt-helpers): frame binary messages rather than hoping they arrive A client reads every binary frame that is not a reserved one as a framed message, so there is no such thing as sending it raw bytes. Bytes with no framing are read as a route length, a route and an id, and what reaches the application is a payload short by however many bytes that invented header consumed, delivered under a route nothing is listening on. Nothing throws and nothing is logged, the subscription simply never fires. The runtime cannot put the framing on itself, because the send it is given carries no route and the id it does carry is its own rather than the one the client sees. Inventing either would mean altering what the application composed and telling the client something the application never said. So the framing belongs to whoever composes the message, and this gives them the means and then holds them to it. An encoder joins the parser that has always been here, refusing anything it cannot represent rather than truncating it into a frame that would be read as something other than what was meant. That covers a route or an id longer than a byte can measure, an empty route, and asking to be acknowledged without an id for the acknowledgement to name. It also refuses a route beginning with one of the reserved bytes, which would otherwise come back from the parser as a ping or an acknowledgement rather than as itself. The runtime then refuses a binary message it cannot read as a frame, on the decode it was already doing, so the check costs nothing and covers every way a message reaches a socket. A handler is told which of its messages was refused and why, rather than watching a client receive nothing. Worth being clear about the limit. Bytes can pass this check by coincidence, as a payload beginning with a small number followed by enough length looks exactly like a short route. There is no byte that separates framed from unframed, which is the same reason a client cannot work it out either, and why the format has to be required rather than detected. --- .../core/src/generated/celerity.runtime.v1.rs | 13 ++ libs/runtime/helpers/src/websockets.rs | 220 +++++++++++++++++- .../proto/celerity/runtime/v1/runtime.proto | 13 ++ libs/runtime/ws/ws-registry/src/errors.rs | 6 + .../ws/ws-registry/src/message_helpers.rs | 63 ++++- 5 files changed, 309 insertions(+), 6 deletions(-) diff --git a/libs/runtime/core/src/generated/celerity.runtime.v1.rs b/libs/runtime/core/src/generated/celerity.runtime.v1.rs index d82cd4fd..9c720863 100644 --- a/libs/runtime/core/src/generated/celerity.runtime.v1.rs +++ b/libs/runtime/core/src/generated/celerity.runtime.v1.rs @@ -433,6 +433,19 @@ pub struct WsSend { pub struct WsOutbound { #[prost(string, tag = "1")] pub connection_id: ::prost::alloc::string::String, + /// Sent to the socket exactly as given. + /// + /// When is_binary is set this must be in the Celerity Binary Message Format, + /// ``. A + /// client reads every binary frame that is not a reserved one as a framed + /// message, so raw bytes are not read as a payload, they are read as a route + /// length, a route and an id, leaving the application a short payload under a + /// route nothing serves. A message carrying no id sets both requireAck and + /// messageIdLength to zero. The runtime refuses a binary message it cannot + /// read as a frame rather than sending one no client can use, reporting it as + /// a WsSendFailure for that message. + /// + /// Text messages are unconstrained beyond the protocol's reserved keys. #[prost(bytes = "vec", tag = "2")] pub message: ::prost::alloc::vec::Vec, #[prost(bool, tag = "3")] diff --git a/libs/runtime/helpers/src/websockets.rs b/libs/runtime/helpers/src/websockets.rs index 6f1b0ccf..7cde1485 100644 --- a/libs/runtime/helpers/src/websockets.rs +++ b/libs/runtime/helpers/src/websockets.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Serialize}; /// The parsed data from a binary message in the -/// [Celerity Binary Message Format](https://celerityframework.io/docs/applications/resources/celerity-api#celerity-binary-message-format) +/// [Celerity Binary Message Format](https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format) /// used for WebSocket APIs. #[derive(Debug, PartialEq)] pub struct BinaryMessageData { @@ -27,7 +27,7 @@ pub enum BinaryMessageParseError { } /// Parses a binary message in the -/// [Celerity Binary Message Format](https://celerityframework.io/docs/applications/resources/celerity-api#celerity-binary-message-format) +/// [Celerity Binary Message Format](https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format) /// used for WebSocket APIs. /// Empty payloads are allowed but all other fields are required. pub fn parse_binary_message( @@ -105,6 +105,92 @@ pub fn parse_binary_message( } } +/// The parts of a binary message to be framed in the +/// [Celerity Binary Message Format](https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format). +pub struct BinaryMessageParts<'a> { + /// The route the message is for, which a client uses to hand it to the + /// right handler. Reserved single byte routes are not built through here, + /// as those frames are fixed and are written out directly. + pub route: &'a str, + /// The id the message is known by, which is what an acknowledgement names, + /// what deduplication keys on and what a loss notification refers to. + pub message_id: Option<&'a str>, + /// Whether the receiver is being asked to acknowledge this message, which + /// only means anything alongside an id. + pub require_ack: bool, + /// The payload, carried without being read. + pub message: &'a [u8], +} + +/// The error type for framing a binary message. +#[derive(Debug, PartialEq)] +pub enum BinaryMessageEncodeError { + Invalid(String), +} + +/// Frames a binary message in the +/// [Celerity Binary Message Format](https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format). +/// +/// The mirror of [`parse_binary_message`], and the reason a caller should not +/// be laying out these bytes itself. Every field that cannot be represented is +/// refused rather than truncated into a frame that would be read as something +/// other than what was meant. +pub fn encode_binary_message( + parts: BinaryMessageParts<'_>, +) -> Result, BinaryMessageEncodeError> { + let route_bytes = parts.route.as_bytes(); + if route_bytes.is_empty() { + return Err(BinaryMessageEncodeError::Invalid( + "a route is required, as it is what the message is delivered by".to_string(), + )); + } + if route_bytes.len() > u8::MAX as usize { + return Err(BinaryMessageEncodeError::Invalid(format!( + "a route can not be longer than {} bytes, this one is {}", + u8::MAX, + route_bytes.len() + ))); + } + // A route is read as reserved when its first byte is one of the reserved + // values, so a custom route starting with one would come back as a ping or + // an acknowledgement rather than as itself. + if route_bytes[0] <= 0x4 { + return Err(BinaryMessageEncodeError::Invalid(format!( + "a route can not begin with the byte {:#x}, which is reserved", + route_bytes[0] + ))); + } + + let message_id_bytes = parts.message_id.unwrap_or_default().as_bytes(); + if message_id_bytes.len() > u8::MAX as usize { + return Err(BinaryMessageEncodeError::Invalid(format!( + "a message id can not be longer than {} bytes, this one is {}", + u8::MAX, + message_id_bytes.len() + ))); + } + // Asking to be acknowledged without an id is refused rather than quietly + // dropped, since the sender would otherwise wait for an answer that has + // nothing to name and can never come. + if parts.require_ack && message_id_bytes.is_empty() { + return Err(BinaryMessageEncodeError::Invalid( + "a message asking to be acknowledged needs an id for the acknowledgement to name" + .to_string(), + )); + } + + let mut framed = + Vec::with_capacity(3 + route_bytes.len() + message_id_bytes.len() + parts.message.len()); + framed.push(route_bytes.len() as u8); + framed.extend_from_slice(route_bytes); + framed.push(if parts.require_ack { 0x1 } else { 0x0 }); + framed.push(message_id_bytes.len() as u8); + framed.extend_from_slice(message_id_bytes); + framed.extend_from_slice(parts.message); + + Ok(framed) +} + /// The data for a lost message. /// This is a notification that a message has been lost. /// It is sent by the server to the client when a message is considered lost. @@ -370,4 +456,134 @@ mod tests { ) ); } + + /// What is framed is what comes back out, which is the property every other + /// use of this depends on. + #[test] + fn test_encode_binary_message_round_trips_through_the_parser() { + let framed = encode_binary_message(BinaryMessageParts { + route: "price.tick", + message_id: Some("m-1"), + require_ack: true, + message: &[0xde, 0xad, 0xbe, 0xef], + }) + .unwrap(); + + assert_eq!( + parse_binary_message(&framed).unwrap(), + BinaryMessageData { + route: BinaryRoute::Custom("price.tick".to_string()), + message_id: Some("m-1".to_string()), + require_ack: true, + message: vec![0xde, 0xad, 0xbe, 0xef], + } + ); + } + + #[test] + fn test_encode_binary_message_lays_the_fields_out_in_order() { + let framed = encode_binary_message(BinaryMessageParts { + route: "up", + message_id: Some("id"), + require_ack: false, + message: &[0xff], + }) + .unwrap(); + + // [routeLength][route][requireAck][messageIdLength][messageId][message] + assert_eq!(framed, vec![0x2, b'u', b'p', 0x0, 0x2, b'i', b'd', 0xff]); + } + + /// A message with nothing to say is still a message, and a message with no + /// id is the ordinary case for one that does not ask to be acknowledged. + #[test] + fn test_encode_binary_message_allows_an_empty_payload_and_no_id() { + let framed = encode_binary_message(BinaryMessageParts { + route: "up", + message_id: None, + require_ack: false, + message: &[], + }) + .unwrap(); + + assert_eq!(framed, vec![0x2, b'u', b'p', 0x0, 0x0]); + assert_eq!( + parse_binary_message(&framed).unwrap(), + BinaryMessageData { + route: BinaryRoute::Custom("up".to_string()), + message_id: None, + require_ack: false, + message: Vec::new(), + } + ); + } + + #[test] + fn test_encode_binary_message_refuses_a_route_it_cannot_represent() { + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: "", + message_id: None, + require_ack: false, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + + let too_long = "r".repeat(256); + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: &too_long, + message_id: None, + require_ack: false, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + } + + /// A custom route beginning with a reserved byte would be read back as a + /// ping or an acknowledgement rather than as itself. + #[test] + fn test_encode_binary_message_refuses_a_route_that_would_read_as_reserved() { + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: "\u{4}route", + message_id: None, + require_ack: false, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + } + + #[test] + fn test_encode_binary_message_refuses_an_id_it_cannot_represent() { + let too_long = "i".repeat(256); + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: "up", + message_id: Some(&too_long), + require_ack: false, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + } + + /// Asking for an acknowledgement with no id is refused rather than framed + /// and ignored, since the sender would wait for an answer that has nothing + /// to name. + #[test] + fn test_encode_binary_message_refuses_an_ack_request_with_no_id() { + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: "up", + message_id: None, + require_ack: true, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + } } diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto index 57f0d79c..02c3fd8f 100644 --- a/libs/runtime/proto/celerity/runtime/v1/runtime.proto +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -294,6 +294,19 @@ message WsSend { message WsOutbound { string connection_id = 1; + // Sent to the socket exactly as given. + // + // When is_binary is set this must be in the Celerity Binary Message Format, + // ``. A + // client reads every binary frame that is not a reserved one as a framed + // message, so raw bytes are not read as a payload, they are read as a route + // length, a route and an id, leaving the application a short payload under a + // route nothing serves. A message carrying no id sets both requireAck and + // messageIdLength to zero. The runtime refuses a binary message it cannot + // read as a frame rather than sending one no client can use, reporting it as + // a WsSendFailure for that message. + // + // Text messages are unconstrained beyond the protocol's reserved keys. bytes message = 2; bool is_binary = 3; repeated string inform_clients_on_loss = 4; diff --git a/libs/runtime/ws/ws-registry/src/errors.rs b/libs/runtime/ws/ws-registry/src/errors.rs index 4d72ff57..57b855d2 100644 --- a/libs/runtime/ws/ws-registry/src/errors.rs +++ b/libs/runtime/ws/ws-registry/src/errors.rs @@ -10,6 +10,9 @@ pub enum WebSocketConnError { MessageLost(String), AckCheckFailed(String), Base64DecodeError(String), + // A binary message that is not in the Celerity Binary Message Format, which + // a client has no way to read as anything other than a framed message. + MalformedBinaryMessage(String), } impl Display for WebSocketConnError { @@ -22,6 +25,9 @@ impl Display for WebSocketConnError { WebSocketConnError::MessageLost(e) => write!(f, "MessageLost: {e}"), WebSocketConnError::AckCheckFailed(e) => write!(f, "AckCheckFailed: {e}"), WebSocketConnError::Base64DecodeError(e) => write!(f, "Base64DecodeError: {e}"), + WebSocketConnError::MalformedBinaryMessage(e) => { + write!(f, "MalformedBinaryMessage: {e}") + } } } } diff --git a/libs/runtime/ws/ws-registry/src/message_helpers.rs b/libs/runtime/ws/ws-registry/src/message_helpers.rs index a12e87e4..ec354fbe 100644 --- a/libs/runtime/ws/ws-registry/src/message_helpers.rs +++ b/libs/runtime/ws/ws-registry/src/message_helpers.rs @@ -1,12 +1,13 @@ use axum::extract::ws::Message; -use base64::{prelude::BASE64_STANDARD, DecodeError, Engine}; +use base64::{prelude::BASE64_STANDARD, Engine}; +use celerity_helpers::websockets::parse_binary_message; use serde_json::{json, Value}; -use crate::types::MessageType; +use crate::{errors::WebSocketConnError, types::MessageType}; /// Creates a message lost event to be sent to a WebSocket connection. /// This follows the Celerity Binary Message Format documented here: -/// https://www.celerityframework.io/docs/applications/resources/celerity-api#celerity-binary-message-format +/// https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format pub fn create_message_lost_event(message_id: String, caller: Option) -> Vec { let payload = json!({ "messageId": message_id, @@ -33,14 +34,29 @@ pub fn create_message_lost_event(message_id: String, caller: Option) -> /// into a message that can be sent to a WebSocket connection. /// Binary messages will be base64 encoded strings that can be stored in stores /// that back WebSocket registries. +/// +/// A binary message must be in the Celerity Binary Message Format and is +/// refused if it is not. A client reads every binary frame that is not a +/// reserved one as a framed message, so there is no such thing as sending it +/// raw bytes. Unframed bytes are read as a route length, a route and an id, and +/// what reaches the application is a payload short by however many bytes that +/// invented header consumed, delivered under a route nothing is listening on. +/// Refusing here turns that silence into an error the sender can see. pub fn create_ws_message( message_type: MessageType, message: String, -) -> Result { +) -> Result { match message_type { MessageType::Json => Ok(Message::Text(message.into())), MessageType::Binary => { let bytes = BASE64_STANDARD.decode(message.as_bytes())?; + // Read from the bytes that were about to be sent, so the check + // costs no second decode. + if let Err(err) = parse_binary_message(&bytes) { + return Err(WebSocketConnError::MalformedBinaryMessage(format!( + "a binary message must be in the Celerity Binary Message Format, {err:?}" + ))); + } Ok(Message::Binary(bytes.into())) } } @@ -91,6 +107,45 @@ mod tests { BASE64_STANDARD.encode(bytes) } + /// Unframed bytes are refused rather than sent, since a client has no way + /// to read them as anything other than a framed message. + #[test] + fn test_create_ws_message_refuses_binary_that_is_not_framed() { + // A protobuf payload, which is the shape of thing an application + // reaches for. Field 1 as a length delimited string, then "price". + let raw = [0x0a, 0x05, b'p', b'r', b'i', b'c', b'e']; + + let result = create_ws_message(MessageType::Binary, BASE64_STANDARD.encode(raw)); + + assert!( + matches!(result, Err(WebSocketConnError::MalformedBinaryMessage(_))), + "unframed bytes should be refused, got {result:?}" + ); + } + + #[test] + fn test_create_ws_message_passes_a_framed_binary_message_through_untouched() { + let framed = frame(b"price.tick", 0x1, b"m-1", &[0xde, 0xad]); + + let message = create_ws_message(MessageType::Binary, framed.clone()).unwrap(); + + match message { + Message::Binary(bytes) => { + assert_eq!(bytes[..], BASE64_STANDARD.decode(framed).unwrap()[..]) + } + other => panic!("a binary message should stay binary, got {other:?}"), + } + } + + /// Text is not framed and is not checked, which is what the spec says and + /// what every JSON message on the wire relies on. + #[test] + fn test_create_ws_message_leaves_text_alone() { + let message = create_ws_message(MessageType::Json, "not json either".to_string()).unwrap(); + + assert!(matches!(message, Message::Text(_))); + } + #[test] fn test_client_ack_request_reads_the_opt_in_from_the_message() { assert_eq!( From b7edcd053c3acd6c09d4b8acb11c1d55d6f7335b Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 11:59:41 +0100 Subject: [PATCH 02/10] docs(runtime-libs): point the documentation links at where the pages now live Every link into the framework documentation was missing the framework segment of the path, so all of them led nowhere. The pages sit under docs/framework, which is what the documentation's own internal links use. The blueprint specification had moved further than that. It is no longer part of the Celerity documentation at all, it belongs to Bluelink and is published on its site, so those links now point there. The anchor they were reaching for is still the one they want. Also dropped the www prefix from the ones that carried it, since the site is served from the bare domain. --- libs/runtime/api-docs/workflow-api/README.md | 2 +- libs/runtime/helpers/README.md | 4 ++-- libs/runtime/signature/README.md | 2 +- libs/runtime/workflow/README.md | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libs/runtime/api-docs/workflow-api/README.md b/libs/runtime/api-docs/workflow-api/README.md index 2303e922..bf044548 100644 --- a/libs/runtime/api-docs/workflow-api/README.md +++ b/libs/runtime/api-docs/workflow-api/README.md @@ -4,7 +4,7 @@ The Celerity Workflow API allows for triggering and monitoring the workflow alon ## Authentication -API calls to a workflow application must be authenticated with an [API key](https://celerityframework.io/docs/auth/api-keys), [Celerity Signature v1](https://celerityframework.io/docs/auth/signature-v1) or a [JWT access token issued by an OAuth2/OpenID connect provider](https://celerityframework.io/docs/auth/jwts). +API calls to a workflow application must be authenticated with an [API key](https://celerityframework.io/docs/framework/auth/api-keys), [Celerity Signature v1](https://celerityframework.io/docs/framework/auth/signature-v1) or a [JWT access token issued by an OAuth2/OpenID connect provider](https://celerityframework.io/docs/framework/auth/jwts). An OAuth2/OpenID Connect provider must publish a JWKS (JSON Web Key Set) for the public key used to verify the JWT signature in the `{issuer}/.well-known/openid-configuration` or `{issuer}/.well-known/oauth-authorization-server` endpoint. diff --git a/libs/runtime/helpers/README.md b/libs/runtime/helpers/README.md index 359836c2..4fb82f5c 100644 --- a/libs/runtime/helpers/README.md +++ b/libs/runtime/helpers/README.md @@ -1,13 +1,13 @@ # celerity runtime workflow This package provides the workflow engine components designed to be used in the Celerity workflow runtime. -This crate provides a HTTP server application for the workflow engine that implements the specification defined in the [Celerity Workflow Specification](https://www.celerityframework.io/docs/applications/resources/celerity-workflow). +This crate provides a HTTP server application for the workflow engine that implements the specification defined in the [Celerity Workflow Specification](https://celerityframework.io/docs/framework/applications/resources/celerity-workflow). This package creates an executable workflow from a blueprint file and a set of handlers. This also provides an API for the registration of handlers. ### About `${..}` Substitutions -The runtime supports a limited version of `${..}` [substitutions](https://www.celerityframework.io/docs/blueprint/specification#references--substitutions). +The runtime supports a limited version of `${..}` [substitutions](https://bluelink.dev/docs/bluelink/blueprints/specification#references--substitutions). Only `${variables.[name]}` substitutions are recognised, all other substitutions are treated as string literals. In the runtime, the parser will replace `${variables.[name]}` with an environment variable of the form `CELERITY_VARIABLE_[name]`, these environment variables are expected to be set at package/build time by a tool like the Celerity Deploy Engine used in the Celerity CLI. diff --git a/libs/runtime/signature/README.md b/libs/runtime/signature/README.md index 9f337173..a58713e9 100644 --- a/libs/runtime/signature/README.md +++ b/libs/runtime/signature/README.md @@ -6,7 +6,7 @@ This package provides helpers for creating and verifying Celerity signatures. This provides functionality for the following signature specs: -- [Celerity Signature v1](https://celerityframework.io/docs/auth/signature-v1) +- [Celerity Signature v1](https://celerityframework.io/docs/framework/auth/signature-v1) ## Additional documentation diff --git a/libs/runtime/workflow/README.md b/libs/runtime/workflow/README.md index 5716cbc3..c8347fe1 100644 --- a/libs/runtime/workflow/README.md +++ b/libs/runtime/workflow/README.md @@ -3,13 +3,13 @@ [![codecov](https://codecov.io/gh/newstack-cloud/celerity/graph/badge.svg?token=u1SKOg58yo&flag=runtime-lib-workflow)](https://codecov.io/gh/newstack-cloud/celerity) This package provides the workflow engine components designed to be used in the Celerity workflow runtime. -This crate provides a HTTP server application for the workflow engine that implements the specification defined in the [Celerity Workflow Specification](https://www.celerityframework.io/docs/applications/resources/celerity-workflow). +This crate provides a HTTP server application for the workflow engine that implements the specification defined in the [Celerity Workflow Specification](https://celerityframework.io/docs/framework/applications/resources/celerity-workflow). This package creates an executable workflow from a blueprint file and a set of handlers. This also provides an API for the registration of handlers. ### About `${..}` Substitutions -The runtime supports a limited version of `${..}` [substitutions](https://www.celerityframework.io/docs/blueprint/specification#references--substitutions). +The runtime supports a limited version of `${..}` [substitutions](https://bluelink.dev/docs/bluelink/blueprints/specification#references--substitutions). Only `${variables.[name]}` substitutions are recognised, all other substitutions are treated as string literals. In the runtime, the parser will replace `${variables.[name]}` with an environment variable of the form `CELERITY_VARIABLE_[name]`, these environment variables are expected to be set at package/build time by a tool like the Celerity Deploy Engine used in the Celerity CLI. From 2648460c9a0051c6aeb7cdef40e26c623f95d770 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 15:19:50 +0100 Subject: [PATCH 03/10] fix(lib-rt-core): wait for a runtime before starting the worker that waits on clients Setting up a websocket API started the worker that tracks messages waiting to be acknowledged, and starting it means spawning. Setting an application up is not an async operation and is called from wherever the host language happens to be, so in the FFI call mode there is no runtime on that thread to spawn into. Every such application died on startup, and not with an error it could report, the process aborted. The worker now starts in run, alongside tracing and the consumers, which are already there for exactly this reason. The registry is kept from setup for run to use, as itself rather than as the trait the rest of the application sends through, since the worker is not part of that trait. Still before anything serves, so a message cannot go out before there is something waiting to hear it arrived. The test for this is deliberately not a tokio test. A tokio test always has the runtime that is missing here, so no test written as one could have shown this, which is why nothing did. --- libs/runtime/core/src/application.rs | 21 ++++++++++++---- .../runtime/core/tests/ipc_end_to_end_test.rs | 24 +++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 28aeb9df..547cb3bf 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -118,6 +118,10 @@ pub struct Application { ipc_server_shutdown_signal: Option>, event_cleanup_task_shutdown_signal: Option>, ws_connections: Option>, + // The same registry as above, held as itself rather than as what it sends + // through, so that `run` can start the worker that waits on clients. + // Taken when it does, since it is only started once. + ws_conn_registry: Option>, ws_app_routes: Arc>>>, custom_auth_guards: Arc>>>, server_shutdown_signal: Option>, @@ -161,6 +165,7 @@ impl Application { ipc_dispatcher_shutdown_signal: None, ipc_server_shutdown_signal: None, ws_connections: None, + ws_conn_registry: None, ws_app_routes: Arc::new(AsyncMutex::new(HashMap::new())), custom_auth_guards: Arc::new(AsyncMutex::new(HashMap::new())), resource_store: None, @@ -340,10 +345,10 @@ impl Application { None, )); self.ws_connections = Some(conn_registry.clone()); - - // Tracks the messages that asked their client to acknowledge them, - // resending and eventually giving up on the ones that go unanswered. - conn_registry.clone().start_client_ack_worker(); + // Kept for `run` to start the worker that tracks the messages + // asking their client to acknowledge them. Starting one here would + // mean spawning, and this runs outside the async runtime when in FFI mode. + self.ws_conn_registry = Some(conn_registry.clone()); // As with HTTP routes, the FFI call mode has the SDK register these // as it binds each in-process handler. In the IPC call mode the @@ -695,6 +700,14 @@ impl Application { self.event_cleanup_task_shutdown_signal = Some(cleanup_task.spawn()); } + // Here rather than in `setup` for the same reason tracing and the + // consumers are, spawning needs a runtime and `setup` is called from + // outside one. Before anything serves, so that no message can go out + // before there is anything waiting to hear it was received. + if let Some(conn_registry) = self.ws_conn_registry.take() { + conn_registry.start_client_ack_worker(); + } + self.run_ipc_stream_server().await?; let mut server_task = None; diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index eb42265b..0e66bc17 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -86,6 +86,30 @@ async fn start_runtime_with( (app, addr, socket) } +/// Setting an application up must not need a runtime to be running. +/// +/// Deliberately not a tokio test, which is the whole point. An SDK calls setup +/// from wherever the host language happens to be, with no runtime on that +/// thread, so anything here that spawns takes the process down rather than +/// returning an error. That is what a websocket API did until the worker that +/// waits on clients moved to `run`, and a tokio test cannot show it because a +/// tokio test always has the runtime that is missing. +#[test] +fn sets_up_a_websocket_api_without_a_runtime_to_spawn_into() { + let socket = socket_path("ipc-ws-setup-sync"); + let env_vars = ipc_env( + "ipc-ws-setup-sync", + "tests/data/fixtures/ipc-websocket-default-route.blueprint.yaml", + &socket, + &[], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + + app.setup() + .expect("setting up a websocket api should not need a runtime"); +} + /// Stands in for a handlers executable. struct HandlerStub { /// The events the handler was asked to process. From efd0ab65d9d4dd9df29724c88568d92bd6ae7e9d Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 15:20:19 +0100 Subject: [PATCH 04/10] feat(lib-rt-sdk-python): give handlers a way to frame a binary message A client reads every binary frame that is not a reserved one as a framed message, so a handler sending a payload without framing it is not sending a payload. The bytes are read as a route length, a route and an id, and the application on the other side is handed what is left under a route it never subscribed to. The runtime refuses such a message now rather than sending one no client can use, which leaves a handler needing a way to compose one it will accept. Composing it by hand meant laying out four header fields from the specification and base64 encoding the result, since that is the form the send takes for binary. The encoder does both, returning the message ready to send, and refuses anything that cannot be represented rather than truncating it into a frame that would be read as something other than what was meant. --- libs/runtime/sdk/python/Cargo.toml | 1 + .../python/celerity_runtime_sdk/__init__.py | 2 + .../_celerity_runtime_sdk.pyi | 35 ++++++++++++++++ libs/runtime/sdk/python/src/lib.rs | 4 ++ libs/runtime/sdk/python/src/websockets.rs | 42 +++++++++++++++++++ .../sdk/python/tests/test_websocket.py | 30 ++++++++++++- 6 files changed, 113 insertions(+), 1 deletion(-) diff --git a/libs/runtime/sdk/python/Cargo.toml b/libs/runtime/sdk/python/Cargo.toml index 99e4630e..89cf5a91 100644 --- a/libs/runtime/sdk/python/Cargo.toml +++ b/libs/runtime/sdk/python/Cargo.toml @@ -28,6 +28,7 @@ tracing = "0.1.40" tracing-core = "0.1.32" tracing-subscriber = { version = "0.3.20", features = ["chrono", "json"] } async-trait = "0.1.88" +base64 = "0.22.1" pythonize = "0.25.0" chrono = "0.4.41" diff --git a/libs/runtime/sdk/python/python/celerity_runtime_sdk/__init__.py b/libs/runtime/sdk/python/python/celerity_runtime_sdk/__init__.py index fba38f96..9f5af9eb 100644 --- a/libs/runtime/sdk/python/python/celerity_runtime_sdk/__init__.py +++ b/libs/runtime/sdk/python/python/celerity_runtime_sdk/__init__.py @@ -30,6 +30,7 @@ RequestContext, HttpProtocolVersion, WebSocketRegistry, + encode_binary_message, SendContext, WebSocketMessageType, WebSocketEventType, @@ -76,6 +77,7 @@ "RequestContext", "HttpProtocolVersion", "WebSocketRegistry", + "encode_binary_message", "SendContext", "WebSocketMessageType", "WebSocketEventType", diff --git a/libs/runtime/sdk/python/python/celerity_runtime_sdk/_celerity_runtime_sdk.pyi b/libs/runtime/sdk/python/python/celerity_runtime_sdk/_celerity_runtime_sdk.pyi index e7e6feb8..7cc7b550 100644 --- a/libs/runtime/sdk/python/python/celerity_runtime_sdk/_celerity_runtime_sdk.pyi +++ b/libs/runtime/sdk/python/python/celerity_runtime_sdk/_celerity_runtime_sdk.pyi @@ -1336,6 +1336,41 @@ class WebSocketRegistry: """ +def encode_binary_message( + route: str, + message: bytes, + message_id: str | None = None, + require_ack: bool = False, +) -> str: + """ + Frames a binary message in the Celerity Binary Message Format. + + A client reads every binary frame that is not a reserved one as a framed message, + so a payload sent without this is not read as a payload. It is read as a route + length, a route and an id, and what reaches the application is short by however + many bytes that are treated as headers, under a route nothing is listening on. + The runtime refuses a binary message it cannot read as a frame, so this is how a + handler composes one it will accept. + + Args: + route: The route the message is for, which is how a client hands it to the + right handler. At most 255 bytes, and it can not begin with one of the + bytes the protocol reserves for its own frames. + message: The payload, carried to the client without being read. + message_id: The id the message is known by, which is what an acknowledgement + names and what deduplication keys on. At most 255 bytes. + require_ack: Whether the client is being asked to acknowledge this message, + which needs an id for the acknowledgement to name. + + Returns: + The framed message base64 encoded, which is the form `send_message` takes for + a binary message, so the result can be passed straight to it. + + Raises: + ValueError: If any part cannot be represented in the format. + """ + + class ConsumerEventInput: """ The handler input for when consumer event messages are received from an event source. diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index 19b3c874..4c6aa575 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -1002,6 +1002,10 @@ fn _celerity_runtime_sdk(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_function(wrap_pyfunction!( + crate::websockets::encode_binary_message, + m + )?)?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/libs/runtime/sdk/python/src/websockets.rs b/libs/runtime/sdk/python/src/websockets.rs index e0252a20..1076be90 100644 --- a/libs/runtime/sdk/python/src/websockets.rs +++ b/libs/runtime/sdk/python/src/websockets.rs @@ -1,6 +1,11 @@ use std::{collections::HashMap, sync::Arc}; use async_trait::async_trait; +use base64::{prelude::BASE64_STANDARD, Engine}; +use celerity_helpers::websockets::{ + encode_binary_message as encode_binary_message_inner, BinaryMessageEncodeError, + BinaryMessageParts, +}; use celerity_runtime_core::{ config::{WebSocketConfig, WebSocketHandlerDefinition}, errors::WebSocketsMessageError, @@ -523,6 +528,43 @@ impl From for MessageType { } } +/// Frames a binary message in the Celerity Binary Message Format. +/// +/// A client reads every binary frame that is not a reserved one as a framed +/// message, so a payload sent without this is not read as a payload. It is read +/// as a route length, a route and an id, and what reaches the application is +/// short by however many bytes that are treated as headers, under a route +/// nothing is listening on. The runtime refuses a binary message it cannot read +/// as a frame, so this is how a handler composes one it will accept. +/// +/// The route can be at most 255 bytes and can not begin with one of the bytes +/// the protocol reserves for its own frames. The message id, which is what an +/// acknowledgement names and what deduplication keys on, can also be at most +/// 255 bytes, and is required when asking to be acknowledged. +/// +/// Returns the framed message base64 encoded, which is the form `send_message` +/// takes for a binary message, so the result can be passed straight to it. +#[pyfunction] +#[pyo3(signature = (route, message, message_id=None, require_ack=false))] +pub fn encode_binary_message( + route: &str, + message: &[u8], + message_id: Option<&str>, + require_ack: bool, +) -> PyResult { + let framed = encode_binary_message_inner(BinaryMessageParts { + route, + message_id, + require_ack, + message, + }) + .map_err(|BinaryMessageEncodeError::Invalid(reason)| { + pyo3::exceptions::PyValueError::new_err(format!("encode_binary_message failed: {reason}")) + })?; + + Ok(BASE64_STANDARD.encode(framed)) +} + #[pyclass(name = "WebSocketRegistry")] pub struct WSBindingRegistrySend { pub inner: Arc, diff --git a/libs/runtime/sdk/python/tests/test_websocket.py b/libs/runtime/sdk/python/tests/test_websocket.py index 920a0f7e..b96d28ed 100644 --- a/libs/runtime/sdk/python/tests/test_websocket.py +++ b/libs/runtime/sdk/python/tests/test_websocket.py @@ -1,3 +1,4 @@ +import base64 import json import os import shutil @@ -8,7 +9,11 @@ import pytest from dotenv import dotenv_values from websocket import create_connection -from celerity_runtime_sdk import CoreRuntimeApplication, CoreRuntimeConfigBuilder +from celerity_runtime_sdk import ( + CoreRuntimeApplication, + CoreRuntimeConfigBuilder, + encode_binary_message, +) WS_SERVER_PORT = 22362 WS_URL = f"ws://localhost:{WS_SERVER_PORT}/ws" @@ -224,3 +229,26 @@ def test_ws_request_context(ws_server): assert msg["requestContext"]["path"] == "/ws" finally: ws.close() + + +def test_encode_binary_message_lays_out_the_celerity_binary_message_format(): + framed = base64.b64decode( + encode_binary_message("up", b"\xff", message_id="id") + ) + + # [routeLength][route][requireAck][messageIdLength][messageId][message] + assert framed == bytes([0x02, 0x75, 0x70, 0x00, 0x02, 0x69, 0x64, 0xFF]) + + +def test_encode_binary_message_refuses_what_it_cannot_represent(): + # An empty route, which is what the message would be delivered by. + with pytest.raises(ValueError): + encode_binary_message("", b"\x01") + + # A route longer than the single byte that measures it. + with pytest.raises(ValueError): + encode_binary_message("r" * 256, b"\x01") + + # Asking to be acknowledged with no id for the acknowledgement to name. + with pytest.raises(ValueError): + encode_binary_message("up", b"\x01", require_ack=True) From b409262306efcc62fc3cb09e76d641eb17168337 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 15:20:42 +0100 Subject: [PATCH 05/10] feat(lib-rt-sdk-node): give handlers a way to frame a binary message A client reads every binary frame that is not a reserved one as a framed message, so a handler sending a payload without framing it is not sending a payload. The bytes are read as a route length, a route and an id, and the application on the other side is handed what is left under a route it never subscribed to. The runtime refuses such a message now rather than sending one no client can use, which leaves a handler needing a way to compose one it will accept. Composing it by hand meant laying out four header fields from the specification and base64 encoding the result, since that is the form the send takes for binary. The encoder does both, taking the payload as a buffer and returning the message ready to send, and refuses anything that cannot be represented rather than truncating it into a frame that would be read as something other than what was meant. Re-exported from the crate root because nothing in Rust calls it. Only JavaScript does, and the compiler cannot see that. The tests also stop taking the capabilities signal as the first message a client receives. It is a binary frame of its own that arrives the moment a connection opens, and whether it lands before or after a listener is attached comes down to timing, which is what made one of them fail only under load. The lockfile also carries the encoding dependency added to the Python SDK, since there is only the one. --- libs/runtime/Cargo.lock | 2 + libs/runtime/sdk/node/Cargo.toml | 1 + .../sdk/node/__test__/websocket.spec.ts | 149 +++++++++++++++++- libs/runtime/sdk/node/index.d.ts | 51 ++++++ libs/runtime/sdk/node/index.js | 105 ++++++------ libs/runtime/sdk/node/src/lib.rs | 5 + libs/runtime/sdk/node/src/websocket.rs | 52 ++++++ 7 files changed, 311 insertions(+), 54 deletions(-) diff --git a/libs/runtime/Cargo.lock b/libs/runtime/Cargo.lock index 1b39f971..4ba38712 100644 --- a/libs/runtime/Cargo.lock +++ b/libs/runtime/Cargo.lock @@ -988,6 +988,7 @@ dependencies = [ "async-trait", "axum 0.8.8", "axum-extra 0.10.3", + "base64 0.22.1", "celerity_helpers", "celerity_runtime_core", "celerity_ws_registry", @@ -1362,6 +1363,7 @@ dependencies = [ "async-trait", "axum 0.8.8", "axum-extra 0.10.3", + "base64 0.22.1", "celerity_helpers", "celerity_runtime_core", "celerity_ws_registry", diff --git a/libs/runtime/sdk/node/Cargo.toml b/libs/runtime/sdk/node/Cargo.toml index bb3a5f5c..2a7153f1 100644 --- a/libs/runtime/sdk/node/Cargo.toml +++ b/libs/runtime/sdk/node/Cargo.toml @@ -16,6 +16,7 @@ napi = { version = "3.8", default-features = false, features = [ ] } napi-derive = "3" async-trait = "0.1.88" +base64 = "0.22.1" tokio = "1.39.2" axum = "0.8.4" axum-extra = { version = "0.10.1", features = ["cookie"] } diff --git a/libs/runtime/sdk/node/__test__/websocket.spec.ts b/libs/runtime/sdk/node/__test__/websocket.spec.ts index 72f7e179..54e21948 100644 --- a/libs/runtime/sdk/node/__test__/websocket.spec.ts +++ b/libs/runtime/sdk/node/__test__/websocket.spec.ts @@ -2,6 +2,7 @@ import test from "ava"; import { CoreRuntimeApplication, CoreRuntimePlatform, + encodeBinaryMessage, JsMessageType, type CoreRuntimeAppConfig, type CoreRuntimeConfig, @@ -53,16 +54,31 @@ function openWs(url: string): Promise { } /** Waits for the next message on a WebSocket. */ +/** The capabilities signal, which arrives on its own the moment a connection + * opens and is not a message any test is waiting for. */ +function isCapabilitiesSignal(data: Buffer, isBinary: boolean): boolean { + return ( + isBinary && data.length === 4 && data[0] === 0x01 && data[1] === 0x05 + ); +} + function nextWsMessage(ws: WebSocket, timeoutMs = 5000): Promise { return new Promise((resolve, reject) => { const timer = setTimeout( () => reject(new Error("timeout waiting for WS message")), timeoutMs, ); - ws.once("message", (data) => { + // Passed over rather than taken as the first message. Whether the signal + // lands before or after a listener is attached comes down to timing. + const onMessage = (data: Buffer, isBinary: boolean) => { + if (isCapabilitiesSignal(data, isBinary)) { + return; + } + ws.off("message", onMessage); clearTimeout(timer); resolve(data.toString()); - }); + }; + ws.on("message", onMessage); }); } @@ -438,3 +454,132 @@ test("WS request context includes connection metadata", async (t) => { app.shutdown(); } }); + +// --------------------------------------------------------------------------- +// 8. Binary message framing +// --------------------------------------------------------------------------- + +test("encodeBinaryMessage lays out the Celerity Binary Message Format", (t) => { + const framed = Buffer.from( + encodeBinaryMessage({ + route: "up", + messageId: "id", + requireAck: false, + message: Buffer.from([0xff]), + }), + "base64", + ); + + // [routeLength][route][requireAck][messageIdLength][messageId][message] + t.deepEqual( + [...framed], + [0x02, 0x75, 0x70, 0x00, 0x02, 0x69, 0x64, 0xff], + ); +}); + +test("encodeBinaryMessage refuses what it cannot represent", (t) => { + // An empty route, which is what the message would be delivered by. + t.throws(() => + encodeBinaryMessage({ route: "", message: Buffer.from([0x01]) }), + ); + + // A route longer than the single byte that measures it. + t.throws(() => + encodeBinaryMessage({ route: "r".repeat(256), message: Buffer.from([0x01]) }), + ); + + // Asking to be acknowledged with no id for the acknowledgement to name. + t.throws(() => + encodeBinaryMessage({ + route: "up", + requireAck: true, + message: Buffer.from([0x01]), + }), + ); +}); + +test("a framed binary message reaches the client exactly as composed", async (t) => { + const serverPort = PORT + 16; + const app = new CoreRuntimeApplication(testConfig({ serverPort })); + const config = app.setup(); + + const registry = app.websocketRegistry(); + const payload = Buffer.from([0xde, 0xad, 0xbe, 0xef]); + const framed = encodeBinaryMessage({ + route: "updates", + messageId: "m-1", + requireAck: false, + message: payload, + }); + let refusedUnframed: unknown = null; + + for (const handler of config.api?.websocket?.handlers ?? []) { + if (handler.route === "echo") { + app.registerWebsocketHandler( + handler.route, + async (_err: Error | null, msg: JsWebSocketMessageInfo) => { + // Raw bytes are refused, since a client would read them as a route + // and an id rather than as a payload. + try { + await registry.sendMessage( + msg.connectionId, + msg.messageId, + "binary" as JsMessageType, + payload.toString("base64"), + null, + ); + } catch (err) { + refusedUnframed = err; + } + + await registry.sendMessage( + msg.connectionId, + msg.messageId, + "binary" as JsMessageType, + framed, + null, + ); + }, + ); + } else { + app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + } + } + + await app.run(false); + + try { + const ws = await openWs(`ws://localhost:${serverPort}/ws`); + try { + const received = deferred(); + ws.on("message", (data: Buffer, isBinary: boolean) => { + if (!isBinary) { + return; + } + if (isCapabilitiesSignal(data, isBinary)) { + return; + } + received.resolve(Buffer.from(data)); + }); + + ws.send(JSON.stringify({ action: "echo", data: "ping" })); + + const timer = setTimeout( + () => received.reject(new Error("timeout waiting for the binary frame")), + 5000, + ); + const frame = await received.promise; + clearTimeout(timer); + + t.truthy(refusedUnframed, "unframed bytes should have been refused"); + t.deepEqual([...frame], [...Buffer.from(framed, "base64")]); + // The payload survives with the framing in front of it, untouched. + t.deepEqual([...frame.subarray(frame.length - payload.length)], [...payload]); + } finally { + ws.close(); + } + } finally { + await new Promise((r) => setTimeout(r, 200)); + app.shutdown(); + } +}); diff --git a/libs/runtime/sdk/node/index.d.ts b/libs/runtime/sdk/node/index.d.ts index 27132219..6289e25c 100644 --- a/libs/runtime/sdk/node/index.d.ts +++ b/libs/runtime/sdk/node/index.d.ts @@ -203,6 +203,12 @@ export declare class CoreRuntimeConfigBuilder { * If not set, falls back to the `CELERITY_LOG_FORMAT` environment variable. */ setLogFormat(value: string): this + /** + * Sets whether to serve the local handler invoke endpoint. Defaults to + * `false`, and is only served when the platform is `Local` or test mode + * is on. + */ + setEnableLocalInvoke(value: boolean): this /** Sets whether to enable metrics collection. Defaults to `false`. */ setMetricsEnabled(value: boolean): this /** Sets the trace sampling ratio (0.0–1.0). Defaults to `0.1` (10%). */ @@ -461,6 +467,13 @@ export interface CoreRuntimeConfig { * environment variable. */ logFormat?: string + /** + * Whether to serve `POST /runtime/handlers/invoke`, which runs any handler + * by name with a payload the caller supplies, bypassing whatever normally + * triggers it and with no authentication. Defaults to `false`, and is only + * served when the platform is `Local` or test mode is on. + */ + enableLocalInvoke?: boolean /** Whether to enable metrics collection. Defaults to `false` when not set. */ metricsEnabled?: boolean /** The trace sampling ratio (0.0–1.0). Defaults to `0.1` (10%) when not set. */ @@ -514,6 +527,21 @@ export interface CoreWebSocketHandlerDefinition { timeout: number } +/** + * Frames a binary message in the Celerity Binary Message Format. + * + * A client reads every binary frame that is not a reserved one as a framed + * message, so a payload sent without this is not read as a payload. It is read + * as a route length, a route and an id, and what reaches the application is + * short by however many bytes that are treated as headers, under a route + * nothing is listening on. The runtime refuses a binary message it cannot read + * as a frame, so this is how a handler composes one it will accept. + * + * Returns the framed message base64 encoded, which is the form `sendMessage` + * takes for a binary message, so the result can be passed straight to it. + */ +export declare function encodeBinaryMessage(parts: JsBinaryMessageParts): string + /** The input passed to a guard handler callback from the Rust runtime. */ export interface GuardInput { /** @@ -558,6 +586,29 @@ export interface GuardResult { message?: string } +/** The parts of a binary message to be framed for a WebSocket client. */ +export interface JsBinaryMessageParts { + /** + * The route the message is for, which is how a client hands it to the right + * handler. No longer than 255 bytes, and it can not begin with one of the + * bytes the protocol reserves for its own frames. + */ + route: string + /** + * The id the message is known by, which is what an acknowledgement names, + * what deduplication keys on and what a loss notification refers to. No + * longer than 255 bytes. + */ + messageId?: string + /** + * Whether the client is being asked to acknowledge this message, which only + * means anything alongside an id. + */ + requireAck?: boolean + /** The payload, carried to the client without being read. */ + message: Buffer +} + /** The handler input for when consumer event messages are received from an event source. */ export interface JsConsumerEventInput { /** A tag identifying the handler, in the format "source::\::\". */ diff --git a/libs/runtime/sdk/node/index.js b/libs/runtime/sdk/node/index.js index 3b4fb9b5..e860c85f 100644 --- a/libs/runtime/sdk/node/index.js +++ b/libs/runtime/sdk/node/index.js @@ -77,8 +77,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-android-arm64') const bindingPackageVersion = require('@celerity-sdk/runtime-android-arm64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -93,8 +93,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-android-arm-eabi') const bindingPackageVersion = require('@celerity-sdk/runtime-android-arm-eabi/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -114,8 +114,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-win32-x64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-win32-x64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -130,8 +130,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-win32-x64-msvc') const bindingPackageVersion = require('@celerity-sdk/runtime-win32-x64-msvc/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -147,8 +147,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-win32-ia32-msvc') const bindingPackageVersion = require('@celerity-sdk/runtime-win32-ia32-msvc/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -163,8 +163,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-win32-arm64-msvc') const bindingPackageVersion = require('@celerity-sdk/runtime-win32-arm64-msvc/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -182,8 +182,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-darwin-universal') const bindingPackageVersion = require('@celerity-sdk/runtime-darwin-universal/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -198,8 +198,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-darwin-x64') const bindingPackageVersion = require('@celerity-sdk/runtime-darwin-x64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -214,8 +214,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-darwin-arm64') const bindingPackageVersion = require('@celerity-sdk/runtime-darwin-arm64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -234,8 +234,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-freebsd-x64') const bindingPackageVersion = require('@celerity-sdk/runtime-freebsd-x64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -250,8 +250,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-freebsd-arm64') const bindingPackageVersion = require('@celerity-sdk/runtime-freebsd-arm64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -271,8 +271,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-x64-musl') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-x64-musl/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -287,8 +287,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-x64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-x64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -305,8 +305,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-arm64-musl') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-arm64-musl/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -321,8 +321,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-arm64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-arm64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -339,8 +339,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-arm-musleabihf') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-arm-musleabihf/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -355,8 +355,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-arm-gnueabihf') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-arm-gnueabihf/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -373,8 +373,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-loong64-musl') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-loong64-musl/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -389,8 +389,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-loong64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-loong64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -407,8 +407,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-riscv64-musl') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-riscv64-musl/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -423,8 +423,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-riscv64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-riscv64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -440,8 +440,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-ppc64-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-ppc64-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -456,8 +456,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-linux-s390x-gnu') const bindingPackageVersion = require('@celerity-sdk/runtime-linux-s390x-gnu/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -476,8 +476,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-openharmony-arm64') const bindingPackageVersion = require('@celerity-sdk/runtime-openharmony-arm64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -492,8 +492,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-openharmony-x64') const bindingPackageVersion = require('@celerity-sdk/runtime-openharmony-x64/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -508,8 +508,8 @@ function requireNative() { try { const binding = require('@celerity-sdk/runtime-openharmony-arm') const bindingPackageVersion = require('@celerity-sdk/runtime-openharmony-arm/package.json').version - if (bindingPackageVersion !== '0.3.2' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.3.2 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (bindingPackageVersion !== '0.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } return binding } catch (e) { @@ -582,6 +582,7 @@ module.exports.CoreWebSocketRegistry = nativeBinding.CoreWebSocketRegistry module.exports.Request = nativeBinding.Request module.exports.JsRequestWrapper = nativeBinding.JsRequestWrapper module.exports.CoreRuntimePlatform = nativeBinding.CoreRuntimePlatform +module.exports.encodeBinaryMessage = nativeBinding.encodeBinaryMessage module.exports.JsMessageType = nativeBinding.JsMessageType module.exports.JsWebSocketEventType = nativeBinding.JsWebSocketEventType module.exports.runtimeConfigFromEnv = nativeBinding.runtimeConfigFromEnv diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index f5427046..58cdcfe7 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -5,6 +5,11 @@ mod consumer; mod invoke; mod websocket; +// Re-exported so that the framing helper is reachable from outside the crate. +// The other bindings in that module are reached through code here, but this one +// is only ever called from JavaScript, which is not a use the compiler can see. +pub use websocket::{encode_binary_message, JsBinaryMessageParts}; + use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; diff --git a/libs/runtime/sdk/node/src/websocket.rs b/libs/runtime/sdk/node/src/websocket.rs index 2441671e..76d90487 100644 --- a/libs/runtime/sdk/node/src/websocket.rs +++ b/libs/runtime/sdk/node/src/websocket.rs @@ -1,6 +1,11 @@ use std::{collections::HashMap, sync::Arc}; use async_trait::async_trait; +use base64::{prelude::BASE64_STANDARD, Engine}; +use celerity_helpers::websockets::{ + encode_binary_message as encode_binary_message_inner, BinaryMessageEncodeError, + BinaryMessageParts, +}; use celerity_runtime_core::{ errors::WebSocketsMessageError, websocket::{ @@ -252,6 +257,53 @@ impl From for SendContext { } } +/// The parts of a binary message to be framed for a WebSocket client. +#[napi(object)] +pub struct JsBinaryMessageParts { + /// The route the message is for, which is how a client hands it to the right + /// handler. No longer than 255 bytes, and it can not begin with one of the + /// bytes the protocol reserves for its own frames. + pub route: String, + /// The id the message is known by, which is what an acknowledgement names, + /// what deduplication keys on and what a loss notification refers to. No + /// longer than 255 bytes. + pub message_id: Option, + /// Whether the client is being asked to acknowledge this message, which only + /// means anything alongside an id. + pub require_ack: Option, + /// The payload, carried to the client without being read. + pub message: Buffer, +} + +/// Frames a binary message in the Celerity Binary Message Format. +/// +/// A client reads every binary frame that is not a reserved one as a framed +/// message, so a payload sent without this is not read as a payload. It is read +/// as a route length, a route and an id, and what reaches the application is +/// short by however many bytes that are treated as headers, under a route +/// nothing is listening on. The runtime refuses a binary message it cannot read +/// as a frame, so this is how a handler composes one it will accept. +/// +/// Returns the framed message base64 encoded, which is the form `sendMessage` +/// takes for a binary message, so the result can be passed straight to it. +#[napi] +pub fn encode_binary_message(parts: JsBinaryMessageParts) -> Result { + let framed = encode_binary_message_inner(BinaryMessageParts { + route: &parts.route, + message_id: parts.message_id.as_deref(), + require_ack: parts.require_ack.unwrap_or(false), + message: &parts.message, + }) + .map_err(|BinaryMessageEncodeError::Invalid(reason)| { + Error::new( + Status::InvalidArg, + format!("encode_binary_message failed: {reason}"), + ) + })?; + + Ok(BASE64_STANDARD.encode(framed)) +} + /// Registry for sending messages to WebSocket connections. /// /// This is thread-safe and can be used from handler functions to send messages From 2ff0b223838d5195113c7870de95cf0a473bb789 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 15:31:15 +0100 Subject: [PATCH 06/10] test(lib-rt-core): cover what a handler is told when a binary send is refused The contract says a binary message the runtime cannot read as a frame is refused and reported against the message it belongs to. That was true by construction and asserted nowhere, because nothing on this side of the stream could send in the first place. The stub only ever answered dispatches, so a handler sending messages of its own accord had no coverage at all, which is a gap wider than the refusal it was hiding. The stub can now send frames and read back what the runtime made of them. The test sends one batch carrying a raw payload and a framed one, and requires the batch to fail, the failure to name the first message by index and connection, and the framed message to arrive at the client exactly as composed. The batch carries both because failures are per message rather than per batch, so one bad message must not take the others down with it. --- .../runtime/core/tests/ipc_end_to_end_test.rs | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index 0e66bc17..2a0b8ec0 100644 --- a/libs/runtime/core/tests/ipc_end_to_end_test.rs +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -14,6 +14,7 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use celerity_runtime_core::{ application::Application, config::RuntimeConfig, + consts::CELERITY_WS_CAPABILITIES_SIGNAL, ipc_proto::{ self as proto, handler_message, handler_runtime_service_client::HandlerRuntimeServiceClient, runtime_message, @@ -116,6 +117,11 @@ struct HandlerStub { dispatches: mpsc::Receiver, /// The events the handler was told to stop working on. cancels: mpsc::Receiver, + /// Frames the handler sends of its own accord, rather than in answer to a + /// dispatch. + outbound: mpsc::Sender, + /// What the runtime made of each batch of websocket sends. + ws_acks: mpsc::Receiver, } impl HandlerStub { @@ -189,6 +195,8 @@ impl HandlerStub { let (dispatch_tx, dispatches) = mpsc::channel(16); let (cancel_tx, cancels) = mpsc::channel(16); + let (ws_ack_tx, ws_acks) = mpsc::channel(16); + let outbound = handler_tx.clone(); tokio::spawn(async move { while let Some(Ok(message)) = frames.next().await { let dispatch = match message.frame { @@ -197,6 +205,10 @@ impl HandlerStub { cancel_tx.send(cancel).await.ok(); continue; } + Some(runtime_message::Frame::WsAck(ack)) => { + ws_ack_tx.send(ack).await.ok(); + continue; + } _ => continue, }; let outcome = respond(&dispatch); @@ -221,9 +233,32 @@ impl HandlerStub { HandlerStub { dispatches, cancels, + outbound, + ws_acks, } } + /// Sends a batch of websocket messages the way a handler does, of its own + /// accord rather than as the result of an event. + async fn send_ws(&self, correlation_id: &str, messages: Vec) { + self.outbound + .send(proto::HandlerMessage { + frame: Some(handler_message::Frame::WsSend(proto::WsSend { + correlation_id: correlation_id.to_string(), + messages, + })), + }) + .await + .expect("the runtime should still be taking frames"); + } + + async fn next_ws_ack(&mut self) -> Option { + tokio::time::timeout(Duration::from_secs(10), self.ws_acks.recv()) + .await + .ok() + .flatten() + } + async fn next_dispatch(&mut self) -> Option { tokio::time::timeout(Duration::from_secs(10), self.dispatches.recv()) .await @@ -1085,6 +1120,111 @@ 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. +/// +/// 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( + "ipc-ws-binary-framing", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + 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(0x0); + framed.push(0x0); + framed.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + + handler + .send_ws( + "batch-1", + vec![ + // Raw bytes, which is what an application reaches for when it + // does not know the format is required. A protobuf payload + // here, field one as a length delimited string. + proto::WsOutbound { + connection_id: connection_id.clone(), + message: vec![0x0a, 0x05, b'p', b'r', b'i', b'c', b'e'], + is_binary: true, + ..Default::default() + }, + proto::WsOutbound { + connection_id: connection_id.clone(), + message: framed.clone(), + is_binary: true, + ..Default::default() + }, + ], + ) + .await; + + let ack = handler + .next_ws_ack() + .await + .expect("the runtime should report what became of the batch"); + assert_eq!(ack.correlation_id, "batch-1"); + assert!( + !ack.success, + "a batch with a refused message is not a success" + ); + assert_eq!( + ack.failures.len(), + 1, + "only the unframed message should fail" + ); + assert_eq!( + ack.failures[0].index, 0, + "the failure should name the message that was refused" + ); + assert_eq!(ack.failures[0].connection_id, connection_id); + + // The framed one still arrives, exactly as the handler composed it, and it + // is the only binary frame after the capabilities signal. + 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 framed message should reach the client"); + + assert_eq!(delivered, Some(framed)); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} + #[test_log::test(tokio::test)] async fn answers_heartbeats_while_a_handler_is_still_running() { let (_app, addr, socket) = start_runtime( From 8d8e804f6035488b9402c634fc63ab4eb51f39f8 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 15:44:20 +0100 Subject: [PATCH 07/10] refactor(lib-rt-helpers): build the protocol's own messages from one place A reserved message is not a different format from an application's, it is the same one with a route that happens to be a single byte, asking for no acknowledgement and carrying no id of its own. That header was written out by hand at each place one was built, four spellings of the same four bytes, and none of them knew about the others. That is how one of them came to be written with two bytes rather than four, leaving a lost message notification no client could recognise as one. Nothing disagreed, because nothing else knew what the header should be. There is now one constructor for them, next to the parser that reads them, so the two are checked against each other by a round trip rather than by whoever notices a client ignoring something. The lost message notification, the pong, the acknowledgement and the capabilities signal all go through it. The constants stay, since matching an inbound frame wants a fixed size array rather than something built each time, but a test holds them against what the constructor produces so the two spellings that remain cannot drift apart. --- libs/runtime/core/src/websocket.rs | 32 ++++++++-- libs/runtime/helpers/src/websockets.rs | 64 +++++++++++++++++++ .../ws/ws-registry/src/message_helpers.rs | 15 +---- 3 files changed, 93 insertions(+), 18 deletions(-) diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index d01c160d..6ec5ca8b 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -26,6 +26,7 @@ use celerity_blueprint_config_parser::blueprint::{ use celerity_helpers::{ http::ResourceStore, request::{headers_to_hashmap, query_from_uri}, + websockets::{encode_reserved_message, ReservedRoute}, }; use celerity_ws_registry::registry::{WebSocketConnRegistry, WebSocketConnSender}; use futures::{SinkExt, StreamExt}; @@ -45,7 +46,7 @@ use crate::{ }, auth_jwt::{validate_jwt_on_ws_connect, ValidateJwtError}, consts::{ - CELERITY_WS_ACK_SIGNAL, CELERITY_WS_CAPABILITIES_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, + CELERITY_WS_ACK_SIGNAL, CELERITY_WS_CONNECT_HANDLER_ROUTE, CELERITY_WS_DEFAULT_MESSAGE_HANDLER_ROUTE, CELERITY_WS_DISCONNECT_HANDLER_ROUTE, CELERITY_WS_FORBIDDEN_ERROR_CODE, CELERITY_WS_UNAUTHORISED_ERROR_CODE, WS_CONNECTION_DRAIN_GRACE_MS, WS_CONNECTION_SATURATED_RETRY_AFTER_MS, @@ -318,7 +319,7 @@ async fn handle_socket( let mut sock = socket_ref.lock().await; let _ = sock .send(Message::Binary( - CELERITY_WS_CAPABILITIES_SIGNAL.to_vec().into(), + encode_reserved_message(ReservedRoute::Capabilities, &[]).into(), )) .await; } @@ -1158,7 +1159,9 @@ fn detect_heartbeat_ping(msg: &Message) -> Option { && bytes[2] == 0x0 && bytes[3] == 0x0 { - return Some(Message::Binary(vec![0x1, 0x2, 0x0, 0x0].into())); + return Some(Message::Binary( + encode_reserved_message(ReservedRoute::Pong, &[]).into(), + )); } None } @@ -1396,9 +1399,7 @@ async fn acknowledge( AckFormat::Binary => { let body = serde_json::json!({ "messageId": message_id, "timestamp": timestamp }).to_string(); - let mut frame = CELERITY_WS_ACK_SIGNAL.to_vec(); - frame.extend_from_slice(body.as_bytes()); - Message::Binary(frame.into()) + Message::Binary(encode_reserved_message(ReservedRoute::Ack, body.as_bytes()).into()) } }; @@ -1653,6 +1654,25 @@ async fn close_with_retry_after(socket_ref: Arc>, ret #[cfg(test)] mod tests { use super::*; + // Only needed to hold the constant against the encoder, since nothing + // outside the tests matches on it. + use crate::consts::CELERITY_WS_CAPABILITIES_SIGNAL; + + /// 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 + /// written short somewhere else, so they are held against each other here. + #[test] + fn test_the_reserved_signals_agree_with_what_the_encoder_builds() { + assert_eq!( + CELERITY_WS_ACK_SIGNAL.to_vec(), + encode_reserved_message(ReservedRoute::Ack, &[]) + ); + assert_eq!( + CELERITY_WS_CAPABILITIES_SIGNAL.to_vec(), + encode_reserved_message(ReservedRoute::Capabilities, &[]) + ); + } #[test] fn test_detect_client_ack_reads_both_encodings() { diff --git a/libs/runtime/helpers/src/websockets.rs b/libs/runtime/helpers/src/websockets.rs index 7cde1485..1010b8f2 100644 --- a/libs/runtime/helpers/src/websockets.rs +++ b/libs/runtime/helpers/src/websockets.rs @@ -20,6 +20,33 @@ pub enum BinaryRoute { Custom(String), } +/// The routes the protocol keeps for itself. +/// +/// An application's route is a name; these are a single byte, which is what +/// makes them reserved rather than reachable. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ReservedRoute { + Ping = 0x1, + Pong = 0x2, + LostMessage = 0x3, + Ack = 0x4, + Capabilities = 0x5, +} + +/// Frames one of the protocol's own messages. +/// +/// Not a different format from an application's message, the same one with a +/// route that is a single byte, asking for no acknowledgement and carrying no +/// id of its own. Writing that header out by hand at each place one of these is +/// built is how it came to be written with two bytes in one of them, leaving a +/// message no client could recognise. +pub fn encode_reserved_message(route: ReservedRoute, payload: &[u8]) -> Vec { + let mut framed = Vec::with_capacity(4 + payload.len()); + framed.extend_from_slice(&[0x1, route as u8, 0x0, 0x0]); + framed.extend_from_slice(payload); + framed +} + /// The error type for parsing a binary message. #[derive(Debug, PartialEq)] pub enum BinaryMessageParseError { @@ -571,6 +598,43 @@ mod tests { )); } + /// A reserved message is read back as the route it names, with the payload + /// whole. The parser is the client's side of this, so a round trip is what + /// says the two agree. + #[test] + fn test_encode_reserved_message_round_trips_through_the_parser() { + let framed = encode_reserved_message(ReservedRoute::LostMessage, br#"{"messageId":"m-1"}"#); + + assert_eq!( + parse_binary_message(&framed).unwrap(), + BinaryMessageData { + route: BinaryRoute::Reserved(0x3), + message_id: None, + require_ack: false, + message: br#"{"messageId":"m-1"}"#.to_vec(), + } + ); + } + + /// The header is four bytes, not two. A short one is not a shorter version + /// of the message, it is one no client can recognise, which is what a + /// hand written header here produced before. + #[test] + fn test_encode_reserved_message_writes_the_whole_header() { + assert_eq!( + encode_reserved_message(ReservedRoute::Pong, &[]), + vec![0x1, 0x2, 0x0, 0x0] + ); + assert_eq!( + encode_reserved_message(ReservedRoute::Capabilities, &[]), + vec![0x1, 0x5, 0x0, 0x0] + ); + assert_eq!( + encode_reserved_message(ReservedRoute::Ack, &[0xff]), + vec![0x1, 0x4, 0x0, 0x0, 0xff] + ); + } + /// Asking for an acknowledgement with no id is refused rather than framed /// and ignored, since the sender would wait for an answer that has nothing /// to name. diff --git a/libs/runtime/ws/ws-registry/src/message_helpers.rs b/libs/runtime/ws/ws-registry/src/message_helpers.rs index ec354fbe..36b6fae4 100644 --- a/libs/runtime/ws/ws-registry/src/message_helpers.rs +++ b/libs/runtime/ws/ws-registry/src/message_helpers.rs @@ -1,6 +1,6 @@ use axum::extract::ws::Message; use base64::{prelude::BASE64_STANDARD, Engine}; -use celerity_helpers::websockets::parse_binary_message; +use celerity_helpers::websockets::{encode_reserved_message, parse_binary_message, ReservedRoute}; use serde_json::{json, Value}; use crate::{errors::WebSocketConnError, types::MessageType}; @@ -17,17 +17,8 @@ pub fn create_message_lost_event(message_id: String, caller: Option) -> "caller": caller.unwrap_or_default(), }) .to_string(); - let payload_bytes = payload.as_bytes(); - - // `[routeLength][route][requireAck][messageIdLength]` then the payload. A - // reserved message needs no acknowledgement of its own and carries no - // message id of its own, which is what the two zero bytes say. Clients match - // on all four, so a short header is not a shorter version of this message, - // it is one they cannot recognise at all. - let mut message = Vec::with_capacity(payload_bytes.len() + 4); - message.extend_from_slice(&[0x1, 0x3, 0x0, 0x0]); - message.extend_from_slice(payload_bytes); - message + + encode_reserved_message(ReservedRoute::LostMessage, payload.as_bytes()) } /// Converts a message type and message received by a WebSocket registry From 766ba557dddc1928364bc4bd4c5fd6d22d13fe13 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 18:37:25 +0100 Subject: [PATCH 08/10] fix(lib-rt-helpers): refuse a binary message whose route has no length A route length of zero passed the length check, left an empty slice once the route was taken from it, and then that slice was indexed, which took the process down rather than reporting a message it could not read. The parser has been able to do this for as long as it has existed, but nothing reached it with those bytes. Reading every binary message on its way out to a client changed that, so any payload beginning with a zero byte was enough, which made the check meant to turn silent corruption into a clear error into something worse for that one input. The capabilities signal was also being read as an application's route rather than one of the protocol's own, since the parser recognised reserved routes by comparing against a bound that stopped one short of it. An application could therefore compose a route that would arrive looking like that signal. Both the parser and the encoder now ask the same question of a route byte instead of each comparing against a bound of its own, so a byte one of them treats as reserved cannot be a byte the other hands out. A test walks every reserved route rather than a chosen one, which is what would have caught the capabilities byte being left out, since the test that existed happened to pick a route on the covered side of the bound. --- libs/runtime/helpers/src/websockets.rs | 98 ++++++++++++++++++- .../ws/ws-registry/src/message_helpers.rs | 17 ++++ 2 files changed, 112 insertions(+), 3 deletions(-) diff --git a/libs/runtime/helpers/src/websockets.rs b/libs/runtime/helpers/src/websockets.rs index 1010b8f2..7f308ce6 100644 --- a/libs/runtime/helpers/src/websockets.rs +++ b/libs/runtime/helpers/src/websockets.rs @@ -33,6 +33,23 @@ pub enum ReservedRoute { Capabilities = 0x5, } +impl ReservedRoute { + /// Reads a route byte as one of the protocol's own, if it is one. + /// + /// The used by the parser and encoder for a single source of truth on + /// reserved routes. + pub fn from_byte(byte: u8) -> Option { + match byte { + 0x1 => Some(ReservedRoute::Ping), + 0x2 => Some(ReservedRoute::Pong), + 0x3 => Some(ReservedRoute::LostMessage), + 0x4 => Some(ReservedRoute::Ack), + 0x5 => Some(ReservedRoute::Capabilities), + _ => None, + } + } +} + /// Frames one of the protocol's own messages. /// /// Not a different format from an application's message, the same one with a @@ -69,6 +86,13 @@ pub fn parse_binary_message( } let route_length = msg_bytes[0]; + if route_length == 0 { + return Err(BinaryMessageParseError::Malformed( + "a message must name the route it is for, and this one has a route \ + of no length" + .to_string(), + )); + } if route_length as usize + 1 > msg_bytes.len() { return Err(BinaryMessageParseError::Malformed( "route length exceeds message length".to_string(), @@ -76,8 +100,7 @@ pub fn parse_binary_message( } let route_bytes = &msg_bytes[1..=route_length as usize]; - let route = if route_bytes[0] <= 0x4 { - // Reserved routes are single byte values from 0x0 to 0x4. + let route = if ReservedRoute::from_byte(route_bytes[0]).is_some() { BinaryRoute::Reserved(route_bytes[0]) } else { // Custom routes are utf-8 strings. @@ -181,7 +204,7 @@ pub fn encode_binary_message( // A route is read as reserved when its first byte is one of the reserved // values, so a custom route starting with one would come back as a ping or // an acknowledgement rather than as itself. - if route_bytes[0] <= 0x4 { + if ReservedRoute::from_byte(route_bytes[0]).is_some() { return Err(BinaryMessageEncodeError::Invalid(format!( "a route can not begin with the byte {:#x}, which is reserved", route_bytes[0] @@ -635,6 +658,75 @@ mod tests { ); } + /// A route of no length left an empty slice that was then indexed, which + /// took the process down rather than reporting a malformed message. Every + /// binary message sent to a client is read by this on its way out, so a + /// payload beginning with a zero byte was enough to do it. + #[test] + fn test_parse_binary_message_refuses_a_route_of_no_length() { + let result = parse_binary_message(&[0x00, 0x01, 0x02, 0x03]); + + assert!( + matches!(result, Err(BinaryMessageParseError::Malformed(_))), + "a route of no length should be refused, got {result:?}" + ); + } + + /// The capabilities signal is one of the protocol's own routes, so it has + /// to be read back as one. Read as a custom route it would be handed to an + /// application as a message on a route named by a control byte. + #[test] + fn test_the_capabilities_signal_round_trips_as_a_reserved_route() { + let framed = encode_reserved_message(ReservedRoute::Capabilities, &[]); + + assert_eq!( + parse_binary_message(&framed).unwrap(), + BinaryMessageData { + route: BinaryRoute::Reserved(0x5), + message_id: None, + require_ack: false, + message: Vec::new(), + } + ); + } + + /// Every reserved route, so none of them can be left out of the parser's + /// reckoning the way the capabilities one was. + #[test] + fn test_every_reserved_route_round_trips_as_reserved() { + for route in [ + ReservedRoute::Ping, + ReservedRoute::Pong, + ReservedRoute::LostMessage, + ReservedRoute::Ack, + ReservedRoute::Capabilities, + ] { + let framed = encode_reserved_message(route, &[]); + let parsed = parse_binary_message(&framed).unwrap(); + + assert_eq!( + parsed.route, + BinaryRoute::Reserved(route as u8), + "{route:?} should be read back as the reserved route it is" + ); + } + } + + /// An application must not be able to compose a route that would be read as + /// the capabilities signal, for the same reason as the other reserved ones. + #[test] + fn test_encode_binary_message_refuses_a_route_beginning_with_the_capabilities_byte() { + assert!(matches!( + encode_binary_message(BinaryMessageParts { + route: "\u{5}route", + message_id: None, + require_ack: false, + message: &[], + }), + Err(BinaryMessageEncodeError::Invalid(_)) + )); + } + /// Asking for an acknowledgement with no id is refused rather than framed /// and ignored, since the sender would wait for an answer that has nothing /// to name. diff --git a/libs/runtime/ws/ws-registry/src/message_helpers.rs b/libs/runtime/ws/ws-registry/src/message_helpers.rs index 36b6fae4..717cbdfa 100644 --- a/libs/runtime/ws/ws-registry/src/message_helpers.rs +++ b/libs/runtime/ws/ws-registry/src/message_helpers.rs @@ -114,6 +114,23 @@ mod tests { ); } + /// A payload starting with a zero byte used to take the process down here, + /// since the parser read it as a route of no length and then indexed the + /// empty slice that left. Every binary message passes through this on its + /// way out, so that was reachable from any application. + #[test] + fn test_create_ws_message_refuses_binary_with_a_route_of_no_length() { + let result = create_ws_message( + MessageType::Binary, + BASE64_STANDARD.encode([0x00, 0x01, 0x02, 0x03]), + ); + + assert!( + matches!(result, Err(WebSocketConnError::MalformedBinaryMessage(_))), + "a route of no length should be refused rather than panic, got {result:?}" + ); + } + #[test] fn test_create_ws_message_passes_a_framed_binary_message_through_untouched() { let framed = frame(b"price.tick", 0x1, b"m-1", &[0xde, 0xad]); From c5c06466b166c4d1a2ce739b8da9534d925548e8 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 18:37:39 +0100 Subject: [PATCH 09/10] docs(runtime-libs): describe the helpers crate rather than the workflow one The helpers readme was a copy of the workflow one, down to the title, so it announced a HTTP server for the workflow engine, executable workflows and an API for registering handlers, none of which are in it. It now describes what is, leading with the WebSocket message format, since a parser and an encoder that disagree produce messages nobody receives and that is the reason they live in a shared crate rather than in the crates that use them. The substitutions heading in the workflow readme was a level too deep, sitting under the title as though it belonged to something above it. --- libs/runtime/helpers/README.md | 21 +++++++++++---------- libs/runtime/workflow/README.md | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/libs/runtime/helpers/README.md b/libs/runtime/helpers/README.md index 4fb82f5c..b12011e9 100644 --- a/libs/runtime/helpers/README.md +++ b/libs/runtime/helpers/README.md @@ -1,16 +1,17 @@ -# celerity runtime workflow +# celerity runtime helpers -This package provides the workflow engine components designed to be used in the Celerity workflow runtime. -This crate provides a HTTP server application for the workflow engine that implements the specification defined in the [Celerity Workflow Specification](https://celerityframework.io/docs/framework/applications/resources/celerity-workflow). -This package creates an executable workflow from a blueprint file and a set of handlers. -This also provides an API for the registration of handlers. +This crate holds the pieces more than one Celerity runtime component needs, so +that they are written once and agree with each other. -### About `${..}` Substitutions +The most prominent of these being the WebSocket message format, where a parser and an encoder +sit together. A message read differently from the way it was written is a +message nobody receives, so the two belong side by side rather than in the +crates that happen to use them. -The runtime supports a limited version of `${..}` [substitutions](https://bluelink.dev/docs/bluelink/blueprints/specification#references--substitutions). -Only `${variables.[name]}` substitutions are recognised, all other substitutions are treated as string literals. - -In the runtime, the parser will replace `${variables.[name]}` with an environment variable of the form `CELERITY_VARIABLE_[name]`, these environment variables are expected to be set at package/build time by a tool like the Celerity Deploy Engine used in the Celerity CLI. +The rest is the ordinary shared ground of a runtime: reading configuration from +the environment, request and response helpers, telemetry setup for tracing and +metrics, retry and backoff, time, JSONPath, and the client pieces for consumers +and Redis. ## Additional documentation diff --git a/libs/runtime/workflow/README.md b/libs/runtime/workflow/README.md index c8347fe1..04d8432f 100644 --- a/libs/runtime/workflow/README.md +++ b/libs/runtime/workflow/README.md @@ -7,7 +7,7 @@ This crate provides a HTTP server application for the workflow engine that imple This package creates an executable workflow from a blueprint file and a set of handlers. This also provides an API for the registration of handlers. -### About `${..}` Substitutions +## About `${..}` Substitutions The runtime supports a limited version of `${..}` [substitutions](https://bluelink.dev/docs/bluelink/blueprints/specification#references--substitutions). Only `${variables.[name]}` substitutions are recognised, all other substitutions are treated as string literals. From b753d58c9e3ac23f80a321eba5a8c532ec10d1a0 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 17 Aug 2026 18:37:53 +0100 Subject: [PATCH 10/10] test(lib-rt-sdk-node): let go of a listener when waiting for a message times out Waiting for a message attached a listener and detached it again on the way out, but only when a message arrived. A socket that went quiet kept the listener, and whatever it had captured, for as long as the socket lived. The comment on the capabilities signal now says what the four bytes are. The leading one is the length of the route rather than a version, which is the reading that makes the byte after it the route the protocol reserves for the signal rather than a number that happens to follow. --- .../sdk/node/__test__/websocket.spec.ts | 57 ++++++++++--------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/libs/runtime/sdk/node/__test__/websocket.spec.ts b/libs/runtime/sdk/node/__test__/websocket.spec.ts index 54e21948..93bb4ed1 100644 --- a/libs/runtime/sdk/node/__test__/websocket.spec.ts +++ b/libs/runtime/sdk/node/__test__/websocket.spec.ts @@ -57,17 +57,11 @@ function openWs(url: string): Promise { /** The capabilities signal, which arrives on its own the moment a connection * opens and is not a message any test is waiting for. */ function isCapabilitiesSignal(data: Buffer, isBinary: boolean): boolean { - return ( - isBinary && data.length === 4 && data[0] === 0x01 && data[1] === 0x05 - ); + return isBinary && data.length === 4 && data[0] === 0x01 && data[1] === 0x05; } function nextWsMessage(ws: WebSocket, timeoutMs = 5000): Promise { return new Promise((resolve, reject) => { - const timer = setTimeout( - () => reject(new Error("timeout waiting for WS message")), - timeoutMs, - ); // Passed over rather than taken as the first message. Whether the signal // lands before or after a listener is attached comes down to timing. const onMessage = (data: Buffer, isBinary: boolean) => { @@ -78,6 +72,13 @@ function nextWsMessage(ws: WebSocket, timeoutMs = 5000): Promise { clearTimeout(timer); resolve(data.toString()); }; + // Detached on the way out as well as on the way in, or a socket that goes + // quiet keeps the listener, and whatever it captured, for as long as it + // lives. + const timer = setTimeout(() => { + ws.off("message", onMessage); + reject(new Error("timeout waiting for WS message")); + }, timeoutMs); ws.on("message", onMessage); }); } @@ -124,7 +125,7 @@ test("WS connect triggers $connect handler", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -162,7 +163,6 @@ test("WS JSON message routes to echo handler", async (t) => { const app = new CoreRuntimeApplication(testConfig({ serverPort })); const config = app.setup(); - const echoReceived = deferred(); for (const handler of config.api?.websocket?.handlers ?? []) { @@ -176,7 +176,7 @@ test("WS JSON message routes to echo handler", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -219,7 +219,6 @@ test("WS $default route handles unmatched action", async (t) => { const app = new CoreRuntimeApplication(testConfig({ serverPort })); const config = app.setup(); - const defaultReceived = deferred(); for (const handler of config.api?.websocket?.handlers ?? []) { @@ -233,7 +232,7 @@ test("WS $default route handles unmatched action", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -274,7 +273,6 @@ test("WS disconnect triggers $disconnect handler", async (t) => { const app = new CoreRuntimeApplication(testConfig({ serverPort })); const config = app.setup(); - const disconnectReceived = deferred(); for (const handler of config.api?.websocket?.handlers ?? []) { @@ -288,7 +286,7 @@ test("WS disconnect triggers $disconnect handler", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -324,7 +322,6 @@ test("websocketRegistry sendMessage sends to connected client", async (t) => { const app = new CoreRuntimeApplication(testConfig({ serverPort })); const config = app.setup(); - const registry = app.websocketRegistry(); let capturedConnectionId = ""; const connectDone = deferred(); @@ -356,7 +353,7 @@ test("websocketRegistry sendMessage sends to connected client", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -402,7 +399,6 @@ test("WS request context includes connection metadata", async (t) => { const app = new CoreRuntimeApplication(testConfig({ serverPort })); const config = app.setup(); - const connectReceived = deferred(); for (const handler of config.api?.websocket?.handlers ?? []) { @@ -416,7 +412,7 @@ test("WS request context includes connection metadata", async (t) => { ); break; default: - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); break; } } @@ -425,7 +421,10 @@ test("WS request context includes connection metadata", async (t) => { try { const ws = new WebSocket(`ws://localhost:${serverPort}/ws?token=abc123`, { - headers: { "x-custom-header": "test-value", origin: "https://example.com" }, + headers: { + "x-custom-header": "test-value", + origin: "https://example.com", + }, }); await new Promise((resolve, reject) => { @@ -471,10 +470,7 @@ test("encodeBinaryMessage lays out the Celerity Binary Message Format", (t) => { ); // [routeLength][route][requireAck][messageIdLength][messageId][message] - t.deepEqual( - [...framed], - [0x02, 0x75, 0x70, 0x00, 0x02, 0x69, 0x64, 0xff], - ); + t.deepEqual([...framed], [0x02, 0x75, 0x70, 0x00, 0x02, 0x69, 0x64, 0xff]); }); test("encodeBinaryMessage refuses what it cannot represent", (t) => { @@ -485,7 +481,10 @@ test("encodeBinaryMessage refuses what it cannot represent", (t) => { // A route longer than the single byte that measures it. t.throws(() => - encodeBinaryMessage({ route: "r".repeat(256), message: Buffer.from([0x01]) }), + encodeBinaryMessage({ + route: "r".repeat(256), + message: Buffer.from([0x01]), + }), ); // Asking to be acknowledged with no id for the acknowledgement to name. @@ -542,7 +541,7 @@ test("a framed binary message reaches the client exactly as composed", async (t) }, ); } else { - app.registerWebsocketHandler(handler.route, async (_err, _msg) => { }); + app.registerWebsocketHandler(handler.route, async (_err, _msg) => {}); } } @@ -565,7 +564,8 @@ test("a framed binary message reaches the client exactly as composed", async (t) ws.send(JSON.stringify({ action: "echo", data: "ping" })); const timer = setTimeout( - () => received.reject(new Error("timeout waiting for the binary frame")), + () => + received.reject(new Error("timeout waiting for the binary frame")), 5000, ); const frame = await received.promise; @@ -574,7 +574,10 @@ test("a framed binary message reaches the client exactly as composed", async (t) t.truthy(refusedUnframed, "unframed bytes should have been refused"); t.deepEqual([...frame], [...Buffer.from(framed, "base64")]); // The payload survives with the framing in front of it, untouched. - t.deepEqual([...frame.subarray(frame.length - payload.length)], [...payload]); + t.deepEqual( + [...frame.subarray(frame.length - payload.length)], + [...payload], + ); } finally { ws.close(); }