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/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/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/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/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/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs index eb42265b..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, @@ -86,12 +87,41 @@ 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. 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 { @@ -165,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 { @@ -173,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); @@ -197,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 @@ -1061,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( diff --git a/libs/runtime/helpers/README.md b/libs/runtime/helpers/README.md index 359836c2..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://www.celerityframework.io/docs/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://www.celerityframework.io/docs/blueprint/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/helpers/src/websockets.rs b/libs/runtime/helpers/src/websockets.rs index 6f1b0ccf..7f308ce6 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 { @@ -20,6 +20,50 @@ 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, +} + +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 +/// 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 { @@ -27,7 +71,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( @@ -42,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(), @@ -49,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. @@ -105,6 +155,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 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] + ))); + } + + 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 +506,240 @@ 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(_)) + )); + } + + /// 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] + ); + } + + /// 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. + #[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/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..93bb4ed1 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,32 @@ 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()); - }); + }; + // 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); }); } @@ -108,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; } } @@ -146,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 ?? []) { @@ -160,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; } } @@ -203,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 ?? []) { @@ -217,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; } } @@ -258,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 ?? []) { @@ -272,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; } } @@ -308,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(); @@ -340,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; } } @@ -386,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 ?? []) { @@ -400,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; } } @@ -409,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) => { @@ -438,3 +453,136 @@ 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 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) 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..04d8432f 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 +## 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/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..717cbdfa 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::{encode_reserved_message, parse_binary_message, ReservedRoute}; 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, @@ -16,31 +17,37 @@ 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 /// 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 +98,62 @@ 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:?}" + ); + } + + /// 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]); + + 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!(