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
14 changes: 14 additions & 0 deletions libs/runtime/core/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ use crate::{
types::ApiAppState,
utils::get_epoch_seconds,
websocket::{self, WebSocketMessageHandler},
websocket_dedupe::{InMemoryMessageIdStore, DEFAULT_MESSAGE_ID_TTL_MS},
};

/// Shutdown signal for a consumer — either oneshot (SQS) or broadcast (Redis).
Expand Down Expand Up @@ -122,6 +123,10 @@ pub struct Application {
// 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<Arc<WebSocketConnRegistry>>,
// Kept for `run` to start its sweep, for the same reason as the registry
// above. The store itself is built in setup, since building it spawns
// nothing.
ws_seen_messages: Option<Arc<InMemoryMessageIdStore>>,
ws_app_routes: Arc<AsyncMutex<HashMap<String, Arc<dyn WebSocketMessageHandler + Send + Sync>>>>,
custom_auth_guards: Arc<AsyncMutex<HashMap<String, Arc<dyn AuthGuardHandler + Send + Sync>>>>,
server_shutdown_signal: Option<tokio::sync::oneshot::Sender<()>>,
Expand Down Expand Up @@ -166,6 +171,7 @@ impl Application {
ipc_server_shutdown_signal: None,
ws_connections: None,
ws_conn_registry: None,
ws_seen_messages: None,
ws_app_routes: Arc::new(AsyncMutex::new(HashMap::new())),
custom_auth_guards: Arc::new(AsyncMutex::new(HashMap::new())),
resource_store: None,
Expand Down Expand Up @@ -350,6 +356,9 @@ impl Application {
// mean spawning, and this runs outside the async runtime when in FFI mode.
self.ws_conn_registry = Some(conn_registry.clone());

let seen_messages = Arc::new(InMemoryMessageIdStore::new(DEFAULT_MESSAGE_ID_TTL_MS));
self.ws_seen_messages = Some(seen_messages.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
// runtime registers one per blueprint handler, so that messages
Expand Down Expand Up @@ -382,6 +391,7 @@ impl Application {
websocket_base_path,
get(websocket::handler).with_state(websocket::WebSocketAppState {
connections: conn_registry,
seen_messages: seen_messages.clone(),
routes: self.ws_app_routes.clone(),
route_key: websocket_config.route_key.clone(),
api_auth: api_config.auth.clone(),
Expand Down Expand Up @@ -708,6 +718,10 @@ impl Application {
conn_registry.start_client_ack_worker();
}

if let Some(seen_messages) = self.ws_seen_messages.take() {
seen_messages.start_eviction();
}

self.run_ipc_stream_server().await?;

let mut server_task = None;
Expand Down
1 change: 1 addition & 0 deletions libs/runtime/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ pub mod types;
pub(crate) mod utils;
mod value_sources;
pub mod websocket;
pub mod websocket_dedupe;
43 changes: 43 additions & 0 deletions libs/runtime/core/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
time::{Duration, Instant},
};

use crate::websocket_dedupe::MessageIdStore;
use async_trait::async_trait;
use axum::{
extract::{
Expand Down Expand Up @@ -78,6 +79,9 @@
pub connection_auth_guards: HashMap<String, Arc<dyn AuthGuardHandler + Send + Sync>>,
pub cors: Option<CelerityApiCors>,
pub resource_store: Arc<ResourceStore>,
// What the node has already seen from its clients, so a message resent
// because an acknowledgement went missing is not acted on twice.
pub seen_messages: Arc<dyn MessageIdStore>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -1055,7 +1059,40 @@
Ok(serde_json::Value::Object(accumulated_claims))
}

/// Whether a message has already been acted on, so a resend of it is not acted
/// on again.
///
/// Only asked of a message the client gave an id to. An id the runtime made up
/// for one that carried none is unique by construction, so it would never match
/// anything, and remembering it would fill the store with entries nothing can
/// look up.
///
/// This runs after the acknowledgement has gone out, which is the order it has
/// to be in. A client resends because it did not hear one, and the thing that
/// went missing may have been the acknowledgement rather than the message.
/// Staying silent about a duplicate would leave it resending the message the
/// runtime is refusing to answer for.
async fn already_acted_on(
message_id: &Option<String>,
connection_id: &str,
state: &WebSocketAppState,
) -> bool {
let Some(message_id) = message_id else {
return false;
};

if state.seen_messages.record_and_check_seen(message_id).await {
debug!(
"client {connection_id} sent message {message_id} again, which has already been \
handled, so it is not handled a second time"
);
return true;
}

false
}

async fn process_message(

Check failure on line 1095 in libs/runtime/core/src/websocket.rs

View check run for this annotation

SonarQubeCloud / [Celerity Runtime Libs] SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 21 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_celerity-runtime-libs&issues=AaAQ_PPye9jGw-ClXW07&open=AaAQ_PPye9jGw-ClXW07&pullRequest=183
msg: Message,
connection_id: String,
request_ctx: WebSocketRequestContext,
Expand All @@ -1069,6 +1106,9 @@
state.route_key.clone(),
)?;
if let Some((route, message_id, _requires_ack, data)) = resolved {
if already_acted_on(&message_id, &connection_id, state).await {
return ControlFlow::Continue(());
}
if let Some(handler) = get_message_route_handler(&route, state).await {
handle_json_message(
handler.clone(),
Expand All @@ -1090,6 +1130,9 @@
Message::Binary(bytes) => {
let resolved = resolve_binary_route(&bytes, connection_id.clone())?;
if let Some((route, message_id, _requires_ack, bytes_stripped)) = resolved {
if already_acted_on(&message_id, &connection_id, state).await {
return ControlFlow::Continue(());
}
if let Some(handler) = get_message_route_handler(&route, state).await {
handle_binary_message(
handler.clone(),
Expand Down
153 changes: 153 additions & 0 deletions libs/runtime/core/src/websocket_dedupe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use std::{
collections::HashMap,
sync::{Arc, RwLock},
time::{Duration, Instant},
};

use async_trait::async_trait;
use tracing::debug;

/// How long a message id is remembered for, which is how far apart two copies
/// of a message can arrive and still be recognised as the same one.
pub const DEFAULT_MESSAGE_ID_TTL_MS: u64 = 300_000;

/// How often expired ids are cleaned up. Expiry is decided by the timestamp
/// rather than by the clean up, so this only bounds how long a dead entry keeps
/// its memory, not how long it counts as seen.
const EVICTION_INTERVAL_MS: u64 = 60_000;

/// Remembers the messages a client has already sent, so the same one is not
/// acted on twice.
///
/// A client resends when it does not receive an acknowledgement in time, and the
/// message that went missing may have been the acknowledgement rather than the
/// message. The second copy is a delivery the runtime already has.
#[async_trait]
pub trait MessageIdStore: Send + Sync + std::fmt::Debug {
/// Records a message id and says whether it was already there.
///
/// One call rather than a check and a write, so two copies of a message
/// arriving together cannot both find it absent and both be processed.
async fn record_and_check_seen(&self, message_id: &str) -> bool;
}

/// The store for a single node, which is every deployment that is not a
/// cluster.
///
/// A cluster needs a shared one, since a client that reconnects may land on a
/// different node and resend there, and what this node holds in-memory says nothing about
/// what another one has seen.
#[derive(Debug)]
pub struct InMemoryMessageIdStore {
seen: Arc<RwLock<HashMap<String, Instant>>>,
ttl: Duration,
}

impl InMemoryMessageIdStore {
pub fn new(ttl_ms: u64) -> Self {
Self {
seen: Arc::new(RwLock::new(HashMap::new())),
ttl: Duration::from_millis(ttl_ms),
}
}

/// Starts the sweep that keeps the store from growing without limit.
///
/// Spawns, so it must be called with a runtime running. Nothing depends on
/// it for correctness, since an entry past its time is treated as absent
/// whether or not it has been swept.
pub fn start_eviction(self: Arc<Self>) {
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_millis(EVICTION_INTERVAL_MS));
loop {
interval.tick().await;
self.evict_expired();
}
});
}

fn evict_expired(&self) {
let now = Instant::now();
let mut seen = match self.seen.write() {
Ok(seen) => seen,
Err(poisoned) => poisoned.into_inner(),
};
let before = seen.len();
seen.retain(|_, recorded_at| now.duration_since(*recorded_at) < self.ttl);
let removed = before - seen.len();
if removed > 0 {
debug!("swept {removed} expired message ids, {} remain", seen.len());
}
}
}

#[async_trait]
impl MessageIdStore for InMemoryMessageIdStore {
async fn record_and_check_seen(&self, message_id: &str) -> bool {
let now = Instant::now();
let mut seen = match self.seen.write() {
Ok(seen) => seen,
Err(poisoned) => poisoned.into_inner(),
};

match seen.insert(message_id.to_string(), now) {
// Past its time, so this is a new message that happens to reuse an
// id the store had not got around to sweeping.
Some(recorded_at) => now.duration_since(recorded_at) < self.ttl,
None => false,
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test_log::test(tokio::test)]
async fn test_a_message_is_new_the_first_time_and_seen_the_second() {
let store = InMemoryMessageIdStore::new(DEFAULT_MESSAGE_ID_TTL_MS);

assert!(!store.record_and_check_seen("m-1").await);
assert!(store.record_and_check_seen("m-1").await);
assert!(store.record_and_check_seen("m-1").await);
}

#[test_log::test(tokio::test)]
async fn test_messages_are_told_apart_by_their_id() {
let store = InMemoryMessageIdStore::new(DEFAULT_MESSAGE_ID_TTL_MS);

assert!(!store.record_and_check_seen("m-1").await);
assert!(!store.record_and_check_seen("m-2").await);
}

/// An id past its time is a new message again, which is what makes the
/// store bounded rather than a record of everything a client ever sent.
#[test_log::test(tokio::test)]
async fn test_an_id_is_forgotten_once_its_time_is_up() {
let store = InMemoryMessageIdStore::new(50);

assert!(!store.record_and_check_seen("m-1").await);
tokio::time::sleep(Duration::from_millis(80)).await;
assert!(
!store.record_and_check_seen("m-1").await,
"an id past its time should be treated as one that was never seen"
);
}

/// Expiry is decided by the entry's own timestamp, so it holds whether or
/// not the sweep has run.
#[test_log::test(tokio::test)]
async fn test_sweeping_removes_what_has_expired_and_keeps_what_has_not() {
let store = InMemoryMessageIdStore::new(50);

store.record_and_check_seen("old").await;
tokio::time::sleep(Duration::from_millis(80)).await;
store.record_and_check_seen("new").await;

store.evict_expired();

let seen = store.seen.read().unwrap();
assert!(!seen.contains_key("old"), "an expired id should be swept");
assert!(seen.contains_key("new"), "a live id should be kept");
}
}
Loading
Loading