Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions libs/runtime/core/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ impl Application {
));
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();

// 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
// runtime registers one per blueprint handler, so that messages
Expand Down
92 changes: 92 additions & 0 deletions libs/runtime/core/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,23 @@ async fn handle_socket(
}
}
} else {
// A client acknowledging something the runtime sent it,
// taken before routing so it is not mistaken for a routed
// message and handed to the default handler.
//
// Only from a connection that has authenticated, since an
// acknowledgement calls off a resend and the loss event
// that follows it, and that is not something an unproven
// client should be able to do to a message.
if let Some(acknowledged) = detect_client_ack(&msg) {
debug!("client {connection_id} acknowledged message {acknowledged}");
state
.connections
.record_client_ack(connection_id.clone(), acknowledged)
.await;
continue;
}

// Handed to the worker rather than run here. A handler that
// takes a while must not stop this loop reading, or the
// heartbeat above goes unanswered and a close frame goes
Expand Down Expand Up @@ -1264,6 +1281,42 @@ enum AckFormat {
Binary,
}

/// Recognises a client acknowledging something the runtime sent it, returning
/// the id of the message being acknowledged.
///
/// Reads both encodings, the reserved `0x4` binary frame and the JSON form
/// carrying `ack` as the value of `event`. That key is fixed by the protocol
/// rather than being the API's configured route key, which is what makes these
/// messages unroutable and why they have to be recognised here.
fn detect_client_ack(msg: &Message) -> Option<String> {
let body = match msg {
Message::Binary(bytes) => {
if !bytes.starts_with(&CELERITY_WS_ACK_SIGNAL) {
return None;
}
let value: Value = serde_json::from_slice(bytes.get(4..)?).ok()?;
value
}
Message::Text(text) => {
// A reserved acknowledgement always names itself, so anything that
// does not mention it is passed over before it is parsed.
if !text.contains("\"ack\"") {
return None;
}
let value: Value = serde_json::from_str(text).ok()?;
if value.get("event").and_then(Value::as_str) != Some("ack") {
return None;
}
value.get("data")?.clone()
}
_ => return None,
};

body.get("messageId")
.and_then(Value::as_str)
.map(str::to_string)
}

/// Whether a JSON text carries `ack` as an object key.
///
/// A prefilter, not a parser. It is allowed to say yes to a message that turns
Expand All @@ -1275,6 +1328,13 @@ fn has_ack_key(text: &str) -> bool {
.any(|(index, matched)| text[index + matched.len()..].trim_start().starts_with(':'))
}

/// Recognises a message asking to be acknowledged, returning the id to
/// acknowledge it by and the encoding to answer in.
///
/// Read off the frame rather than out of the routing, so a message can be
/// answered as soon as it is taken in. Asking without a message id returns
/// nothing, since an acknowledgement names the message it is for and there
/// would be nothing to name.
fn ack_request(msg: &Message) -> Option<(String, AckFormat)> {
match msg {
Message::Text(text) => {
Expand Down Expand Up @@ -1594,6 +1654,38 @@ async fn close_with_retry_after(socket_ref: Arc<Mutex<WebSocketConnSender>>, ret
mod tests {
use super::*;

#[test]
fn test_detect_client_ack_reads_both_encodings() {
let mut frame = CELERITY_WS_ACK_SIGNAL.to_vec();
frame.extend_from_slice(br#"{"messageId":"m-1","timestamp":"1"}"#);
assert_eq!(
detect_client_ack(&Message::Binary(frame.into())),
Some("m-1".to_string())
);

let text = r#"{"event":"ack","data":{"messageId":"m-2","timestamp":"1"}}"#;
assert_eq!(
detect_client_ack(&Message::Text(text.into())),
Some("m-2".to_string())
);
}

#[test]
fn test_detect_client_ack_leaves_application_messages_alone() {
// Carries the word but is an ordinary message, and the runtime must not
// swallow it on the way to its handler.
let text = r#"{"event":"sendMessage","data":{"kind":"ack"}}"#;
assert!(detect_client_ack(&Message::Text(text.into())).is_none());

// An acknowledgement request, which travels the other way.
let text = r#"{"event":"sendMessage","ack":true,"messageId":"m-3"}"#;
assert!(detect_client_ack(&Message::Text(text.into())).is_none());

// A binary application message whose route happens to be one byte.
let frame = vec![0x1, 0x9, 0x0, 0x0, 0xff];
assert!(detect_client_ack(&Message::Binary(frame.into())).is_none());
}

#[test]
fn test_has_ack_key_ignores_ack_as_a_value() {
// Reserved as an event value by the protocol itself, so a message
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
version: 2025-11-02
transform: celerity-2026-02-28
variables:
logLevel:
type: string
description: "The log level to use for logging."
default: "INFO"
allowedValues:
- "DEBUG"
- "INFO"
- "WARNING"
- "ERROR"

resources:
ordersWebSocketApi:
type: "celerity/api"
description: "A WebSocket API with a custom route key and a default handler, where anything the runtime does not take out of the way reaches the application."
metadata:
displayName: Orders WebSocket API
linkSelector:
byLabel:
application: "orders"
spec:
protocols:
- websocketConfig:
# Deliberately not the default. A reserved message names its route
# with `event`, so against a different route key it carries no route
# the runtime recognises and falls through to the default handler.
routeKey: "action"
tracingEnabled: false

sendMessageHandler:
type: "celerity/handler"
metadata:
displayName: Send Message Handler
labels:
application: "orders"
annotations:
celerity.handler.websocket: true
celerity.handler.websocket.route: "sendMessage"
spec:
handlerName: Orders-SendMessageHandler-v1
codeLocation: "./orders"
handler: "handlers.send_message"
runtime: "python3.12.x"
memory: 1024
timeout: 10
tracingEnabled: false
environmentVariables:
LOG_LEVEL: "${variables.logLevel}"

defaultHandler:
type: "celerity/handler"
metadata:
displayName: Default Handler
labels:
application: "orders"
annotations:
celerity.handler.websocket: true
celerity.handler.websocket.route: "$default"
spec:
handlerName: Orders-DefaultHandler-v1
codeLocation: "./orders"
handler: "handlers.default"
runtime: "python3.12.x"
memory: 1024
timeout: 10
tracingEnabled: false
environmentVariables:
LOG_LEVEL: "${variables.logLevel}"
113 changes: 113 additions & 0 deletions libs/runtime/core/tests/ipc_end_to_end_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,60 @@ async fn tells_an_unauthenticated_client_to_authenticate_first() {
let _ = tokio::fs::remove_file(&socket).await;
}

/// An acknowledgement is a message like any other until the client has proved
/// who it is.
///
/// Acknowledgements are taken out of the way before routing, and that used to
/// happen ahead of the authentication gate, so an unauthenticated client could
/// still settle a message and call off the resend and loss event that follow
/// it. The refusal below is the gate doing its job.
#[test_log::test(tokio::test)]
async fn refuses_an_acknowledgement_from_a_client_that_has_not_authenticated() {
let (_app, addr, socket) = start_runtime(
"ipc-ws-auth-message-ack",
"tests/data/fixtures/ipc-websocket-auth-message.blueprint.yaml",
)
.await;
let _handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await;

let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/"))
.await
.expect("the authMessage strategy should let the connection upgrade");

socket_conn
.send(tokio_tungstenite::tungstenite::Message::Text(
json!({
"event": "ack",
"data": { "messageId": "m-1", "timestamp": "2026-01-01T00:00:00.000Z" }
})
.to_string(),
))
.await
.unwrap();

let rejected = tokio::time::timeout(Duration::from_secs(5), async {
while let Some(Ok(message)) = socket_conn.next().await {
if let tokio_tungstenite::tungstenite::Message::Text(text) = message {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) {
if value["event"] == "error" {
return true;
}
}
}
}
false
})
.await;

assert_eq!(
rejected,
Ok(true),
"an acknowledgement before authentication should be refused rather than settle a message"
);

let _ = tokio::fs::remove_file(&socket).await;
}
Comment thread
fr3shw3b marked this conversation as resolved.
Resolved

#[test_log::test(tokio::test)]
async fn closes_a_connection_out_without_waiting_for_all_the_work_it_queued() {
let (_app, addr, socket) = start_runtime(
Expand Down Expand Up @@ -1569,6 +1623,65 @@ async fn acknowledges_a_message_queued_behind_a_handler_that_is_still_running()
let _ = tokio::fs::remove_file(&socket).await;
}

#[test_log::test(tokio::test)]
async fn does_not_route_a_client_acknowledgement_to_a_handler() {
let (_app, addr, socket) = start_runtime(
"ipc-ws-inbound-ack",
"tests/data/fixtures/ipc-websocket-default-route.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");

// What a client sends to acknowledge something the runtime sent it. A
// reserved message names its route with `event`, and this API routes on
// `action`, so left alone it carries no route the runtime knows and lands
// on the default handler as though the application had been sent it.
socket_conn
.send(tokio_tungstenite::tungstenite::Message::Text(
json!({
"event": "ack",
"data": { "messageId": "m-1", "timestamp": "1" },
})
.to_string(),
))
.await
.unwrap();
let mut binary = vec![0x1, 0x4, 0x0, 0x0];
binary.extend_from_slice(br#"{"messageId":"m-2","timestamp":"1"}"#);
socket_conn
.send(tokio_tungstenite::tungstenite::Message::Binary(binary))
.await
.unwrap();

// Sent last and expected first, since anything the runtime failed to take
// out of the way would have reached the handler ahead of it.
socket_conn
.send(tokio_tungstenite::tungstenite::Message::Text(
json!({ "action": "sendMessage", "data": { "text": "hello" } }).to_string(),
))
.await
.unwrap();

let dispatch = handler
.next_dispatch()
.await
.expect("the ordinary message should reach the handler");
let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else {
panic!("expected a WebSocket source");
};
let body: serde_json::Value = serde_json::from_slice(&message.message).unwrap();
assert_eq!(
body["data"]["text"], "hello",
"an acknowledgement reached the handler ahead of the message that followed it"
);

let _ = tokio::fs::remove_file(&socket).await;
}

#[test_log::test(tokio::test)]
async fn does_not_acknowledge_a_message_that_did_not_ask() {
let (_app, addr, socket) = start_runtime(
Expand Down
48 changes: 48 additions & 0 deletions libs/runtime/ws/ws-registry/src/acks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ pub enum MessageAction {

pub enum AckWorkerMessage {
Status(String, AckStatus),
ClientAck {
message_id: String,
connection_id: String,
},
Check(String, Sender<AckStatus>),
Wait(String, Sender<AckStatus>),
}
Expand Down Expand Up @@ -160,6 +164,12 @@ impl Worker {
Some(AckWorkerMessage::Status(message_id, ack_status)) => {
self.record_ack(message_id, ack_status).await;
}
Some(AckWorkerMessage::ClientAck {
message_id,
connection_id,
}) => {
self.record_client_ack(message_id, connection_id).await;
}
Comment thread
fr3shw3b marked this conversation as resolved.
Resolved
Some(AckWorkerMessage::Check(message_id, tx)) => {
let acks_guard = self.acks.lock().await;
let detailed_ack_status = acks_guard.get(&message_id).cloned();
Expand Down Expand Up @@ -221,6 +231,44 @@ impl Worker {

acks_guard.insert(message_id, new_detailed_ack_status);
}

/// Settles a message on the word of the client it was sent to.
///
/// An acknowledgement naming a message that is waiting on a different
/// connection is ignored, so one client cannot call off the delivery
/// guarantees another is relying on.
async fn record_client_ack(&mut self, message_id: String, connection_id: String) {
let mut acks_guard = self.acks.lock().await;
let Some(existing) = acks_guard.get_mut(&message_id) else {
debug!(
message_id = %message_id,
connection_id = %connection_id,
"a client acknowledged a message nothing is waiting on, ignoring it"
);
return;
};

let owed_by = match &existing.status {
AckStatus::Pending {
connection_id: pending_connection_id,
..
} => pending_connection_id,
// Already settled one way or the other, so there is nothing left to
// say about it.
_ => return,
};

if *owed_by != connection_id {
debug!(
message_id = %message_id,
connection_id = %connection_id,
"a client acknowledged a message owed by another connection, ignoring it"
);
return;
}

existing.status = AckStatus::Received;
}
}

async fn check_for_actions_periodic(
Expand Down
Loading
Loading