diff --git a/apps/runtime/core/Cargo.lock b/apps/runtime/core/Cargo.lock index d76fe513..2ba67ed3 100644 --- a/apps/runtime/core/Cargo.lock +++ b/apps/runtime/core/Cargo.lock @@ -367,6 +367,7 @@ dependencies = [ "bytes", "celerity_blueprint_config_parser", "celerity_helpers", + "celerity_ws_redis", "celerity_ws_registry", "form_urlencoded", "futures", @@ -395,6 +396,23 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "celerity_ws_redis" +version = "0.1.0" +dependencies = [ + "async-trait", + "celerity_helpers", + "celerity_ws_registry", + "futures", + "jsonpath-rust", + "nanoid", + "redis", + "serde", + "serde_json", + "tokio", + "tracing", +] + [[package]] name = "celerity_ws_registry" version = "0.1.0" diff --git a/apps/runtime/core/Cargo.toml b/apps/runtime/core/Cargo.toml index baec06c1..5167fda0 100644 --- a/apps/runtime/core/Cargo.toml +++ b/apps/runtime/core/Cargo.toml @@ -23,6 +23,10 @@ tracing = "=0.1.44" [dependencies.celerity_runtime_core] path = "../../../libs/runtime/core" +# Shipped with the image so a deployment turns clustering on with environment +# variables rather than a rebuild. With no Redis deployment configured it stays +# a single node. +features = ["ws_clustering"] [dependencies.celerity_helpers] path = "../../../libs/runtime/helpers" diff --git a/apps/runtime/nodejs/Dockerfile.local b/apps/runtime/nodejs/Dockerfile.local index 799788ce..ced5fd63 100644 --- a/apps/runtime/nodejs/Dockerfile.local +++ b/apps/runtime/nodejs/Dockerfile.local @@ -56,7 +56,7 @@ COPY --from=runtime sdk/ ./sdk/ # Install napi-cli and build the native addon for this platform WORKDIR /build/sdk/node RUN npm install -RUN npx napi build --platform --features celerity_local_consumers +RUN npx napi build --platform --features celerity_local_consumers,ws_clustering # ----------------------------------------------------------------------------- # Stage 1b: Lightweight cache — only the final NAPI artifacts (~100 MB vs ~14 GB) diff --git a/libs/runtime/Cargo.lock b/libs/runtime/Cargo.lock index 68669e4c..e7ab49e6 100644 --- a/libs/runtime/Cargo.lock +++ b/libs/runtime/Cargo.lock @@ -1237,6 +1237,7 @@ dependencies = [ "celerity_consumer_redis", "celerity_consumer_sqs", "celerity_helpers", + "celerity_ws_redis", "celerity_ws_registry", "chrono", "coverage-helper", @@ -1323,16 +1324,20 @@ name = "celerity_ws_redis" version = "0.1.0" dependencies = [ "async-trait", + "axum 0.8.8", "celerity_helpers", "celerity_ws_registry", "coverage-helper", + "futures", "jsonpath-rust", + "nanoid", "pretty_assertions", "redis", "serde", "serde_json", "test-log", "tokio", + "tokio-tungstenite 0.23.1", "tracing", ] diff --git a/libs/runtime/consumers/consumer-sqs/src/message_consumer.rs b/libs/runtime/consumers/consumer-sqs/src/message_consumer.rs index 07198428..53126e46 100644 --- a/libs/runtime/consumers/consumer-sqs/src/message_consumer.rs +++ b/libs/runtime/consumers/consumer-sqs/src/message_consumer.rs @@ -369,6 +369,11 @@ impl SQSMessageConsumer { } } + // The error is the SDK's own, and the lint's advice is to make it smaller, + // which is not ours to do. Boxing it here instead would change how every + // caller matches on it, to save a hundred and change bytes on the path + // where a network call has already failed. + #[allow(clippy::result_large_err)] async fn terminate_visibility_timeout(&self, messages: &[MessageHandle]) -> Result<(), Error> { if !self.config.terminate_visibility_timeout { debug!("sqs consumer not configured to terminate visibility timeout, moving on"); @@ -387,6 +392,8 @@ impl SQSMessageConsumer { Ok(()) } + // The error is the SDK's own, as above. + #[allow(clippy::result_large_err)] async fn delete_messages( &self, messages: &[MessageHandle], @@ -438,6 +445,11 @@ impl SQSMessageConsumer { } #[instrument(skip(self))] + // The error is the SDK's own, and the lint's advice is to make it smaller, + // which is not ours to do. Boxing it here instead would change how every + // caller matches on it, to save a hundred and change bytes on the path + // where a network call has already failed. + #[allow(clippy::result_large_err)] async fn receive_messages(&self) -> Result<(), SdkError> { let rcv_message_output = self .client diff --git a/libs/runtime/consumers/consumer-sqs/src/visibility_timeout.rs b/libs/runtime/consumers/consumer-sqs/src/visibility_timeout.rs index c1b260d9..4ab05f7f 100644 --- a/libs/runtime/consumers/consumer-sqs/src/visibility_timeout.rs +++ b/libs/runtime/consumers/consumer-sqs/src/visibility_timeout.rs @@ -82,6 +82,10 @@ impl VisibilityTimeoutExtender { } } + // The error is the SDK's own, and shrinking it is not ours to do. Boxing it + // would change how the caller matches on it, to save bytes on the path + // where a call to AWS has already failed. + #[allow(clippy::result_large_err)] pub async fn change_visibility_timeout( &self, messages: &[MessageHandle], diff --git a/libs/runtime/core/Cargo.toml b/libs/runtime/core/Cargo.toml index 9b4a977f..f8642044 100644 --- a/libs/runtime/core/Cargo.toml +++ b/libs/runtime/core/Cargo.toml @@ -78,6 +78,14 @@ optional = true [dependencies.celerity_ws_registry] path = "../ws/ws-registry" +[dependencies.celerity_ws_redis] +path = "../ws/ws-redis" +optional = true + +[dev-dependencies.celerity_helpers] +path = "../helpers" +features = ["test-support"] + [dev-dependencies] # tonic 0.14 builds on tower 0.5 while the crate itself still uses 0.4, so # the test connector needs the newer one under a name that cannot collide. @@ -108,3 +116,6 @@ gcloud_consumers = [ "dep:celerity_consumer_gcloud_tasks", ] celerity_local_consumers = ["dep:celerity_consumer_redis"] +# Lets a WebSocket API be deployed as more than one node. Compiling it in +# changes nothing until a Redis deployment is configured to cluster over. +ws_clustering = ["dep:celerity_ws_redis"] diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index 0fdc43b6..86a7722d 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -86,7 +86,7 @@ use crate::{ types::ApiAppState, utils::get_epoch_seconds, websocket::{self, WebSocketMessageHandler}, - websocket_dedupe::{InMemoryMessageIdStore, DEFAULT_MESSAGE_ID_TTL_MS}, + websocket_dedupe::{SeenMessages, DEFAULT_MESSAGE_ID_TTL_MS}, }; /// Shutdown signal for a consumer — either oneshot (SQS) or broadcast (Redis). @@ -131,13 +131,21 @@ pub struct Application { // 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>, + ws_seen_messages: Option>, ws_app_routes: Arc>>>, custom_auth_guards: Arc>>>, server_shutdown_signal: Option>, consumer_shutdown_signals: Option>>, resource_store: Option>, resource_store_cleanup_task_shutdown_signal: Option>, + #[cfg(feature = "ws_clustering")] + ws_cluster_shutdown_signal: Option>, + /// What this node is called among the others serving the same API. + /// + /// This is determined once and kept, because a name that had to be generated is a + /// different one every time it is worked out, and the registry and the + /// cluster have to agree on what this node is called. + server_node_name: String, http_auth_state: Option, api_cors: Option, handler_names: HashMap<(String, String), String>, @@ -156,9 +164,31 @@ pub struct Application { handler_invoke_registry: HandlerInvokeRegistry, } +/// Names this node among the others serving the same WebSocket API. +/// +/// Taken from the configuration, then the host name, which is the pod name on +/// Kubernetes and the container id under Docker, and finally a generated id so +/// that a node always has a name of its own. Two nodes sharing one would each +/// take the other's acknowledgements. +fn resolve_server_node_name(runtime_config: &RuntimeConfig, env_vars: &dyn EnvVars) -> String { + runtime_config + .server_node_name + .clone() + .or_else(|| { + env_vars + .var("HOSTNAME") + .ok() + .map(|hostname| hostname.trim().to_string()) + .filter(|hostname| !hostname.is_empty()) + }) + .unwrap_or_else(|| nanoid::nanoid!()) +} + impl Application { pub fn new(runtime_config: RuntimeConfig, env_vars: Box) -> Self { + let server_node_name = resolve_server_node_name(&runtime_config, env_vars.as_ref()); Application { + server_node_name, runtime_config, env_vars, app_tracing_enabled: false, @@ -182,6 +212,8 @@ impl Application { custom_auth_guards: Arc::new(AsyncMutex::new(HashMap::new())), resource_store: None, resource_store_cleanup_task_shutdown_signal: None, + #[cfg(feature = "ws_clustering")] + ws_cluster_shutdown_signal: None, http_auth_state: None, api_cors: None, handler_names: HashMap::new(), @@ -389,7 +421,7 @@ impl Application { message_timeout_ms: self.runtime_config.ws_ack_timeout_ms, max_attempts: self.runtime_config.ws_ack_max_attempts, }), - server_node_name: "node1".to_string(), + server_node_name: self.server_node_name.clone(), }, None, )); @@ -399,7 +431,7 @@ 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)); + let seen_messages = SeenMessages::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 @@ -719,6 +751,34 @@ impl Application { Ok(()) } + /// Joins this node to the others serving the same WebSocket API. + /// + /// Nothing here runs unless a Redis deployment is configured to cluster + /// over, so an application with the feature compiled in serves a single + /// node until it is told otherwise. + #[cfg(feature = "ws_clustering")] + async fn join_websocket_cluster(&mut self) -> Result<(), ApplicationStartError> { + let (Some(cluster_config), Some(registry)) = ( + self.runtime_config.ws_cluster.clone(), + self.ws_conn_registry.take(), + ) else { + return Ok(()); + }; + + self.ws_cluster_shutdown_signal = Some( + crate::websocket_cluster::join_cluster( + registry, + self.ws_seen_messages.take(), + cluster_config, + &self.runtime_config.service_name, + &self.server_node_name, + ) + .await?, + ); + + Ok(()) + } + pub async fn run(&mut self, block: bool) -> Result { // Tracing setup is in `run` instead of `setup` because // we need to be in an async context (tokio runtime) in order to set up tracing. @@ -740,14 +800,17 @@ impl Application { // 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() { + if let Some(conn_registry) = self.ws_conn_registry.clone() { conn_registry.start_client_ack_worker(); } - if let Some(seen_messages) = self.ws_seen_messages.take() { + if let Some(seen_messages) = self.ws_seen_messages.clone() { seen_messages.start_eviction(); } + #[cfg(feature = "ws_clustering")] + self.join_websocket_cluster().await?; + self.run_ipc_stream_server().await?; let mut server_task = None; @@ -1424,6 +1487,13 @@ impl Application { tx.send(()) .expect("failed to send shutdown signal to resource store cleanup task"); } + #[cfg(feature = "ws_clustering")] + if let Some(tx) = self.ws_cluster_shutdown_signal.take() { + // The heartbeat leaves the node group and takes this node's + // connection entries away when it sees this. + let _ = tx.send(()); + } + if let Some(consumer_shutdown_signals_lock) = self.consumer_shutdown_signals.take() { let mut consumer_shutdown_signals = consumer_shutdown_signals_lock .lock() @@ -1875,3 +1945,96 @@ async fn restrict_runtime_socket_dir(path: &std::path::Path) -> std::io::Result< tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::*; + + #[derive(Clone)] + struct MapEnv(HashMap<&'static str, String>); + + impl EnvVars for MapEnv { + fn var(&self, key: &str) -> Result { + self.0 + .get(key) + .cloned() + .ok_or(std::env::VarError::NotPresent) + } + + fn clone_env_vars(&self) -> Box { + Box::new(self.clone()) + } + } + + /// The smallest environment a runtime config will accept, plus whatever a + /// test is about. + fn env(overrides: &[(&'static str, &str)]) -> MapEnv { + let mut vars: HashMap<&'static str, String> = vec![ + ("CELERITY_BLUEPRINT", "blueprint.yaml".to_string()), + ("CELERITY_SERVICE_NAME", "test".to_string()), + ("CELERITY_SERVER_PORT", "8080".to_string()), + ("CELERITY_RUNTIME_PLATFORM", "local".to_string()), + ("CELERITY_RUNTIME_CALL_MODE", "ipc".to_string()), + ] + .into_iter() + .collect(); + for (key, value) in overrides { + vars.insert(key, value.to_string()); + } + MapEnv(vars) + } + + /// A node with nothing to take a name from is given a new one every time it + /// is asked, which is why the answer is settled once and kept. + /// + /// Working it out a second time would have the registry stamp one name on + /// the messages it sends while the cluster knows this node by another, and + /// an acknowledgement addressed to the first would be delivered to nobody. + #[test] + fn test_a_generated_node_name_is_a_different_one_every_time() { + let vars = env(&[]); + let config = RuntimeConfig::from_env(&vars); + + assert_ne!( + resolve_server_node_name(&config, &vars), + resolve_server_node_name(&config, &vars) + ); + } + + /// Whatever the name is worked out from, the application settles on one and + /// hands that same one to everything that needs it. + #[test] + fn test_an_application_keeps_the_name_it_settled_on() { + let vars = env(&[]); + let app = Application::new(RuntimeConfig::from_env(&vars), Box::new(vars.clone())); + + assert!(!app.server_node_name.is_empty()); + assert_ne!( + app.server_node_name, + resolve_server_node_name(&app.runtime_config, &vars), + "a name worked out again is not the one the application is known by" + ); + } + + /// A configured name is taken as it is, so nodes are named by whoever + /// deployed them rather than by chance. + #[test] + fn test_a_configured_node_name_is_the_one_the_application_takes() { + let vars = env(&[("CELERITY_SERVER_NODE_NAME", "node-a")]); + let app = Application::new(RuntimeConfig::from_env(&vars), Box::new(vars.clone())); + + assert_eq!(app.server_node_name, "node-a"); + } + + /// Falling back to the hostname names a node after the machine running it, + /// which is stable across everything that asks. + #[test] + fn test_a_node_falls_back_to_the_hostname_it_is_running_on() { + let vars = env(&[("HOSTNAME", "container-7")]); + let app = Application::new(RuntimeConfig::from_env(&vars), Box::new(vars.clone())); + + assert_eq!(app.server_node_name, "container-7"); + } +} diff --git a/libs/runtime/core/src/auth_http.rs b/libs/runtime/core/src/auth_http.rs index 390f21ef..af0a4d8c 100644 --- a/libs/runtime/core/src/auth_http.rs +++ b/libs/runtime/core/src/auth_http.rs @@ -144,6 +144,11 @@ fn token_source_needs_body(guard_config: &CelerityApiAuthGuard) -> bool { /// Buffers the request body as JSON, reconstructing the request for downstream handlers. /// Returns `Err` with a 413 response if the body exceeds `MAX_AUTH_BODY_BUFFER_SIZE`. +// +// Not boxed, unlike the guard chain below. What comes back on success is a +// request and its body, which is larger than the response, so moving the +// response to the heap would shrink nothing. +#[allow(clippy::result_large_err)] async fn buffer_request_body( request: axum::extract::Request, ) -> Result<(serde_json::Value, axum::extract::Request), Response> { @@ -255,7 +260,7 @@ pub async fn http_auth_middleware( request.extensions_mut().insert(auth_context); next.run(request).await } - Err(response) => response, + Err(response) => *response, } } @@ -265,7 +270,7 @@ async fn execute_guard_chain( guard_chain: &[String], state: &HttpAuthState, elements: &HttpAuthRequestElements, -) -> Result, Response> { +) -> Result, Box> { let mut accumulated_auth = serde_json::Map::new(); for guard_name in guard_chain { @@ -273,11 +278,13 @@ async fn execute_guard_chain( Some(config) => config, None => { warn!(guard = %guard_name, "auth guard referenced but not defined in API auth configuration"); - return Err(( - StatusCode::INTERNAL_SERVER_ERROR, - "Auth guard misconfigured", - ) - .into_response()); + return Err(Box::new( + ( + StatusCode::INTERNAL_SERVER_ERROR, + "Auth guard misconfigured", + ) + .into_response(), + )); } }; @@ -298,7 +305,7 @@ async fn validate_single_guard( state: &HttpAuthState, elements: &HttpAuthRequestElements, accumulated_auth: &serde_json::Map, -) -> Result { +) -> Result> { match guard_config.guard_type { CelerityApiAuthGuardType::Jwt => { crate::auth_jwt::validate_jwt_on_http_request( @@ -312,7 +319,7 @@ async fn validate_single_guard( .await .map_err(|e| { warn!(guard = %guard_name, request_id = %elements.request_id.0, client_ip = %elements.client_ip, "JWT auth failed: {e}"); - (StatusCode::UNAUTHORIZED, "Unauthorized").into_response() + Box::new((StatusCode::UNAUTHORIZED, "Unauthorized").into_response()) }) } CelerityApiAuthGuardType::Custom => { @@ -337,15 +344,17 @@ async fn validate_single_guard( elements.handler_name.clone(), ) .await - .map_err(|e| match e { - AuthGuardValidateError::Forbidden(_) => { - warn!(guard = %guard_name, request_id = %elements.request_id.0, client_ip = %elements.client_ip, "custom auth forbidden: {e}"); - (StatusCode::FORBIDDEN, "Forbidden").into_response() - } - _ => { - warn!(guard = %guard_name, request_id = %elements.request_id.0, client_ip = %elements.client_ip, "custom auth failed: {e}"); - (StatusCode::UNAUTHORIZED, "Unauthorized").into_response() - } + .map_err(|e| { + Box::new(match e { + AuthGuardValidateError::Forbidden(_) => { + warn!(guard = %guard_name, request_id = %elements.request_id.0, client_ip = %elements.client_ip, "custom auth forbidden: {e}"); + (StatusCode::FORBIDDEN, "Forbidden").into_response() + } + _ => { + warn!(guard = %guard_name, request_id = %elements.request_id.0, client_ip = %elements.client_ip, "custom auth failed: {e}"); + (StatusCode::UNAUTHORIZED, "Unauthorized").into_response() + } + }) }) } CelerityApiAuthGuardType::NoGuardType => Ok(serde_json::Value::Null), diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index 9e3809f3..92e90f95 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -202,6 +202,136 @@ pub struct RuntimeConfig { /// connection rather than the process. /// Set via `CELERITY_WS_HANDLER_CONCURRENCY`. pub ws_handler_concurrency: Option, + /// Names this node among the others serving the same WebSocket API. + /// + /// This must be different for every node, since it is what an acknowledgement + /// from another node is addressed to. Leave unset to take the host name, + /// which is the pod or container name on the deployment targets, and a + /// generated id where there is none. + /// Set via `CELERITY_SERVER_NODE_NAME`. + pub server_node_name: Option, + /// How the nodes of a WebSocket API find each other, or `None` for a + /// single node. + /// + /// A single node needs no shared store, because every connection it is + /// asked about is either its own or nowhere. + pub ws_cluster: Option, +} + +/// How a WebSocket API's nodes reach each other and how much they tell each +/// other. +/// +/// Debug is written out by hand rather than derived, so that a credential +/// cannot reach a log through anything that prints a config. +#[derive(Clone)] +pub struct WsClusterConfig { + /// The Redis deployment the nodes cluster over, as one URL or several for + /// a cluster. + /// Set via `CELERITY_WS_CLUSTER_REDIS_NODES`, comma separated. + pub redis_nodes: Vec, + /// Set via `CELERITY_WS_CLUSTER_REDIS_PASSWORD`. + pub redis_password: Option, + /// Whether a Redis cluster is to be connected to rather than a single instance. + /// Set via `CELERITY_WS_CLUSTER_REDIS_CLUSTER_MODE`. + pub redis_cluster_mode: bool, + /// What the keys and channels the nodes share are named under. + /// + /// Nodes sharing this are one cluster, so it must be the same across an + /// application's nodes and different between applications. Leave unset to + /// take the service name, which is both. + /// Set via `CELERITY_WS_CLUSTER_KEY_PREFIX`. + pub key_prefix: Option, + /// How many nodes a node group holds before a new one is started. + /// + /// Bounds how many nodes are told about a message for a connection none of + /// them may be holding. Leave unset to use the default of five as per the + /// protocol spec. + /// Set via `CELERITY_WS_CLUSTER_NODE_GROUP_CAPACITY`. + pub node_group_capacity: Option, + /// How long a node goes without announcing it is running before the others + /// treat it as gone. + /// + /// Announced three times inside this window, so two can be missed to a stall or + /// a slow round trip. Leave unset for thirty seconds. + /// Set via `CELERITY_WS_CLUSTER_NODE_TTL_MS`. + pub node_ttl_ms: Option, + /// How long a node keeps listening to the group it has left after moving to + /// another one. + /// + /// Covers a sender that read where a connection was just before it moved. + /// Leave unset for five seconds. + /// Set via `CELERITY_WS_CLUSTER_MIGRATION_GRACE_MS`. + pub migration_grace_ms: Option, + /// How long the cluster remembers that a message was forwarded to its + /// client, which is how far apart two copies can arrive and still be + /// recognised as one message. + /// + /// Must outlast a message's whole life as its sender sees it, which is the + /// acknowledgement timeout multiplied by the attempts allowed. Leave unset + /// for five minutes. + /// Set via `CELERITY_WS_CLUSTER_FORWARDED_TTL_MS`. + pub forwarded_ttl_ms: Option, + /// How long the cluster remembers a message it was sent by a client, so a + /// client that resends to another node is not acted on twice. + /// + /// Leave unset for five minutes. + /// Set via `CELERITY_WS_CLUSTER_SEEN_TTL_MS`. + pub seen_ttl_ms: Option, +} + +/// What stands in for a credential that has been kept out of a log. +const REDACTED: &str = ""; + +impl std::fmt::Debug for WsClusterConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WsClusterConfig") + .field( + "redis_nodes", + &self + .redis_nodes + .iter() + .map(|node| redact_url_credentials(node)) + .collect::>(), + ) + .field( + "redis_password", + &self.redis_password.as_ref().map(|_| REDACTED), + ) + .field("redis_cluster_mode", &self.redis_cluster_mode) + .field("key_prefix", &self.key_prefix) + .field("node_group_capacity", &self.node_group_capacity) + .field("node_ttl_ms", &self.node_ttl_ms) + .field("migration_grace_ms", &self.migration_grace_ms) + .field("forwarded_ttl_ms", &self.forwarded_ttl_ms) + .field("seen_ttl_ms", &self.seen_ttl_ms) + .finish() + } +} + +/// Takes the credentials out of a URL, leaving enough of it to tell one node +/// from another. +/// +/// A managed Redis deployment usually hands out its address with the password +/// already in it, so the address is as much a secret as the password field is. +fn redact_url_credentials(node: &str) -> String { + let Some(scheme_end) = node.find("://") else { + return node.to_string(); + }; + let authority_start = scheme_end + "://".len(); + // Only the authority, since a later part of the URL is not a credential + // however much it looks like one. + let authority_end = node[authority_start..] + .find('/') + .map_or(node.len(), |offset| authority_start + offset); + let Some(offset) = node[authority_start..authority_end].rfind('@') else { + return node.to_string(); + }; + + format!( + "{}{REDACTED}{}", + &node[..authority_start], + &node[authority_start + offset..] + ) } impl RuntimeConfig { @@ -372,6 +502,8 @@ impl RuntimeConfig { let ws_ack_timeout_ms = ws_ack_timeout_ms_from_env(env); let ws_ack_max_attempts = ws_ack_max_attempts_from_env(env); let ws_handler_concurrency = ws_handler_concurrency_from_env(env); + let server_node_name = server_node_name_from_env(env); + let ws_cluster = ws_cluster_from_env(env); RuntimeConfig { blueprint_config_path, @@ -403,6 +535,8 @@ impl RuntimeConfig { ws_ack_timeout_ms, ws_ack_max_attempts, ws_handler_concurrency, + server_node_name, + ws_cluster, } } @@ -425,6 +559,104 @@ impl RuntimeConfig { } } +/// Reads how the nodes of a WebSocket API reach each other, or `None` where no +/// Redis deployment is configured. +/// +/// Configuring a Redis deployment is what turns clustering on. Everything else +/// here refines a decision that has already been made, so it can all be left +/// unset. +/// +/// See [`ws_ack_timeout_ms_from_env`] for why this is not only read in +/// [`RuntimeConfig::from_env`]. +pub fn ws_cluster_from_env(env: &impl EnvVars) -> Option { + // A comma separated list, since a single instance is the usual case and a + // cluster is given as several. Empty entries are dropped, so a trailing + // comma is not a node called nothing. + let redis_nodes: Vec = env + .var("CELERITY_WS_CLUSTER_REDIS_NODES") + .ok()? + .split(',') + .map(str::trim) + .filter(|node| !node.is_empty()) + .map(str::to_string) + .collect(); + if redis_nodes.is_empty() { + return None; + } + + Some(WsClusterConfig { + redis_nodes, + redis_password: env.var("CELERITY_WS_CLUSTER_REDIS_PASSWORD").ok(), + redis_cluster_mode: env + .var("CELERITY_WS_CLUSTER_REDIS_CLUSTER_MODE") + .map(|val| { + val.parse().expect( + "Invalid WebSocket cluster mode value, must be either \"true\" or \"false\"", + ) + }) + .unwrap_or(false), + key_prefix: env.var("CELERITY_WS_CLUSTER_KEY_PREFIX").ok(), + node_group_capacity: env + .var("CELERITY_WS_CLUSTER_NODE_GROUP_CAPACITY") + .ok() + .map(|val| { + let capacity: usize = val + .parse() + .expect("Invalid WebSocket node group capacity, must be a whole number"); + assert!( + capacity > 0, + "Invalid WebSocket node group capacity, a group has to hold at least one node" + ); + capacity + }), + node_ttl_ms: env.var("CELERITY_WS_CLUSTER_NODE_TTL_MS").ok().map(|val| { + let ttl: u64 = val + .parse() + .expect("Invalid WebSocket node TTL, must be a whole number of milliseconds"); + assert!( + ttl > 0, + "Invalid WebSocket node TTL, a node needs some time to say it is running in" + ); + ttl + }), + migration_grace_ms: env + .var("CELERITY_WS_CLUSTER_MIGRATION_GRACE_MS") + .ok() + .map(|val| { + val.parse().expect( + "Invalid WebSocket migration grace period, must be a whole number of \ + milliseconds", + ) + }), + seen_ttl_ms: env.var("CELERITY_WS_CLUSTER_SEEN_TTL_MS").ok().map(|val| { + let ttl: u64 = val.parse().expect( + "Invalid WebSocket seen message TTL, must be a whole number of milliseconds", + ); + assert!( + ttl > 0, + "Invalid WebSocket seen message TTL, a message forgotten immediately is never \ + recognised as one already handled" + ); + ttl + }), + forwarded_ttl_ms: env + .var("CELERITY_WS_CLUSTER_FORWARDED_TTL_MS") + .ok() + .map(|val| { + let ttl: u64 = val.parse().expect( + "Invalid WebSocket forwarded message TTL, must be a whole number of \ + milliseconds", + ); + assert!( + ttl > 0, + "Invalid WebSocket forwarded message TTL, a message forgotten immediately \ + is never recognised as one already sent" + ); + ttl + }), + }) +} + /// Reads the WebSocket acknowledgement timeout from the environment. /// /// Separate from [`RuntimeConfig::from_env`] so that the SDKs, which rebuild a @@ -478,6 +710,21 @@ pub fn ws_handler_concurrency_from_env(env: &impl EnvVars) -> Option { }) } +/// Reads the name this node is known by to the others serving the same API. +/// +/// Surrounding whitespace is taken off and a name left empty is treated as one +/// that was never configured, since an empty name would have every node of a +/// cluster answering to the same one. +/// +/// See [`ws_ack_timeout_ms_from_env`] for why this is not only read in +/// [`RuntimeConfig::from_env`]. +pub fn server_node_name_from_env(env: &impl EnvVars) -> Option { + env.var("CELERITY_SERVER_NODE_NAME") + .ok() + .map(|name| name.trim().to_string()) + .filter(|name| !name.is_empty()) +} + #[derive(Debug)] pub struct AppConfig { pub api: Option, @@ -791,6 +1038,100 @@ mod tests { MapEnv(vars) } + /// A config reaches a log through anything that prints it, so the + /// credentials have to be gone before they are written out rather than at + /// each place that writes. + #[test] + fn test_a_password_is_kept_out_of_what_is_written_about_a_cluster() { + let config = RuntimeConfig::from_env(&env(&[ + ("CELERITY_WS_CLUSTER_REDIS_NODES", "redis://127.0.0.1:6379"), + ("CELERITY_WS_CLUSTER_REDIS_PASSWORD", "hunter2"), + ])); + + let written = format!("{config:?}"); + + assert!(!written.contains("hunter2"), "written out as {written}"); + assert!(written.contains("redis_password: Some(\"\")")); + assert_eq!( + config.ws_cluster.and_then(|cluster| cluster.redis_password), + Some("hunter2".to_string()), + "the password still has to be there to connect with" + ); + } + + /// A managed deployment hands out an address with the password already in + /// it, so an address is as much a secret as the password field. + #[test] + fn test_a_password_carried_by_an_address_is_kept_out_too() { + let config = ws_cluster_from_env(&env(&[( + "CELERITY_WS_CLUSTER_REDIS_NODES", + "redis://user:hunter2@cache.example.com:6379,rediss://:hunter3@other.example.com:6380", + )])) + .expect("configuring a redis deployment should turn clustering on"); + + let written = format!("{config:?}"); + + assert!(!written.contains("hunter2"), "written out as {written}"); + assert!(!written.contains("hunter3"), "written out as {written}"); + assert!( + written.contains("cache.example.com:6379") + && written.contains("other.example.com:6380"), + "enough of an address should be left to tell one node from another, {written}" + ); + } + + /// An address carrying no credentials is left as it is, so the usual case + /// reads as it was configured. + #[test] + fn test_an_address_with_nothing_to_hide_is_written_out_as_it_is() { + let config = ws_cluster_from_env(&env(&[( + "CELERITY_WS_CLUSTER_REDIS_NODES", + "redis://127.0.0.1:6379", + )])) + .expect("configuring a redis deployment should turn clustering on"); + + assert!(format!("{config:?}").contains("redis://127.0.0.1:6379")); + } + + /// The part of a URL after the authority is not a credential however much + /// it looks like one. + #[test] + fn test_only_the_authority_of_an_address_is_taken_as_a_credential() { + assert_eq!( + redact_url_credentials("redis://127.0.0.1:6379/0@notacredential"), + "redis://127.0.0.1:6379/0@notacredential" + ); + } + + #[test] + fn test_takes_the_node_name_it_is_given() { + let config = RuntimeConfig::from_env(&env(&[("CELERITY_SERVER_NODE_NAME", "node-a")])); + + assert_eq!(config.server_node_name, Some("node-a".to_string())); + } + + #[test] + fn test_takes_the_surrounding_whitespace_off_a_node_name() { + let config = RuntimeConfig::from_env(&env(&[("CELERITY_SERVER_NODE_NAME", " node-a ")])); + + assert_eq!(config.server_node_name, Some("node-a".to_string())); + } + + /// An empty name has to fall through to the hostname rather than be taken + /// as the identity, since every node of a cluster would otherwise answer to + /// the same one. + #[test] + fn test_treats_an_empty_node_name_as_one_that_was_never_configured() { + for value in ["", " "] { + let config = RuntimeConfig::from_env(&env(&[("CELERITY_SERVER_NODE_NAME", value)])); + + assert_eq!( + config.server_node_name, None, + "{value:?} should not be a name" + ); + } + } + #[test] fn reads_a_fallback_port_within_the_range_a_port_can_take() { let config = @@ -886,6 +1227,94 @@ mod tests { RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_TIMEOUT_MS", "ten seconds")])); } + /// No Redis deployment configured means a single node, which is the shape + /// most deployments have. + #[test] + fn test_a_deployment_with_no_redis_configured_is_a_single_node() { + assert!(RuntimeConfig::from_env(&env(&[])).ws_cluster.is_none()); + } + + /// An empty list is nothing configured, rather than a cluster of no nodes. + #[test] + fn test_an_empty_redis_list_is_a_single_node() { + assert!( + RuntimeConfig::from_env(&env(&[("CELERITY_WS_CLUSTER_REDIS_NODES", " , ")])) + .ws_cluster + .is_none() + ); + } + + #[test] + fn test_the_cluster_settings_are_read_from_the_environment() { + let config = RuntimeConfig::from_env(&env(&[ + ("CELERITY_SERVER_NODE_NAME", "api-node-1"), + ( + "CELERITY_WS_CLUSTER_REDIS_NODES", + "redis://one:6379, redis://two:6379,", + ), + ("CELERITY_WS_CLUSTER_REDIS_PASSWORD", "hunter2"), + ("CELERITY_WS_CLUSTER_REDIS_CLUSTER_MODE", "true"), + ("CELERITY_WS_CLUSTER_KEY_PREFIX", "chat"), + ("CELERITY_WS_CLUSTER_NODE_GROUP_CAPACITY", "3"), + ("CELERITY_WS_CLUSTER_NODE_TTL_MS", "15000"), + ("CELERITY_WS_CLUSTER_MIGRATION_GRACE_MS", "2000"), + ])); + + assert_eq!(config.server_node_name, Some("api-node-1".to_string())); + let cluster = config.ws_cluster.expect("the nodes should be clustered"); + // Trimmed, and the trailing comma is not a node called nothing. + assert_eq!( + cluster.redis_nodes, + vec![ + "redis://one:6379".to_string(), + "redis://two:6379".to_string() + ] + ); + assert_eq!(cluster.redis_password, Some("hunter2".to_string())); + assert!(cluster.redis_cluster_mode); + assert_eq!(cluster.key_prefix, Some("chat".to_string())); + assert_eq!(cluster.node_group_capacity, Some(3)); + assert_eq!(cluster.node_ttl_ms, Some(15000)); + assert_eq!(cluster.migration_grace_ms, Some(2000)); + } + + /// Configuring a Redis deployment is the whole decision, so everything else + /// can be left to the runtime. + #[test] + fn test_configuring_a_redis_is_enough_to_cluster() { + let config = RuntimeConfig::from_env(&env(&[( + "CELERITY_WS_CLUSTER_REDIS_NODES", + "redis://one:6379", + )])); + + let cluster = config.ws_cluster.expect("the nodes should be clustered"); + assert!(!cluster.redis_cluster_mode); + assert_eq!(cluster.key_prefix, None); + assert_eq!(cluster.node_group_capacity, None); + assert_eq!(cluster.node_ttl_ms, None); + assert_eq!(cluster.migration_grace_ms, None); + } + + /// A group holding nothing has nowhere to put the node that is asking. + #[test] + #[should_panic(expected = "at least one node")] + fn test_a_node_group_holding_nothing_is_refused() { + RuntimeConfig::from_env(&env(&[ + ("CELERITY_WS_CLUSTER_REDIS_NODES", "redis://one:6379"), + ("CELERITY_WS_CLUSTER_NODE_GROUP_CAPACITY", "0"), + ])); + } + + /// No time at all leaves a node dead the moment it says it is running. + #[test] + #[should_panic(expected = "some time to say it is running in")] + fn test_a_node_ttl_of_nothing_is_refused() { + RuntimeConfig::from_env(&env(&[ + ("CELERITY_WS_CLUSTER_REDIS_NODES", "redis://one:6379"), + ("CELERITY_WS_CLUSTER_NODE_TTL_MS", "0"), + ])); + } + #[test] fn test_handler_concurrency_is_left_to_the_runtime_when_unset() { assert_eq!( diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index d8c58750..8bfe842e 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -310,3 +310,21 @@ pub const CELERITY_CONSUMER_DLQ_MAX_ATTEMPTS_ANNOTATION_NAME: &str = // The leeway for JWT validation in seconds. pub const JWT_VALIDATION_CLOCK_SKEW_LEEWAY: u64 = 60; + +// How many nodes a node group holds before a new one is started, which is the +// number that the scalable WebSockets protocol suggests. +pub const DEFAULT_WS_NODE_GROUP_CAPACITY: usize = 5; + +// How long a node goes without saying it is running before the rest of the +// cluster treats it as gone. +// +// Long enough to ride out a stalled task or a slow round trip, since a node +// beats three times inside it, and short enough that a node which has really +// gone stops attracting messages promptly. +pub const DEFAULT_WS_CLUSTER_NODE_TTL_MS: u64 = 30_000; + +// How long a node keeps listening to the group it has left after moving. +// +// Covers a sender that read where a connection was just before it moved and +// published a moment later. +pub const DEFAULT_WS_CLUSTER_MIGRATION_GRACE_MS: u64 = 5_000; diff --git a/libs/runtime/core/src/errors.rs b/libs/runtime/core/src/errors.rs index 0f59a5b4..fe82b5ac 100644 --- a/libs/runtime/core/src/errors.rs +++ b/libs/runtime/core/src/errors.rs @@ -78,6 +78,10 @@ pub enum ApplicationStartError { HttpClient(reqwest::Error), ConsumerSetup(String), OpenTelemetryMetrics(String), + // The nodes of a WebSocket API could not be joined up. Fatal rather than + // logged, since a node that starts anyway serves clients whose messages + // silently never reach the connections held elsewhere. + WebSocketClusterSetup(String), } impl fmt::Display for ApplicationStartError { @@ -113,6 +117,12 @@ impl fmt::Display for ApplicationStartError { ApplicationStartError::OpenTelemetryMetrics(msg) => { write!(f, "application start error: metrics setup failed: {msg}") } + ApplicationStartError::WebSocketClusterSetup(msg) => { + write!( + f, + "application start error: websocket cluster setup failed: {msg}" + ) + } } } } diff --git a/libs/runtime/core/src/lib.rs b/libs/runtime/core/src/lib.rs index 72daa83c..4e2ee7ab 100644 --- a/libs/runtime/core/src/lib.rs +++ b/libs/runtime/core/src/lib.rs @@ -35,4 +35,6 @@ pub mod types; pub(crate) mod utils; mod value_sources; pub mod websocket; +#[cfg(feature = "ws_clustering")] +pub mod websocket_cluster; pub mod websocket_dedupe; diff --git a/libs/runtime/core/src/transform_config.rs b/libs/runtime/core/src/transform_config.rs index ed791bf3..a25343e8 100644 --- a/libs/runtime/core/src/transform_config.rs +++ b/libs/runtime/core/src/transform_config.rs @@ -1497,6 +1497,8 @@ mod tests { ws_ack_timeout_ms: None, ws_ack_max_attempts: None, ws_handler_concurrency: None, + server_node_name: None, + ws_cluster: None, } } diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 6d60a545..1331a254 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -313,7 +313,8 @@ async fn handle_socket( // causing the TCP connection to linger. state .connections - .add_connection(connection_id.clone(), socket_ref.clone()); + .register_connection(connection_id.clone(), socket_ref.clone()) + .await; ws_connections_counter().add(1, &[]); // Send the capabilities signal, this is a binary frame that indicates the server @@ -364,7 +365,10 @@ async fn handle_socket( // No disconnect handler runs. The connect handler turned this // connection down, so from the application's side it never // connected. - state.connections.remove_connection(connection_id.clone()); + state + .connections + .deregister_connection(connection_id.clone()) + .await; ws_connections_counter().add(-1, &[]); return; } @@ -568,7 +572,10 @@ async fn handle_socket( } let _ = on_disconnect(connection_id.clone(), &state, &request_ctx).await; - state.connections.remove_connection(connection_id.clone()); + state + .connections + .deregister_connection(connection_id.clone()) + .await; ws_connections_counter().add(-1, &[]); } .instrument(info_span!("websocket_connection", connection_id = %connection_id)) diff --git a/libs/runtime/core/src/websocket_cluster.rs b/libs/runtime/core/src/websocket_cluster.rs new file mode 100644 index 00000000..c5ed2606 --- /dev/null +++ b/libs/runtime/core/src/websocket_cluster.rs @@ -0,0 +1,154 @@ +//! Joining a node to the others serving the same WebSocket API. + +use std::sync::Arc; + +use celerity_ws_registry::registry::WebSocketConnRegistry; +use tokio::sync::oneshot; + +use crate::{ + config::WsClusterConfig, + consts::{ + DEFAULT_WS_CLUSTER_MIGRATION_GRACE_MS, DEFAULT_WS_CLUSTER_NODE_TTL_MS, + DEFAULT_WS_NODE_GROUP_CAPACITY, + }, + errors::ApplicationStartError, + websocket_dedupe::{SeenMessages, SharedMessageIdStore, DEFAULT_MESSAGE_ID_TTL_MS}, +}; + +/// One shape for every way joining a cluster can fail, so a message names the +/// step rather than only the error. +fn cluster_setup_error(message: &str, err: E) -> ApplicationStartError { + ApplicationStartError::WebSocketClusterSetup(format!("{message}: {err:?}")) +} + +/// Joins this node to the others serving the same WebSocket API, and returns +/// what to tell when it should leave. +/// +/// A failure here should stop the runtime starting. A node that carried on +/// would serve its own clients while every message for a connection held +/// elsewhere went nowhere, which is worse than not starting. +pub async fn join_cluster( + registry: Arc, + seen_messages: Option>, + cluster_config: WsClusterConfig, + service_name: &str, + server_node_name: &str, +) -> Result, ApplicationStartError> { + use celerity_helpers::redis::{get_redis_connection, ConnectionConfig}; + use celerity_ws_redis::{ + forwarded::{ForwardedMessages, DEFAULT_FORWARDED_TTL_MS}, + locations::ConnectionLocations, + node_group::{join_or_create, spawn_heartbeat, NodeGroupConfig}, + pubsub::{connect, PubSubConnectionConfig}, + }; + + // Fallback to the service name as an application's nodes share it and two + // separate applications do not. + let key_prefix = cluster_config + .key_prefix + .clone() + .unwrap_or_else(|| service_name.to_string()); + let group_config = NodeGroupConfig { + server_node_name: server_node_name.to_string(), + capacity: cluster_config + .node_group_capacity + .unwrap_or(DEFAULT_WS_NODE_GROUP_CAPACITY), + node_ttl_ms: cluster_config + .node_ttl_ms + .unwrap_or(DEFAULT_WS_CLUSTER_NODE_TTL_MS), + key_prefix: key_prefix.clone(), + }; + + let mut conn = get_redis_connection( + &ConnectionConfig { + nodes: cluster_config.redis_nodes.clone(), + password: cluster_config.redis_password.clone(), + cluster_mode: cluster_config.redis_cluster_mode, + }, + None, + ) + .await + .map_err(|err| { + cluster_setup_error( + "could not reach the redis deployment the nodes cluster over", + err, + ) + })?; + + let group = join_or_create(&mut conn, &group_config) + .await + .map_err(|err| cluster_setup_error("could not join a node group", err))?; + let locations = ConnectionLocations::new( + conn.clone(), + key_prefix.clone(), + group.id.clone(), + group_config.node_ttl_ms, + ); + registry + .set_locations(locations.clone()) + .map_err(|err| cluster_setup_error("could not attach the connection store", err))?; + + // The other direction of the same idea: a client resending to whichever + // node it reconnected to, rather than a node relaying to a client. + if let Some(seen_messages) = seen_messages { + seen_messages + .attach_shared(SharedMessageIdStore::new( + conn.clone(), + key_prefix.clone(), + cluster_config + .seen_ttl_ms + .unwrap_or(DEFAULT_MESSAGE_ID_TTL_MS), + )) + .map_err(|_| { + ApplicationStartError::WebSocketClusterSetup( + "the store for messages seen from clients was already shared".to_string(), + ) + })?; + } + + // Shared, because a message resent after its acknowledgement went + // missing arrives at whichever node holds the connection now, which may + // not be the node that delivered it the first time. + registry + .set_forwarded_messages(ForwardedMessages::new( + conn.clone(), + key_prefix.clone(), + cluster_config + .forwarded_ttl_ms + .unwrap_or(DEFAULT_FORWARDED_TTL_MS), + )) + .map_err(|err| cluster_setup_error("could not attach the forwarded message store", err))?; + + let (moved_tx, moved_rx) = tokio::sync::mpsc::channel(4); + let (broadcaster, from_other_nodes) = connect( + PubSubConnectionConfig { + server_node_name: group_config.server_node_name.clone(), + key_prefix, + nodes: cluster_config.redis_nodes, + password: cluster_config.redis_password, + cluster_mode: cluster_config.redis_cluster_mode, + migration_grace_ms: cluster_config + .migration_grace_ms + .unwrap_or(DEFAULT_WS_CLUSTER_MIGRATION_GRACE_MS), + }, + group.clone(), + locations.clone(), + moved_rx, + ) + .await + .map_err(|err| cluster_setup_error("could not subscribe to the node group", err))?; + + // We need to initialise the registry in this order because the ack worker + // only starts where there is a broadcaster to resend through, + // and listening before either would take in a message with nowhere to put it. + registry + .set_broadcaster(broadcaster) + .map_err(|err| cluster_setup_error("could not attach the broadcaster", err))?; + registry.clone().start_ack_worker(); + registry.listen(from_other_nodes); + + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + spawn_heartbeat(conn, group_config, group, locations, moved_tx, shutdown_rx); + + Ok(shutdown_tx) +} diff --git a/libs/runtime/core/src/websocket_dedupe.rs b/libs/runtime/core/src/websocket_dedupe.rs index 94feb313..a37a267e 100644 --- a/libs/runtime/core/src/websocket_dedupe.rs +++ b/libs/runtime/core/src/websocket_dedupe.rs @@ -1,12 +1,17 @@ use std::{ collections::HashMap, - sync::{Arc, RwLock}, + sync::{Arc, OnceLock, RwLock}, time::{Duration, Instant}, }; use async_trait::async_trait; use tracing::debug; +#[cfg(feature = "ws_clustering")] +use celerity_helpers::redis::ConnectionWrapper; +#[cfg(feature = "ws_clustering")] +use tracing::error; + /// 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; @@ -99,6 +104,121 @@ impl MessageIdStore for InMemoryMessageIdStore { } } +/// The store a connection asks, which is the shared one once a cluster has been +/// joined and this node's own memory until then. +/// +/// The store cannot simply be chosen on construction, because reaching a shared one +/// means connecting to it, which needs a runtime, and the API is built before +/// there is one. So a connection holds this and the answer changes underneath +/// it when the cluster is joined. +#[derive(Debug)] +pub struct SeenMessages { + local: Arc, + shared: OnceLock>, +} + +impl SeenMessages { + pub fn new(ttl_ms: u64) -> Arc { + Arc::new(Self { + local: Arc::new(InMemoryMessageIdStore::new(ttl_ms)), + shared: OnceLock::new(), + }) + } + + /// Hands over to a store the rest of the cluster can see. + /// + /// Refused twice, since the second would answer for messages the first has + /// already been told about. The store that was refused comes back, so a + /// caller can say what it was holding. + pub fn attach_shared( + &self, + shared: Arc, + ) -> Result<(), Arc> { + self.shared.set(shared) + } + + /// Clears out ids this node has remembered past their time. + /// + /// Only what this node holds. A shared store expires its own entries. + pub fn start_eviction(self: &Arc) { + self.local.clone().start_eviction(); + } +} + +#[async_trait] +impl MessageIdStore for SeenMessages { + async fn record_and_check_seen(&self, message_id: &str) -> bool { + match self.shared.get() { + Some(shared) => shared.record_and_check_seen(message_id).await, + None => self.local.record_and_check_seen(message_id).await, + } + } +} + +/// The store holding what every node of a cluster has already +/// been sent by its clients. +/// +/// A client resends when it does not hear that its message arrived, and a +/// client that reconnected first may resend to a different node. Only a record +/// the whole cluster can read recognises that as the message it already acted +/// on. +/// +/// Kept apart from the record of what the cluster has forwarded to clients, +/// which is the same idea in the other direction. An application chooses its own +/// message ids in both, so one keyspace would let a client's id collide with a +/// server's. +#[cfg(feature = "ws_clustering")] +#[derive(Debug)] +pub struct SharedMessageIdStore { + conn: ConnectionWrapper, + key_prefix: String, + ttl_ms: u64, +} + +#[cfg(feature = "ws_clustering")] +impl SharedMessageIdStore { + pub fn new(conn: ConnectionWrapper, key_prefix: String, ttl_ms: u64) -> Arc { + Arc::new(Self { + conn, + key_prefix, + ttl_ms, + }) + } + + fn key(&self, message_id: &str) -> String { + format!("{}:client-msg:{}", self.key_prefix, message_id) + } +} + +#[cfg(feature = "ws_clustering")] +#[async_trait] +impl MessageIdStore for SharedMessageIdStore { + /// Sets the id only where it is not already there, which answers and + /// records in one round trip. + /// + /// A store that cannot answer is taken as never having seen the message, so + /// a failed lookup costs a message handled twice rather than a message a + /// client sent and nothing acted on. + async fn record_and_check_seen(&self, message_id: &str) -> bool { + match self + .conn + .clone() + .pset_ex_nx(&self.key(message_id), "1", self.ttl_ms) + .await + { + Ok(recorded) => !recorded, + Err(err) => { + error!( + message_id = %message_id, + "could not tell whether this message has been seen before, handling it \ + rather than dropping it: {err}" + ); + false + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -150,4 +270,39 @@ mod tests { assert!(!seen.contains_key("old"), "an expired id should be swept"); assert!(seen.contains_key("new"), "a live id should be kept"); } + + /// Until a cluster is joined a node answers from its own memory, and + /// afterwards from the store the rest of the cluster can see. + #[test_log::test(tokio::test)] + async fn test_the_shared_store_takes_over_once_it_is_attached() { + let seen = SeenMessages::new(DEFAULT_MESSAGE_ID_TTL_MS); + + assert!(!seen.record_and_check_seen("m-1").await); + assert!( + seen.record_and_check_seen("m-1").await, + "this node should recognise a message it has already handled" + ); + + seen.attach_shared(Arc::new(AlwaysNew)).unwrap(); + assert!( + !seen.record_and_check_seen("m-1").await, + "the shared store should be answering, not the memory of this node" + ); + assert!( + seen.attach_shared(Arc::new(AlwaysNew)).is_err(), + "a second shared store would answer for messages the first was told about" + ); + } + + /// Stands in for a shared store, and answers differently from the local one + /// so a test can tell which was asked. + #[derive(Debug)] + struct AlwaysNew; + + #[async_trait] + impl MessageIdStore for AlwaysNew { + async fn record_and_check_seen(&self, _message_id: &str) -> bool { + false + } + } } diff --git a/libs/runtime/core/tests/websocket_cluster_test.rs b/libs/runtime/core/tests/websocket_cluster_test.rs new file mode 100644 index 00000000..89c6f1c1 --- /dev/null +++ b/libs/runtime/core/tests/websocket_cluster_test.rs @@ -0,0 +1,209 @@ +//! Joining a node to the rest of the cluster. +//! +//! Every piece this wires together has tests of its own. What these cover is +//! that the wiring happened at all, which nothing else notices, for example, a store left +//! unattached leaves each piece working perfectly and the runtime behaving as +//! though it were alone. + +#![cfg(feature = "ws_clustering")] + +use std::{sync::Arc, time::Duration}; + +use celerity_helpers::{ + redis::ConnectionWrapper, + testing::{redis_config, redis_connection}, +}; + +use celerity_runtime_core::{ + config::WsClusterConfig, + websocket_cluster::join_cluster, + websocket_dedupe::{MessageIdStore, SeenMessages, SharedMessageIdStore}, +}; +use celerity_ws_redis::{ + forwarded::ForwardedMessages, locations::ConnectionLocations, node_group::node_key, +}; +use celerity_ws_registry::{ + registry::{WebSocketConnRegistry, WebSocketConnRegistryConfig}, + types::AckWorkerConfig, +}; + +/// Clears what an earlier run left behind, since a failed run never reaches its +/// own cleanup. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str) { + let index_key = format!("{prefix}:{{group-meta}}:node-groups"); + for group_id in conn.smembers(&index_key).await.unwrap() { + let members_key = format!("{prefix}:{{group-meta}}:node-group-members:{group_id}"); + for member in conn.smembers(&members_key).await.unwrap() { + conn.del(&node_key(prefix, &member)).await.unwrap(); + } + conn.del(&members_key).await.unwrap(); + } + conn.del(&index_key).await.unwrap(); + conn.del(&format!("{prefix}:client-msg:m-1")).await.unwrap(); +} + +fn registry(node_name: &str) -> Arc { + Arc::new(WebSocketConnRegistry::new( + WebSocketConnRegistryConfig { + ack_worker_config: Some(AckWorkerConfig::default()), + server_node_name: node_name.to_string(), + }, + None, + )) +} + +fn cluster_config(prefix: &str) -> WsClusterConfig { + WsClusterConfig { + redis_nodes: redis_config().nodes, + redis_password: redis_config().password, + redis_cluster_mode: redis_config().cluster_mode, + key_prefix: Some(prefix.to_string()), + node_group_capacity: Some(2), + node_ttl_ms: Some(30_000), + migration_grace_ms: Some(1_000), + forwarded_ttl_ms: Some(30_000), + seen_ttl_ms: Some(30_000), + } +} + +/// Everything a node needs to take part is attached to it. +/// +/// Each store is checked by attaching another and finding it refused, which is +/// the registry saying it already has one. A store left unattached is the +/// failure this is for, and it is silent as the node serves its own clients and +/// simply never finds anybody else's. +#[test_log::test(tokio::test)] +async fn test_joining_attaches_everything_a_node_needs() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-wiring"; + clear(&mut conn, prefix).await; + + let registry = registry("node-1"); + let seen = SeenMessages::new(30_000); + let shutdown = join_cluster( + registry.clone(), + Some(seen.clone()), + cluster_config(prefix), + "a-service", + "node-1", + ) + .await + .expect("a node should be able to join"); + + let (spare_tx, _spare_rx) = tokio::sync::mpsc::channel(1); + assert!( + registry.set_broadcaster(spare_tx).is_err(), + "the registry should already have somewhere to send messages between nodes" + ); + assert!( + registry + .set_locations(ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + "a-group".to_string(), + 30_000, + )) + .is_err(), + "the registry should already know where to record the connections it holds" + ); + assert!( + registry + .set_forwarded_messages(ForwardedMessages::new( + conn.clone(), + prefix.to_string(), + 30_000 + )) + .is_err(), + "the registry should already know where to record what it has forwarded" + ); + assert!( + seen.attach_shared(SharedMessageIdStore::new( + conn.clone(), + prefix.to_string(), + 30_000 + )) + .is_err(), + "what clients have sent should already be recorded where the cluster can see it" + ); + + // And the node took a place, which is what the rest of it hangs off. + assert!(conn.exists(&node_key(prefix, "node-1")).await.unwrap()); + + drop(shutdown); +} + +/// What clients have sent is recorded where every node can read it, rather than +/// in the memory of whichever node took the message. +#[test_log::test(tokio::test)] +async fn test_joining_shares_what_clients_have_sent() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-wiring-seen"; + clear(&mut conn, prefix).await; + + // Another node handled this message before this one joined. + let elsewhere = SharedMessageIdStore::new(conn.clone(), prefix.to_string(), 30_000); + assert!(!elsewhere.record_and_check_seen("m-1").await); + + let seen = SeenMessages::new(30_000); + let shutdown = join_cluster( + registry("node-1"), + Some(seen.clone()), + cluster_config(prefix), + "a-service", + "node-1", + ) + .await + .expect("a node should be able to join"); + + assert!( + seen.record_and_check_seen("m-1").await, + "a joined node should recognise what another node has already handled" + ); + + drop(shutdown); +} + +/// Being told to stop takes this node out of its group rather than leaving the +/// others to wait for its expiry. +#[test_log::test(tokio::test)] +async fn test_a_node_told_to_stop_leaves_its_group() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-wiring-leave"; + clear(&mut conn, prefix).await; + + let shutdown = join_cluster( + registry("node-1"), + None, + cluster_config(prefix), + "a-service", + "node-1", + ) + .await + .expect("a node should be able to join"); + assert!(conn.exists(&node_key(prefix, "node-1")).await.unwrap()); + + shutdown.send(()).unwrap(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while conn.exists(&node_key(prefix, "node-1")).await.unwrap() { + assert!( + tokio::time::Instant::now() < deadline, + "a node told to stop should take its place with it" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// A Redis deployment that cannot be reached stops the runtime starting. +#[test_log::test(tokio::test)] +async fn test_a_node_that_cannot_reach_redis_refuses_to_start() { + let mut config = cluster_config("test-cluster-wiring-unreachable"); + // Nothing listens here, and the port is outside what a test would bind. + config.redis_nodes = vec!["redis://127.0.0.1:6399/?protocol=resp3".to_string()]; + + let joined = join_cluster(registry("node-1"), None, config, "a-service", "node-1").await; + assert!( + joined.is_err(), + "a node that cannot reach the others should refuse to start rather than serve alone" + ); +} diff --git a/libs/runtime/core/tests/websocket_shared_dedupe_test.rs b/libs/runtime/core/tests/websocket_shared_dedupe_test.rs new file mode 100644 index 00000000..5c4d70e1 --- /dev/null +++ b/libs/runtime/core/tests/websocket_shared_dedupe_test.rs @@ -0,0 +1,126 @@ +//! The record of what a client has already sent, shared across a cluster. +//! +//! A client resends when it does not hear that its message arrived, and a +//! client that reconnected first may resend to a different node. Only a record +//! every node can read recognises that as the message it already acted on. + +#![cfg(feature = "ws_clustering")] + +use celerity_helpers::{redis::ConnectionWrapper, testing::redis_connection}; + +use celerity_runtime_core::websocket_dedupe::{MessageIdStore, SeenMessages, SharedMessageIdStore}; +use celerity_ws_redis::forwarded::ForwardedMessages; +use celerity_ws_registry::registry::ForwardedMessageStore; + +/// Clears the records a previous run left behind. +/// +/// A record outlives the run that wrote it, and a suite is usually run again +/// well inside that, so without this a second run finds its first message +/// already recorded and reads it as one it has already handled. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str, message_ids: &[&str]) { + for message_id in message_ids { + conn.del(&format!("{prefix}:client-msg:{message_id}")) + .await + .unwrap(); + conn.del(&format!("{prefix}:msg:{message_id}")) + .await + .unwrap(); + } +} + +/// A message handled by one node is recognised by another. +#[test_log::test(tokio::test)] +async fn test_a_message_handled_on_one_node_is_recognised_on_another() { + let mut conn = redis_connection().await; + let prefix = "test-shared-dedupe"; + clear(&mut conn, prefix, &["m-1", "m-2"]).await; + + let first_node = SharedMessageIdStore::new(conn.clone(), prefix.to_string(), 10_000); + let second_node = + SharedMessageIdStore::new(redis_connection().await, prefix.to_string(), 10_000); + + assert!( + !first_node.record_and_check_seen("m-1").await, + "a message nothing has handled should be acted on" + ); + assert!( + second_node.record_and_check_seen("m-1").await, + "a client that resent to another node should be recognised there" + ); + assert!( + !second_node.record_and_check_seen("m-2").await, + "a different message should be its own" + ); + + clear(&mut conn, prefix, &["m-1", "m-2"]).await; +} + +/// The same message id in each direction is two different messages. +/// +/// An application chooses its own ids for what it sends and what it receives, +/// so the two will collide. Sharing a keyspace would have whichever came first +/// hide the other, and the one hidden is never acted on. +#[test_log::test(tokio::test)] +async fn test_a_clients_messages_do_not_collide_with_the_servers() { + let mut conn = redis_connection().await; + let prefix = "test-shared-dedupe-keyspace"; + clear(&mut conn, prefix, &["shared-id"]).await; + + let from_clients = SharedMessageIdStore::new(conn.clone(), prefix.to_string(), 10_000); + let to_clients = ForwardedMessages::new(conn.clone(), prefix.to_string(), 10_000); + + assert!( + !from_clients.record_and_check_seen("shared-id").await, + "a message a client sent should be acted on the first time" + ); + assert!( + !to_clients + .record_and_check_forwarded("shared-id") + .await + .unwrap(), + "a message the cluster is forwarding should go out, whatever id a client has used" + ); + + // And each still recognises its own. + assert!(from_clients.record_and_check_seen("shared-id").await); + assert!(to_clients + .record_and_check_forwarded("shared-id") + .await + .unwrap()); + + clear(&mut conn, prefix, &["shared-id"]).await; +} + +/// A node reads the shared store once the cluster is joined, having read its +/// own memory before that. +#[test_log::test(tokio::test)] +async fn test_a_node_hands_over_to_the_shared_store() { + let mut conn = redis_connection().await; + let prefix = "test-shared-dedupe-handover"; + clear(&mut conn, prefix, &["m-1", "m-2"]).await; + + // Recorded by another node before this one joins. + let elsewhere = SharedMessageIdStore::new(conn.clone(), prefix.to_string(), 10_000); + assert!(!elsewhere.record_and_check_seen("m-1").await); + + // Asked about a different message, so that what this node remembers cannot + // stand in for what the cluster knows once it has joined. + let seen = SeenMessages::new(10_000); + assert!( + !seen.record_and_check_seen("m-2").await, + "before joining, a node knows only what it has handled itself" + ); + + seen.attach_shared(SharedMessageIdStore::new( + conn.clone(), + prefix.to_string(), + 10_000, + )) + .unwrap(); + assert!( + seen.record_and_check_seen("m-1").await, + "once joined, a node should recognise what the cluster has already handled" + ); + + clear(&mut conn, prefix, &["m-1", "m-2"]).await; +} diff --git a/libs/runtime/docker-compose.test-deps.yml b/libs/runtime/docker-compose.test-deps.yml index 42c8ee52..bb0bcb2a 100644 --- a/libs/runtime/docker-compose.test-deps.yml +++ b/libs/runtime/docker-compose.test-deps.yml @@ -13,8 +13,18 @@ services: - "/var/run/docker.sock:/var/run/docker.sock" valkey: container_name: "valkey_celerity_runtime_tests" - image: bitnamilegacy/valkey:8.1.3 + image: valkey/valkey:8.1.3 ports: - "6379:6379" - environment: - - ALLOW_EMPTY_PASSWORD=yes + # A real cluster, for the tests that check what only a cluster can determine, + # a script reaching across slots is refused, and keys spread across them + # cannot be read or written in one request. + valkey-cluster: + container_name: "valkey_cluster_celerity_runtime_tests" + image: valkey/valkey:8.1.3 + ports: + - "7100-7105:7100-7105" + - "17100-17105:17100-17105" + volumes: + - ./scripts/valkey-cluster-entrypoint.sh:/entrypoint.sh:ro + command: ["sh", "/entrypoint.sh"] diff --git a/libs/runtime/helpers/Cargo.toml b/libs/runtime/helpers/Cargo.toml index c666f271..7f4f051e 100644 --- a/libs/runtime/helpers/Cargo.toml +++ b/libs/runtime/helpers/Cargo.toml @@ -27,6 +27,11 @@ redis = { version = "0.32.5", features = [ ] } rand = "0.8.5" +[features] +# Helpers for the tests of crates that build on this one. Never enabled by a +# runtime, only by a dev-dependency. +test-support = [] + [dev-dependencies] test-log = { version = "0.2.16", features = ["log", "trace"] } pretty_assertions = "1.4.0" diff --git a/libs/runtime/helpers/src/lib.rs b/libs/runtime/helpers/src/lib.rs index 6c4efd52..cc20af59 100644 --- a/libs/runtime/helpers/src/lib.rs +++ b/libs/runtime/helpers/src/lib.rs @@ -9,5 +9,7 @@ pub mod retries; pub mod runtime_types; pub mod scanner; pub mod telemetry; +#[cfg(feature = "test-support")] +pub mod testing; pub mod time; pub mod websockets; diff --git a/libs/runtime/helpers/src/redis.rs b/libs/runtime/helpers/src/redis.rs index 83922f7f..7ecc94cf 100644 --- a/libs/runtime/helpers/src/redis.rs +++ b/libs/runtime/helpers/src/redis.rs @@ -227,6 +227,19 @@ impl ConnectionWrapper { } } + /// Stops receiving from a channel. + /// + /// A subscription outlives the reason it was taken out, so a node that + /// moves between groups has to give up the old one rather than quietly go + /// on being sent its traffic. + /// [Redis Docs](https://redis.io/commands/UNSUBSCRIBE) + pub async fn unsubscribe(&mut self, channel_name: &str) -> RedisResult<()> { + match self { + ConnectionWrapper::Cluster(conn) => conn.unsubscribe(channel_name).await, + ConnectionWrapper::SingleNode(conn) => conn.unsubscribe(channel_name).await, + } + } + /// Posts a message to the given channel. /// [Redis Docs](https://redis.io/commands/PUBLISH) pub async fn publish(&mut self, channel_name: &str, message: String) -> RedisResult { @@ -235,6 +248,55 @@ impl ConnectionWrapper { ConnectionWrapper::SingleNode(conn) => conn.publish(channel_name, message).await, } } + + /// Adds a member to a set, returning whether it was not already there. + /// [Redis Docs](https://redis.io/commands/SADD) + pub async fn sadd(&mut self, key: &str, member: &str) -> RedisResult { + let added: i64 = match self { + ConnectionWrapper::Cluster(conn) => conn.sadd(key, member).await?, + ConnectionWrapper::SingleNode(conn) => conn.sadd(key, member).await?, + }; + Ok(added > 0) + } + + /// Removes a member from a set, returning whether it was there to remove. + /// [Redis Docs](https://redis.io/commands/SREM) + pub async fn srem(&mut self, key: &str, member: &str) -> RedisResult { + let removed: i64 = match self { + ConnectionWrapper::Cluster(conn) => conn.srem(key, member).await?, + ConnectionWrapper::SingleNode(conn) => conn.srem(key, member).await?, + }; + Ok(removed > 0) + } + + /// Reads every member of a set. A set that does not exist reads as empty, + /// which is the same answer as a set that has had every member removed. + /// [Redis Docs](https://redis.io/commands/SMEMBERS) + pub async fn smembers(&mut self, key: &str) -> RedisResult> { + match self { + ConnectionWrapper::Cluster(conn) => conn.smembers(key).await, + ConnectionWrapper::SingleNode(conn) => conn.smembers(key).await, + } + } + + /// Reports whether a key is present. + /// [Redis Docs](https://redis.io/commands/EXISTS) + pub async fn exists(&mut self, key: &str) -> RedisResult { + match self { + ConnectionWrapper::Cluster(conn) => conn.exists(key).await, + ConnectionWrapper::SingleNode(conn) => conn.exists(key).await, + } + } + + /// Removes a key, returning whether it was there to remove. + /// [Redis Docs](https://redis.io/commands/DEL) + pub async fn del(&mut self, key: &str) -> RedisResult { + let removed: i64 = match self { + ConnectionWrapper::Cluster(conn) => conn.del(key).await?, + ConnectionWrapper::SingleNode(conn) => conn.del(key).await?, + }; + Ok(removed > 0) + } } /// Creates a connection to a Redis cluster or instance. diff --git a/libs/runtime/helpers/src/testing.rs b/libs/runtime/helpers/src/testing.rs new file mode 100644 index 00000000..859181f1 --- /dev/null +++ b/libs/runtime/helpers/src/testing.rs @@ -0,0 +1,44 @@ +//! Helpers for tests in the crates that build on this one. +//! +//! Behind the `test-support` feature, so nothing here is built into a runtime. + +use crate::redis::{get_redis_connection, ConnectionConfig, ConnectionWrapper}; + +const SINGLE_NODE: &str = "redis://127.0.0.1:6379/?protocol=resp3"; + +/// The cluster `docker-compose.test-deps.yml` starts. +const CLUSTER_NODES: [&str; 6] = [ + "redis://127.0.0.1:7100/?protocol=resp3", + "redis://127.0.0.1:7101/?protocol=resp3", + "redis://127.0.0.1:7102/?protocol=resp3", + "redis://127.0.0.1:7103/?protocol=resp3", + "redis://127.0.0.1:7104/?protocol=resp3", + "redis://127.0.0.1:7105/?protocol=resp3", +]; + +/// Which deployment a run is against. +/// +/// Set `CELERITY_TEST_REDIS_CLUSTER` for the cluster, which is the only place +/// some decisions can be wrong: a script reaching across slots is refused, and +/// so is a request carrying keys that belong to different ones. +pub fn redis_config() -> ConnectionConfig { + if std::env::var("CELERITY_TEST_REDIS_CLUSTER").is_ok() { + return ConnectionConfig { + nodes: CLUSTER_NODES.iter().map(|node| node.to_string()).collect(), + password: None, + cluster_mode: true, + }; + } + + ConnectionConfig { + nodes: vec![SINGLE_NODE.to_string()], + password: None, + cluster_mode: false, + } +} + +pub async fn redis_connection() -> ConnectionWrapper { + get_redis_connection(&redis_config(), None) + .await + .expect("redis has to be running, see docker-compose.test-deps.yml") +} diff --git a/libs/runtime/helpers/tests/redis_commands_test.rs b/libs/runtime/helpers/tests/redis_commands_test.rs new file mode 100644 index 00000000..9dc0ce4b --- /dev/null +++ b/libs/runtime/helpers/tests/redis_commands_test.rs @@ -0,0 +1,71 @@ +use celerity_helpers::redis::{get_redis_connection, ConnectionConfig, ConnectionWrapper}; + +async fn connection() -> ConnectionWrapper { + let conn_config = ConnectionConfig { + nodes: vec!["redis://127.0.0.1:6379/?protocol=resp3".to_string()], + password: None, + cluster_mode: false, + }; + get_redis_connection(&conn_config, None) + .await + .expect("must be able to connect to redis for the command tests") +} + +/// Set membership, which is how a node group knows who belongs to it. +#[test_log::test(tokio::test)] +async fn test_a_set_holds_its_members_until_they_are_removed() { + let mut conn = connection().await; + // Prefixed per test, since these run beside each other against one server. + let key = "helpers-test:set-members"; + conn.del(key).await.unwrap(); + + assert!( + conn.sadd(key, "node-1").await.unwrap(), + "a member that was not there should be reported as added" + ); + assert!( + !conn.sadd(key, "node-1").await.unwrap(), + "a member that is already there should not be reported as added again" + ); + conn.sadd(key, "node-2").await.unwrap(); + + let mut members = conn.smembers(key).await.unwrap(); + members.sort(); + assert_eq!(members, vec!["node-1".to_string(), "node-2".to_string()]); + + assert!(conn.srem(key, "node-1").await.unwrap()); + assert!( + !conn.srem(key, "node-1").await.unwrap(), + "removing a member twice should say so the second time" + ); + assert_eq!( + conn.smembers(key).await.unwrap(), + vec!["node-2".to_string()] + ); + + conn.del(key).await.unwrap(); + assert!( + conn.smembers(key).await.unwrap().is_empty(), + "a set that is gone should read as empty rather than fail" + ); +} + +/// A key's presence and its removal, which is what a node's liveness comes down +/// to once the key carries an expiry. +#[test_log::test(tokio::test)] +async fn test_a_key_is_there_until_it_is_removed() { + let mut conn = connection().await; + let key = "helpers-test:key-presence"; + conn.del(key).await.unwrap(); + + assert!(!conn.exists(key).await.unwrap()); + conn.pset_ex(key, "group-1", 10_000).await.unwrap(); + assert!(conn.exists(key).await.unwrap()); + + assert!(conn.del(key).await.unwrap()); + assert!( + !conn.del(key).await.unwrap(), + "removing a key that has gone should say so rather than report a removal" + ); + assert!(!conn.exists(key).await.unwrap()); +} diff --git a/libs/runtime/scripts/package-test-tools.py b/libs/runtime/scripts/package-test-tools.py index edc29d45..f97a30be 100644 --- a/libs/runtime/scripts/package-test-tools.py +++ b/libs/runtime/scripts/package-test-tools.py @@ -22,6 +22,12 @@ parser.add_argument("--package", help="run tests for a specific package") +class ValkeyClusterNotReady(Exception): + """ + Raised when the valkey cluster does not form in time. + """ + + class LocalstackNotReady(Exception): """ Custom exception type that is raised @@ -45,7 +51,7 @@ def run_package_test_tools() -> None: args = parser.parse_args() try: _run_integration_tests(args) - except (KeyboardInterrupt, LocalstackNotReady): + except (KeyboardInterrupt, LocalstackNotReady, ValkeyClusterNotReady): if args.localdeps: _teardown_local_deps() @@ -59,30 +65,80 @@ def _run_integration_tests(args: argparse.Namespace) -> None: env_copy = os.environ.copy() in_ci_env = os.environ.get('GITHUB_ACTIONS') test_env_file = '.env.test-ci' if in_ci_env else '.env.test' - report_flags = "--lcov --output-path coverage.lcov" if in_ci_env else "--html" selection_flags = f"--package {args.package}" if args.package else "--workspace" exclude_flags = "--exclude celerity-python-runtime-sdk" - feature_flags = "--features celerity_local_consumers" + feature_flags = "--features celerity_local_consumers,celerity_runtime_core/ws_clustering" + test_env = { + # Integration tests can't share the same env vars (.env) as the API running + # in docker as the host endpoints for the AWS service mocks are different. + **cast(Dict[str, str], dotenv_values(test_env_file)), + **env_copy, + } + + # Neither pass reports on its own and the coverage is put together at the + # end, so the tests are built once and what the cluster pass covers counts + # towards the total. + subprocess.run('cargo llvm-cov clean --workspace', shell=True, check=True) # Use cargo-nextest for cleaner per-test output with a summary at the end. # Debug output is only shown for failing tests. completed_process = subprocess.run( - f'cargo llvm-cov {report_flags} nextest {selection_flags} {exclude_flags} {feature_flags} --no-fail-fast --color always', - env={ - # Integration tests can't share the same env vars (.env) as the API running - # in docker as the host endpoints for the AWS service mocks are different. - **cast(Dict[str, str], dotenv_values(test_env_file)), - **env_copy, - }, + f'cargo llvm-cov --no-report nextest {selection_flags} {exclude_flags} ' + f'{feature_flags} --no-fail-fast --color always', + env=test_env, shell=True, check=False ) + + cluster_process = _run_cluster_mode_tests(test_env) + + report_flags = "--lcov --output-path coverage.lcov" if in_ci_env else "--html" + subprocess.run(f'cargo llvm-cov report {report_flags}', shell=True, check=False) + if args.localdeps: _teardown_local_deps() if completed_process.returncode != 0: raise TestRunnerFailed( f'Tests or test runner failed with code {completed_process.returncode}' ) + if cluster_process.returncode != 0: + raise TestRunnerFailed( + 'Tests against a Redis cluster failed with code ' + f'{cluster_process.returncode}' + ) + + +CLUSTER_MODE_PACKAGES = '--package celerity_ws_redis --package celerity_runtime_core' + + +def _run_cluster_mode_tests(test_env: Dict[str, str]) -> subprocess.CompletedProcess: + """ + Runs the Redis-backed tests a second time against a real cluster. + + A cluster is the only place some of the decisions these cover can be wrong + such as a script reaching across slots being refused, along with a request carrying keys + that belong to different ones. Neither shows up against a single instance, + where every key is in the same place. + + Only the tests that touch Redis are run again, and they share the build the + first pass made, so this is a second or two rather than a pass over the + whole workspace. + """ + print('Running the Redis-backed tests again against a cluster ...') + return subprocess.run( + f'cargo llvm-cov --no-report nextest {CLUSTER_MODE_PACKAGES} ' + '--features celerity_local_consumers,celerity_runtime_core/ws_clustering ' + '--test cluster_test --test forwarded_test --test locations_test ' + '--test node_group_test --test pubsub_test ' + '--test websocket_cluster_test --test websocket_shared_dedupe_test ' + '--no-fail-fast --color always', + env={ + **test_env, + 'CELERITY_TEST_REDIS_CLUSTER': '1', + }, + shell=True, + check=False + ) DEPS_DOCKER_COMPOSE = 'docker-compose.test-deps.yml' @@ -104,6 +160,7 @@ def _run_local_deps(context: str) -> None: print('Waiting for sevices to be ready, tailing LocalStack logs for "Ready." ...') _wait_for_localstack(deadline_seconds=60) + _wait_for_valkey_cluster(deadline_seconds=60) _populate_secrets(context) _generate_sqs_queues(context) @@ -144,6 +201,38 @@ def _wait_for_localstack(deadline_seconds: int) -> None: break +def _wait_for_valkey_cluster(deadline_seconds: int) -> None: + """ + Waits for the six servers to agree that they are a cluster. + + They take a moment to find each other, and a test that connects before they + have is told there is no cluster rather than being made to wait. + + Read again rather than followed, so that a container which has said nothing + for a while and one which has stopped saying anything at all are both + noticed. Following the logs only wakes up when there is a line, so neither + would be. + """ + deadline = time.time() + deadline_seconds + while time.time() < deadline: + logs = subprocess.run( + ['docker', 'logs', 'valkey_cluster_celerity_runtime_tests'], + capture_output=True, + check=False, + ) + if b'cluster ready' in logs.stdout or b'cluster ready' in logs.stderr: + print('Valkey cluster is ready, continuing ...') + return + time.sleep(0.2) + + message = ( + 'Timed out waiting for the valkey cluster to form after ' + f'{deadline_seconds} seconds' + ) + print(message) + raise ValkeyClusterNotReady(message) + + def _populate_secrets(context: str) -> None: print("Saving secrets to LocalStack Secret Manager ...") client: SecretsManagerClient = boto3.client( diff --git a/libs/runtime/scripts/valkey-cluster-entrypoint.sh b/libs/runtime/scripts/valkey-cluster-entrypoint.sh new file mode 100755 index 00000000..627d9049 --- /dev/null +++ b/libs/runtime/scripts/valkey-cluster-entrypoint.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Six valkey servers in one container, each announcing 127.0.0.1 on a published port so +# a client on the host can follow a redirection to any of them. A cluster that +# announced its own addresses would be reachable only for the first hop. +set -e + +PORTS="7100 7101 7102 7103 7104 7105" + +for port in $PORTS; do + valkey-server \ + --port "$port" \ + --cluster-enabled yes \ + --cluster-config-file "/tmp/nodes-$port.conf" \ + --cluster-node-timeout 5000 \ + --cluster-announce-ip 127.0.0.1 \ + --cluster-announce-port "$port" \ + --cluster-announce-bus-port "1$port" \ + --appendonly no \ + --save '' \ + --daemonize yes +done + +# Waited for rather than paused on, since a machine under load can take longer than +# any fixed pause and forming the cluster would then fail outright. +deadline=$(( $(date +%s) + 30 )) +for port in $PORTS; do + until valkey-cli -p "$port" ping 2>/dev/null | grep -q PONG; do + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "valkey on port $port was not accepting connections after 30 seconds" >&2 + exit 1 + fi + sleep 0.1 + done +done + +valkey-cli --cluster create \ + 127.0.0.1:7100 127.0.0.1:7101 127.0.0.1:7102 \ + 127.0.0.1:7103 127.0.0.1:7104 127.0.0.1:7105 \ + --cluster-replicas 1 --cluster-yes + +echo "cluster ready" +tail -f /dev/null diff --git a/libs/runtime/sdk/bindgen-ffi/src/application.rs b/libs/runtime/sdk/bindgen-ffi/src/application.rs index 34fdb2e9..c72d48ad 100644 --- a/libs/runtime/sdk/bindgen-ffi/src/application.rs +++ b/libs/runtime/sdk/bindgen-ffi/src/application.rs @@ -8,8 +8,8 @@ use celerity_helpers::{ use celerity_runtime_core::{ application::Application as RuntimeApp, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, - ClientIpSource, RuntimeConfig, + server_node_name_from_env, ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, + ws_cluster_from_env, ws_handler_concurrency_from_env, ClientIpSource, RuntimeConfig, }, errors::{ApplicationStartError, ConfigError}, }; @@ -71,6 +71,8 @@ pub unsafe fn application_create(core_runtime_config: CoreRuntimeConfig) -> *mut ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), + server_node_name: server_node_name_from_env(&ProcessEnvVars::new()), + ws_cluster: ws_cluster_from_env(&ProcessEnvVars::new()), }, Box::new(ProcessEnvVars::new()), ), @@ -230,6 +232,9 @@ impl From for GeneralError { ApplicationStartError::ConsumerSetup(_) => { GeneralError::ApplicationStartConsumerSetupError } + ApplicationStartError::WebSocketClusterSetup(_) => { + GeneralError::ApplicationStartWebsocketClusterSetupError + } ApplicationStartError::OpenTelemetryMetrics(_) => { GeneralError::ApplicationStartOpenTelemetryTraceError } diff --git a/libs/runtime/sdk/bindgen-schema/src/shared.rs b/libs/runtime/sdk/bindgen-schema/src/shared.rs index a5698228..908567e7 100644 --- a/libs/runtime/sdk/bindgen-schema/src/shared.rs +++ b/libs/runtime/sdk/bindgen-schema/src/shared.rs @@ -70,6 +70,10 @@ pub(crate) fn define(lib: &mut LibraryBuilder) -> BackTraced "application_start_consumer_setup_error", "Error starting the application due to failure in setting up message consumers" )? + .add_error( + "application_start_websocket_cluster_setup_error", + "Error starting the application due to failure in joining the other nodes serving the same WebSocket API" + )? .doc("General error type used throughout the library")? .build()?; diff --git a/libs/runtime/sdk/node/Cargo.toml b/libs/runtime/sdk/node/Cargo.toml index 2a7153f1..fcb2a627 100644 --- a/libs/runtime/sdk/node/Cargo.toml +++ b/libs/runtime/sdk/node/Cargo.toml @@ -44,6 +44,7 @@ celerity_local_consumers = ["celerity_runtime_core/celerity_local_consumers"] aws_consumers = ["celerity_runtime_core/aws_consumers"] azure_consumers = ["celerity_runtime_core/azure_consumers"] gcloud_consumers = ["celerity_runtime_core/gcloud_consumers"] +ws_clustering = ["celerity_runtime_core/ws_clustering"] [profile.release] lto = true diff --git a/libs/runtime/sdk/node/__test__/consumer-schedule.spec.ts b/libs/runtime/sdk/node/__test__/consumer-schedule.spec.ts index e220c1b8..e08312f4 100644 --- a/libs/runtime/sdk/node/__test__/consumer-schedule.spec.ts +++ b/libs/runtime/sdk/node/__test__/consumer-schedule.spec.ts @@ -281,20 +281,38 @@ depTest("schedule handler receives trigger from Valkey", async (t) => { const scheduleId = config.schedules!.schedules[0].scheduleId; const timestamp = String(Math.floor(Date.now() / 1000)); - await redis.xadd( - `celerity:schedules:${scheduleId}`, - "*", - "body", - JSON.stringify({ triggered: true }), - "timestamp", - timestamp, - "message_type", - "0", - ); + // Written again until it is picked up. A consumer that starts while the + // stream already exists begins from the end of it, so a trigger written + // before it was ready is never seen. The runtime is entitled to do that, + // since a schedule should not replay whatever it missed while it was + // down, but it means one write and a wait is a race the test loses about + // one run in five. + // Generous, because it costs nothing when the trigger lands first time + // and a loaded machine has been seen to need most of ten seconds. + const deadline = Date.now() + 30_000; + let event: JsScheduleEventInput | undefined; + + while (event === undefined) { + if (Date.now() > deadline) { + throw new Error("timeout waiting for schedule handler"); + } - const timer = setTimeout(() => received.reject(new Error("timeout waiting for schedule handler")), 10_000); - const event = await received.promise; - clearTimeout(timer); + await redis.xadd( + `celerity:schedules:${scheduleId}`, + "*", + "body", + JSON.stringify({ triggered: true }), + "timestamp", + timestamp, + "message_type", + "0", + ); + + event = await Promise.race([ + received.promise, + new Promise((resolve) => setTimeout(() => resolve(undefined), 500)), + ]); + } t.is(event.handlerTag, "source::dailyCleanup::cleanupHandler"); t.truthy(event.messageId); diff --git a/libs/runtime/sdk/node/package.json b/libs/runtime/sdk/node/package.json index 20484239..e8e8ea68 100644 --- a/libs/runtime/sdk/node/package.json +++ b/libs/runtime/sdk/node/package.json @@ -51,7 +51,7 @@ }, "scripts": { "artifacts": "napi artifacts", - "build": "napi build --platform --release -F celerity_local_consumers,aws_consumers,gcloud_consumers,azure_consumers", + "build": "napi build --platform --release -F celerity_local_consumers,aws_consumers,gcloud_consumers,azure_consumers,ws_clustering", "build:debug": "napi build --platform", "prepublishOnly": "napi prepublish -t npm --no-gh-release", "test": "bash scripts/test.sh", diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index b891372d..4b36216d 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -30,11 +30,12 @@ use celerity_runtime_core::{ auth_custom::{AuthGuardHandler, AuthGuardValidateError, AuthGuardValidateInput}, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, - ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, - CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, - GuardHandlerDefinition, GuardsConfig, HttpConfig, HttpHandlerDefinition, RuntimeConfig, - ScheduleConfig, SchedulesConfig, WebSocketConfig, WebSocketHandlerDefinition, + server_node_name_from_env, ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, + ws_cluster_from_env, ws_handler_concurrency_from_env, ApiConfig, AppConfig, ClientIpSource, + ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, + EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, HttpConfig, + HttpHandlerDefinition, RuntimeConfig, ScheduleConfig, SchedulesConfig, WebSocketConfig, + WebSocketHandlerDefinition, }, consts::{ DEFAULT_RESOURCE_STORE_CACHE_ENTRY_TTL, DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL, @@ -1334,6 +1335,8 @@ impl CoreRuntimeApplication { ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), + server_node_name: server_node_name_from_env(&ProcessEnvVars::new()), + ws_cluster: ws_cluster_from_env(&ProcessEnvVars::new()), }; let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); CoreRuntimeApplication { diff --git a/libs/runtime/sdk/python/Cargo.toml b/libs/runtime/sdk/python/Cargo.toml index 89cf5a91..d6569dc4 100644 --- a/libs/runtime/sdk/python/Cargo.toml +++ b/libs/runtime/sdk/python/Cargo.toml @@ -37,6 +37,7 @@ celerity_local_consumers = ["celerity_runtime_core/celerity_local_consumers"] aws_consumers = ["celerity_runtime_core/aws_consumers"] azure_consumers = ["celerity_runtime_core/azure_consumers"] gcloud_consumers = ["celerity_runtime_core/gcloud_consumers"] +ws_clustering = ["celerity_runtime_core/ws_clustering"] [dependencies.celerity_runtime_core] path = "../../core" diff --git a/libs/runtime/sdk/python/pyproject.toml b/libs/runtime/sdk/python/pyproject.toml index a1fd2a6a..bbc788ec 100644 --- a/libs/runtime/sdk/python/pyproject.toml +++ b/libs/runtime/sdk/python/pyproject.toml @@ -45,4 +45,4 @@ check_untyped_defs = true python-source = "python" module-name = "celerity_runtime_sdk._celerity_runtime_sdk" bindings = "pyo3" -features = ["pyo3/extension-module", "celerity_local_consumers", "aws_consumers", "gcloud_consumers", "azure_consumers"] +features = ["pyo3/extension-module", "celerity_local_consumers", "aws_consumers", "gcloud_consumers", "azure_consumers", "ws_clustering"] diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index 30c2bbf2..7099596c 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -25,10 +25,11 @@ use celerity_runtime_core::{ application::Application, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, - ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, - CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, - GuardHandlerDefinition, GuardsConfig, RuntimeConfig, ScheduleConfig, SchedulesConfig, + server_node_name_from_env, ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, + ws_cluster_from_env, ws_handler_concurrency_from_env, ApiConfig, AppConfig, ClientIpSource, + ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, + EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, RuntimeConfig, + ScheduleConfig, SchedulesConfig, }, request::{MatchedRoute, RequestId, ResolvedClientIp, ResolvedUserAgent}, telemetry_utils::extract_trace_context, @@ -515,6 +516,8 @@ impl CoreRuntimeApplication { ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), + server_node_name: server_node_name_from_env(&ProcessEnvVars::new()), + ws_cluster: ws_cluster_from_env(&ProcessEnvVars::new()), }; println!("Creating CoreRuntimeApplication with config: {native_runtime_config:?}"); let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); diff --git a/libs/runtime/sdk/python/tests/test_consumer_schedule.py b/libs/runtime/sdk/python/tests/test_consumer_schedule.py index f4c1ff38..ffae5859 100644 --- a/libs/runtime/sdk/python/tests/test_consumer_schedule.py +++ b/libs/runtime/sdk/python/tests/test_consumer_schedule.py @@ -45,6 +45,26 @@ def _wait_for_file(path: str, timeout: float = 10.0): raise TimeoutError(f"File {path} not created within {timeout}s") +def _trigger_until_handled( + redis_client, stream: str, entry: dict, result_path: str, timeout: float = 30.0 +): + """Write a trigger until the handler answers one, then return what it wrote. + + A consumer that starts while the stream already exists begins from the end + of it, so a trigger written before it was ready is never seen. The runtime + is entitled to do that, since a schedule should not replay whatever it + missed while it was down, but it means one write and a wait is a race. + """ + start = time.time() + while time.time() - start < timeout: + redis_client.xadd(stream, entry) + try: + return _wait_for_file(result_path, timeout=1.0) + except TimeoutError: + continue + raise TimeoutError(f"File {result_path} not created within {timeout}s") + + # --------------------------------------------------------------------------- # Config-only tests (no external dependencies) # --------------------------------------------------------------------------- @@ -149,16 +169,16 @@ def test_schedule_handler_receives_trigger(consumer_server): r = redis_lib.Redis(host=host, port=port) try: timestamp = str(int(time.time())) - r.xadd( + result = _trigger_until_handled( + r, f"celerity:schedules:{schedule_id}", { "body": json.dumps({"triggered": True}), "timestamp": timestamp, "message_type": "0", }, + os.path.join(results_dir, "schedule_result.json"), ) - - result = _wait_for_file(os.path.join(results_dir, "schedule_result.json")) assert result["handler_tag"] == "source::dailyCleanup::cleanupHandler" assert result["message_id"] is not None assert result["schedule_id"] is not None diff --git a/libs/runtime/ws/ws-redis/Cargo.toml b/libs/runtime/ws/ws-redis/Cargo.toml index bdb1313d..fe3081a8 100644 --- a/libs/runtime/ws/ws-redis/Cargo.toml +++ b/libs/runtime/ws/ws-redis/Cargo.toml @@ -18,6 +18,8 @@ redis = { version = "0.32.3", features = [ "cluster-async", ] } tracing = "0.1.40" +nanoid = "0.4.0" +futures = "0.3.30" [dependencies.celerity_ws_registry] path = "../ws-registry" @@ -25,7 +27,14 @@ path = "../ws-registry" [dependencies.celerity_helpers] path = "../../helpers" +[dev-dependencies.celerity_helpers] +path = "../../helpers" +features = ["test-support"] + [dev-dependencies] +futures = "0.3.30" +axum = { version = "0.8.4", features = ["ws"] } +tokio-tungstenite = "0.23.1" test-log = { version = "0.2.16", features = ["log", "trace"] } pretty_assertions = "1.4.0" coverage-helper = "0.2.2" diff --git a/libs/runtime/ws/ws-redis/src/forwarded.rs b/libs/runtime/ws/ws-redis/src/forwarded.rs new file mode 100644 index 00000000..6599f614 --- /dev/null +++ b/libs/runtime/ws/ws-redis/src/forwarded.rs @@ -0,0 +1,80 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use celerity_helpers::redis::ConnectionWrapper; +use celerity_ws_registry::{errors::WebSocketConnError, registry::ForwardedMessageStore}; + +/// 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. +/// +/// Has to outlast a message's whole life as a sender sees it, which is the +/// acknowledgement timeout multiplied by the attempts allowed. Five minutes +/// leaves room for both to be raised well beyond their defaults. +pub const DEFAULT_FORWARDED_TTL_MS: u64 = 300_000; + +/// What the cluster has already forwarded to its clients. +/// +/// A sender resends a message whose acknowledgement did not arrive, and what +/// went missing may have been the acknowledgement rather than the message. +/// Recording what has been forwarded is how the second copy is recognised. +#[derive(Debug)] +pub struct ForwardedMessages { + conn: ConnectionWrapper, + key_prefix: String, + ttl_ms: u64, +} + +impl ForwardedMessages { + pub fn new(conn: ConnectionWrapper, key_prefix: String, ttl_ms: u64) -> Arc { + Arc::new(Self { + conn, + key_prefix, + ttl_ms, + }) + } + + fn key(&self, message_id: &str) -> String { + format!("{}:msg:{}", self.key_prefix, message_id) + } +} + +#[async_trait] +impl ForwardedMessageStore for ForwardedMessages { + /// Sets the id only where it is not already there, which answers and records + /// in one round trip. + /// + /// A second copy leaves the expiry where it was, so an id is forgotten a + /// fixed time after the message was first forwarded rather than being kept + /// alive by the resends. + async fn record_and_check_forwarded( + &self, + message_id: &str, + ) -> Result { + let recorded = self + .conn + .clone() + .pset_ex_nx(&self.key(message_id), "1", self.ttl_ms) + .await + .map_err(|err| { + WebSocketConnError::ForwardedMessageError(format!( + "could not record a message as forwarded: {err}" + )) + })?; + + Ok(!recorded) + } + + async fn forget_forwarded(&self, message_id: &str) -> Result<(), WebSocketConnError> { + self.conn + .clone() + .del(&self.key(message_id)) + .await + .map_err(|err| { + WebSocketConnError::ForwardedMessageError(format!( + "could not give up the record of a forwarded message: {err}" + )) + })?; + + Ok(()) + } +} diff --git a/libs/runtime/ws/ws-redis/src/lib.rs b/libs/runtime/ws/ws-redis/src/lib.rs index 54d728b0..94ab5489 100644 --- a/libs/runtime/ws/ws-redis/src/lib.rs +++ b/libs/runtime/ws/ws-redis/src/lib.rs @@ -1 +1,4 @@ +pub mod forwarded; +pub mod locations; +pub mod node_group; pub mod pubsub; diff --git a/libs/runtime/ws/ws-redis/src/locations.rs b/libs/runtime/ws/ws-redis/src/locations.rs new file mode 100644 index 00000000..d609ec75 --- /dev/null +++ b/libs/runtime/ws/ws-redis/src/locations.rs @@ -0,0 +1,198 @@ +use std::{ + collections::HashSet, + sync::{Arc, RwLock}, +}; + +use async_trait::async_trait; +use celerity_helpers::redis::ConnectionWrapper; +use celerity_ws_registry::{errors::WebSocketConnError, registry::ConnectionLocationStore}; +use futures::{stream, StreamExt}; +use redis::RedisResult; +use tracing::debug; + +/// Where each connection is, so a message can be published to the one node +/// group holding its client instead of to every node in the cluster. +/// +/// Entries carry an expiry and are refreshed while this node runs, so a node +/// that dies without tidying up leaves nothing behind that would go on +/// attracting messages for connections that died with it. +/// How many of a node's entries are written at once. +const AT_ONCE: usize = 32; + +#[derive(Debug)] +pub struct ConnectionLocations { + conn: ConnectionWrapper, + key_prefix: String, + /// The group this node currently belongs to, which is what its connections + /// are recorded against. + group_id: RwLock, + ttl_ms: u64, + /// The connections this node recorded, so it knows which entries are its to + /// keep alive and to take away. + recorded: RwLock>, +} + +impl ConnectionLocations { + pub fn new( + conn: ConnectionWrapper, + key_prefix: String, + group_id: String, + ttl_ms: u64, + ) -> Arc { + Arc::new(Self { + conn, + key_prefix, + group_id: RwLock::new(group_id), + ttl_ms, + recorded: RwLock::new(HashSet::new()), + }) + } + + /// Reads the group holding a connection, or `None` where nothing has been + /// recorded for it. + pub async fn group_for(&self, connection_id: &str) -> RedisResult> { + let group_id = self.connection().get(&self.key(connection_id)).await?; + Ok(Some(group_id).filter(|group_id| !group_id.is_empty())) + } + + /// Pushes every entry this node holds out to a fresh expiry. + /// + /// One command per entry rather than one request carrying all of them, + /// because connection entries are spread across a cluster's slots by design + /// and a request spanning slots is refused. Several are in flight at once, + /// so the cost is bounded by that rather than by how many entries this node + /// holds. + /// + /// Written again rather than expired again, since the two cost the same and + /// writing also repairs an entry that expired while the node was too busy + /// to say otherwise. + pub async fn refresh(&self) -> RedisResult { + let recorded: Vec = self.recorded.read().unwrap().iter().cloned().collect(); + if recorded.is_empty() { + return Ok(0); + } + + let group_id = self.group(); + let ttl_ms = self.ttl_ms; + let conn = self.conn.clone(); + let results: Vec> = stream::iter( + recorded + .iter() + .map(|connection_id| self.key(connection_id)) + .collect::>(), + ) + .map(|key| { + let mut conn = conn.clone(); + let group_id = group_id.clone(); + async move { conn.pset_ex(&key, &group_id, ttl_ms).await.map(|_| ()) } + }) + .buffer_unordered(AT_ONCE) + .collect() + .await; + + let refreshed = settle(results)?; + debug!( + connections = refreshed, + "refreshed this node's connection entries" + ); + Ok(refreshed) + } + + /// Takes away every entry this node holds, for a node that is shutting down + /// rather than dying. + pub async fn forget_all(&self) -> RedisResult { + let recorded: Vec = self.recorded.write().unwrap().drain().collect(); + if recorded.is_empty() { + return Ok(0); + } + + let conn = self.conn.clone(); + let results: Vec> = stream::iter( + recorded + .iter() + .map(|connection_id| self.key(connection_id)) + .collect::>(), + ) + .map(|key| { + let mut conn = conn.clone(); + async move { conn.del(&key).await.map(|_| ()) } + }) + .buffer_unordered(AT_ONCE) + .collect() + .await; + + settle(results) + } + + /// Points this node's connections at a different group, for a node that had + /// to rejoin. + pub fn set_group(&self, group_id: String) { + *self.group_id.write().unwrap() = group_id; + } + + /// The group this node's connections are currently recorded against. + pub fn group(&self) -> String { + self.group_id.read().unwrap().clone() + } + + fn key(&self, connection_id: &str) -> String { + format!("{}:conn:{}", self.key_prefix, connection_id) + } + + /// A connection of this task's own. Cloning a multiplexed connection shares + /// the one socket, so this costs nothing and saves every lookup queueing + /// behind a lock held by whoever asked first. + fn connection(&self) -> ConnectionWrapper { + self.conn.clone() + } +} + +#[async_trait] +impl ConnectionLocationStore for ConnectionLocations { + async fn record(&self, connection_id: &str) -> Result<(), WebSocketConnError> { + // Taken as this node's before the write, so a write that fails is + // repaired by the next refresh rather than leaving a connection no + // other node can reach for as long as it lasts. + self.recorded + .write() + .unwrap() + .insert(connection_id.to_string()); + let group_id = self.group(); + self.connection() + .pset_ex(&self.key(connection_id), &group_id, self.ttl_ms) + .await + .map_err(location_error)?; + Ok(()) + } + + async fn forget(&self, connection_id: &str) -> Result<(), WebSocketConnError> { + // Forgotten here first, so no later refresh writes the entry back. One + // already under way can still land after the delete, which leaves an + // entry for a connection that has gone until its expiry takes it. That + // costs a message being offered to this node's group rather than to + // every group, and either way nothing holds the connection. + self.recorded.write().unwrap().remove(connection_id); + self.connection() + .del(&self.key(connection_id)) + .await + .map_err(location_error)?; + Ok(()) + } +} + +fn location_error(err: redis::RedisError) -> WebSocketConnError { + WebSocketConnError::ConnectionLocationError(err.to_string()) +} + +/// Counts what succeeded, and returns the first failure once everything has +/// been tried. +/// +/// Each entry stands alone, so one failing is no reason to leave the rest +/// unwritten. +fn settle(results: Vec>) -> RedisResult { + let done = results.iter().filter(|result| result.is_ok()).count(); + for result in results { + result?; + } + Ok(done) +} diff --git a/libs/runtime/ws/ws-redis/src/node_group.rs b/libs/runtime/ws/ws-redis/src/node_group.rs new file mode 100644 index 00000000..12f86edf --- /dev/null +++ b/libs/runtime/ws/ws-redis/src/node_group.rs @@ -0,0 +1,284 @@ +use std::{sync::Arc, time::Duration}; + +use celerity_helpers::redis::ConnectionWrapper; +use nanoid::nanoid; +use redis::RedisResult; +use tokio::{sync::mpsc::Sender, sync::oneshot, task::JoinHandle}; +use tracing::{debug, error, info}; + +use crate::locations::ConnectionLocations; + +/// The prefix the protocol documents, and the fallback for a caller that names +/// nothing of its own. +/// +/// It separates nothing by itself, since it is what any Celerity application +/// would use. Nodes sharing a prefix are one cluster, so two applications on one +/// Redis deployment need prefixes of their own or each will publish messages to +/// the other's nodes for connections they have never heard of. A prefix also has to be the +/// same on every node of an application, which is why it is derived from the +/// application rather than from anything belonging to a node. +pub const DEFAULT_KEY_PREFIX: &str = "celerity"; + +/// The shortest gap between heartbeats, whatever the expiry works out to. +/// +/// A beat is a third of the expiry, so a very short expiry would otherwise ask +/// for a round trip every few milliseconds. Only a test sets one that short, and +/// what it is asking for is a node that looks dead quickly rather than one that +/// spends itself on round trips. +const MIN_HEARTBEAT_MS: u64 = 20; + +/// Decides a group and takes a place in it, without another node being able to +/// count the group in between. +/// +/// Reading the members, deciding, and adding have to happen together. Nodes +/// start together far more often than they start alone, a rolling deploy or a +/// scale-out being the ordinary case, and every one of them reading a group as +/// having room before any of them has taken it would put them all in the same +/// group. +/// +/// A node already in a group stays there, which makes this the heartbeat as +/// well as the join. A node that lapsed and was dropped runs the same path as a +/// node starting, so it takes whatever place is free rather than a place that +/// has to be kept for it. +const JOIN_SCRIPT: &str = include_str!("scripts/join_node_group.lua"); + +/// Gives up a place and takes the group with it where it was the last one in +/// it, without another node being able to join in between. +/// +/// Counting the members and taking an empty group out of the index have to +/// happen together. A node joining between the two would be left holding a +/// group that has just been taken out of the index, which nothing else can find +/// and nothing prunes, so its membership would outlive it. +const LEAVE_SCRIPT: &str = include_str!("scripts/leave_node_group.lua"); + +/// What a node needs to decide which group to join and to stay a member of it. +#[derive(Debug, Clone)] +pub struct NodeGroupConfig { + /// Names this node among the others, and is what an acknowledgement is + /// addressed to. + pub server_node_name: String, + /// How many nodes a group holds before a new one is started. Shared across + /// the cluster, since a group filled to one node's idea of capacity and not + /// another's is not really bounded. + pub capacity: usize, + /// How long this node's liveness key outlives its last refresh. A node that + /// stops refreshing stops counting towards its group's capacity once this + /// runs out, and is dropped from the member set by the next node to look. + pub node_ttl_ms: u64, + /// What every key and channel is named under. Nodes sharing a prefix are + /// one cluster, so this must name the application and must match across its + /// nodes. See [`DEFAULT_KEY_PREFIX`]. + pub key_prefix: String, +} + +/// A node group, and the two channels that carry its traffic. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NodeGroup { + pub id: String, + /// Carries messages for connections held by the group's nodes. + pub channel: String, + /// Mirrors the group's channel and carries only acknowledgements, so a node + /// waiting to hear that a message arrived is not reading every message the + /// group is handling. + pub ack_channel: String, +} + +impl NodeGroup { + /// Names a group's channels from its id, for a caller holding an id and + /// nothing else. + pub fn new(prefix: &str, id: String) -> Self { + Self { + channel: format!("{prefix}:node-group:{id}"), + ack_channel: format!("{prefix}:node-group-ack:{id}"), + id, + } + } +} + +/// What the keys holding group membership are named under. +/// +/// The brace is a Redis Cluster hash tag, which puts every key the join and +/// leave scripts touch in one slot. A script reaching across slots is refused, +/// and these keys are few and small enough that one shard holding them does +/// not have a significant cost. +/// Connection entries are deliberately outside it, since there is one per client +/// and they belong spread across the cluster. +fn meta_prefix(prefix: &str) -> String { + format!("{prefix}:{{group-meta}}") +} + +/// The set holding every node group's id. +pub fn group_index_key(prefix: &str) -> String { + format!("{}:node-groups", meta_prefix(prefix)) +} + +/// The key whose presence says a node is still running, and whose value is the +/// group it belongs to. +pub fn node_key(prefix: &str, server_node_name: &str) -> String { + format!("{}:node:{}", meta_prefix(prefix), server_node_name) +} + +/// Joins the emptiest group with room in it, or starts a new one, or refreshes +/// the place this node already holds. +/// +/// A group's size is its member set, filtered to the members still saying they +/// are running, which reads the same from any Redis node and tells a node that +/// died apart from one that was never there. +pub async fn join_or_create( + conn: &mut ConnectionWrapper, + config: &NodeGroupConfig, +) -> RedisResult { + let index_key = group_index_key(&config.key_prefix); + let meta = meta_prefix(&config.key_prefix); + let capacity = config.capacity.to_string(); + let ttl_ms = config.node_ttl_ms.to_string(); + let new_group_id = nanoid!(); + + let result: Vec = conn + .eval_script( + JOIN_SCRIPT, + &[&index_key], + &[ + &meta, + &config.server_node_name, + &capacity, + &ttl_ms, + &new_group_id, + ], + ) + .await?; + + let group_id = result + .first() + .cloned() + .unwrap_or_else(|| new_group_id.clone()); + match result.get(1).map(String::as_str) { + Some("held") => debug!(node_group = %group_id, "still holding a place in this node group"), + _ if group_id == new_group_id => { + info!(node_group = %group_id, "no node group had room, started a new one") + } + _ => info!(node_group = %group_id, "joined a node group"), + } + + Ok(NodeGroup::new(&config.key_prefix, group_id)) +} + +/// Leaves the group, taking this node's membership and liveness key with it. +/// +/// The alternative is waiting out the TTL, during which the group looks fuller +/// than it is and messages for connections this node no longer holds are still +/// published to it. +pub async fn leave( + conn: &mut ConnectionWrapper, + config: &NodeGroupConfig, + group: &NodeGroup, +) -> RedisResult<()> { + // An empty group is taken out of the index by the same script, since it + // exists only as somewhere for nodes to be. + let removed: i64 = conn + .eval_script( + LEAVE_SCRIPT, + &[&group_index_key(&config.key_prefix)], + &[ + &meta_prefix(&config.key_prefix), + &config.server_node_name, + &group.id, + ], + ) + .await?; + + if removed == 1 { + debug!(node_group = %group.id, "last node left the group, removing it"); + } + + Ok(()) +} + +/// Keeps this node's place and its connection entries alive until it is asked +/// to stop, and leaves the group tidily when it is. +/// +/// Every beat runs the join, so a node dropped from its group while it was slow +/// takes a place again without anything having to keep one for it. The place it +/// gets may be in another group, which is reported on `moved` for the caller to +/// follow with its subscriptions. +pub fn spawn_heartbeat( + mut conn: ConnectionWrapper, + config: NodeGroupConfig, + group: NodeGroup, + locations: Arc, + moved: Sender, + mut shutdown: oneshot::Receiver<()>, +) -> JoinHandle<()> { + // Beating three times inside the expiry means two beats can be lost, to a + // stalled task or a slow round trip, before anything else decides this node + // has gone. + let interval = Duration::from_millis((config.node_ttl_ms / 3).max(MIN_HEARTBEAT_MS)); + + tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval); + // The first tick is immediate, and the keys were just written by + // joining, so it is skipped rather than beating twice at startup. + ticker.tick().await; + let mut group = group; + + loop { + tokio::select! { + _ = ticker.tick() => { + group = beat(&mut conn, &config, group, &locations, &moved).await; + } + _ = &mut shutdown => { + if let Err(err) = leave(&mut conn, &config, &group).await { + error!("failed to leave the node group on shutdown: {err:?}"); + } + if let Err(err) = locations.forget_all().await { + error!( + "failed to take away this node's connection entries on shutdown: \ + {err:?}" + ); + } + info!(node_group = %group.id, "left the node group"); + return; + } + } + } + }) +} + +/// One beat, returning the group this node holds a place in afterwards. +/// +/// A failure is logged and left to the next beat, since a round trip that +/// failed says nothing about whether the next one will. +async fn beat( + conn: &mut ConnectionWrapper, + config: &NodeGroupConfig, + group: NodeGroup, + locations: &Arc, + moved: &Sender, +) -> NodeGroup { + let group = match join_or_create(conn, config).await { + Ok(held) => held, + Err(err) => { + error!("failed to say this node is still running: {err:?}"); + group + } + }; + + if group.id != locations.group() { + info!( + node_group = %group.id, + "this node was dropped from its group and took a place in another one" + ); + // Told before the entries move, so the caller is listening to the new + // group's channel before anything is sent there for this node. + if moved.send(group.clone()).await.is_err() { + error!("nothing is following this node's group any more"); + } + locations.set_group(group.id.clone()); + } + + if let Err(err) = locations.refresh().await { + error!("failed to keep this node's connection entries alive: {err:?}"); + } + + group +} diff --git a/libs/runtime/ws/ws-redis/src/pubsub.rs b/libs/runtime/ws/ws-redis/src/pubsub.rs index 5eb1a339..d6cf3173 100644 --- a/libs/runtime/ws/ws-redis/src/pubsub.rs +++ b/libs/runtime/ws/ws-redis/src/pubsub.rs @@ -1,26 +1,51 @@ -use std::error::Error; +use std::{ + error::Error, + sync::{Arc, RwLock}, + time::Duration, +}; -use celerity_helpers::redis::{get_redis_connection, ConnectionConfig}; +use celerity_helpers::redis::{get_redis_connection, ConnectionConfig, ConnectionWrapper}; use celerity_ws_registry::types::Message; use redis::{FromRedisValue, PushKind}; use serde::{Deserialize, Serialize}; -use tokio::sync::mpsc::{channel, unbounded_channel, Receiver, Sender}; -use tracing::{debug, error}; +use tokio::{ + sync::mpsc::{channel, unbounded_channel, Receiver, Sender}, + time::{interval, MissedTickBehavior}, +}; +use tracing::{debug, error, warn}; -/// Configuration for a Redis connection for the pubsub channel -/// used with the WebSocket connection registry for providing -/// a horizontally scalable WebSocket API that shares messages -/// between nodes in a cluster for a shared multi-client session (e.g. real-time chat). +use crate::{ + locations::ConnectionLocations, + node_group::{group_index_key, node_key, NodeGroup}, +}; + +/// How long to wait before trying again to take up the channels of a group this +/// node has moved into. +/// +/// Short, because the node is missing messages for its own connections until it +/// succeeds. +const RESUBSCRIBE_RETRY_MS: u64 = 500; + +/// How a node reaches the rest of the cluster, and how it is named within it. #[derive(Debug, Clone)] pub struct PubSubConnectionConfig { - // A name for the current server node, - // primarily used to filter out messages that are not for connections - // on the current node. + /// Names this node, and is what other nodes address an acknowledgement to. pub server_node_name: String, - pub channel_name: String, + /// What every key and channel is named under. Must match across the + /// application's nodes, see + /// [`DEFAULT_KEY_PREFIX`](crate::node_group::DEFAULT_KEY_PREFIX). + pub key_prefix: String, pub nodes: Vec, pub password: Option, pub cluster_mode: bool, + /// How long a node stays subscribed to the group it has left after moving + /// to another one. + /// + /// A sender reads where a connection is and publishes a moment later, so + /// there is always a message in flight against a mapping that has just + /// changed. Holding the old subscription for longer than that gap is what + /// stops those being missed. + pub migration_grace_ms: u64, } impl From for ConnectionConfig { @@ -33,138 +58,149 @@ impl From for ConnectionConfig { } } -/// Connects to a Redis server or cluster pubsub channel and returns a -/// receiver and sender to allow for sharing messages between nodes in a cluster -/// for a WebSocket API. +/// Connects a node to its group's channels, returning a sender for messages +/// leaving this node and a receiver for those arriving from other nodes. /// -/// This should be used for both publishing messages and subscribing to -/// messages. This allows for both messages and acknowledgements to be sent -/// to the same channel, the caller is responsible for handling acknowledgements -/// and providing a layer of resiliency for message sharing between nodes. +/// Both acknowledgements and messages travel this way. The registry is +/// responsible for what they mean; this only decides where they go. /// -/// When cluster mode is disabled, only the first node in the provided -/// nodes list will be used. +/// A message is published to the group holding the connection it names, so a +/// node only hears about connections its group might be holding. An +/// acknowledgement is published to the ack channel of the group holding the +/// node that sent the original message, which is read from that node's key +/// rather than remembered per message. /// -/// # Examples +/// `moved` carries a new group when the node has had to take a place in one, +/// and the node subscribes to it before giving up the one it left. /// -/// **Cluster mode** -/// -/// ``` -/// # use celerity_ws_redis::pubsub::connect; +/// # Example /// -/// let (tx, rx) = connect(ConnectionConfig { +/// ```no_run +/// # use std::sync::Arc; +/// # use celerity_helpers::redis::get_redis_connection; +/// # use celerity_ws_redis::{ +/// # locations::ConnectionLocations, +/// # node_group::{join_or_create, NodeGroupConfig, DEFAULT_KEY_PREFIX}, +/// # pubsub::{connect, PubSubConnectionConfig}, +/// # }; +/// # use celerity_ws_registry::registry::{WebSocketConnRegistry, WebSocketConnRegistryConfig}; +/// # async fn example() -> Result<(), Box> { +/// let group_config = NodeGroupConfig { /// server_node_name: "api-node-1".to_string(), -/// channel_name: "celerity_ws_messages".to_string(), -/// nodes: vec!["redis://127.0.0.1:6379/?protocol=3".to_string()], +/// capacity: 5, +/// node_ttl_ms: 30_000, +/// key_prefix: DEFAULT_KEY_PREFIX.to_string(), +/// }; +/// let pubsub_config = PubSubConnectionConfig { +/// server_node_name: group_config.server_node_name.clone(), +/// key_prefix: group_config.key_prefix.clone(), +/// nodes: vec!["redis://127.0.0.1:6379/?protocol=resp3".to_string()], /// password: None, -/// cluster_mode: true, -/// })?; -/// let registry = Arc::new(WebSocketConnRegistry::new( -/// WebSocketConnRegistryConfig { -/// ack_worker_config: None, -/// }, -/// Some(tx), -/// )); -/// registry.start_ack_worker(); -/// registry.listen(rx); +/// cluster_mode: false, +/// migration_grace_ms: 5_000, +/// }; /// -/// /// Do something with the registry ... -/// ``` +/// let mut conn = get_redis_connection(&pubsub_config.clone().into(), None).await?; +/// let group = join_or_create(&mut conn, &group_config).await?; +/// let locations = ConnectionLocations::new( +/// conn.clone(), +/// group_config.key_prefix.clone(), +/// group.id.clone(), +/// group_config.node_ttl_ms, +/// ); /// -/// **Single node mode** -/// ``` -/// # use celerity_ws_redis::pubsub::connect; +/// let (moved_tx, moved_rx) = tokio::sync::mpsc::channel(4); +/// let (tx, rx) = connect(pubsub_config, group, locations, moved_rx).await?; /// -/// let (tx, rx) = connect(ConnectionConfig { -/// server_node_name: "api-node-1".to_string(), -/// channel_name: "celerity_ws_messages".to_string(), -/// nodes: vec!["redis://127.0.0.1:6379/?protocol=resp3".to_string()], -/// password: None, -/// cluster_mode: false, -/// })?; /// let registry = Arc::new(WebSocketConnRegistry::new( /// WebSocketConnRegistryConfig { /// ack_worker_config: None, +/// server_node_name: group_config.server_node_name, /// }, /// Some(tx), /// )); -/// registry.start_ack_worker(); +/// registry.clone().start_ack_worker(); /// registry.listen(rx); +/// # let _ = moved_tx; +/// # Ok(()) +/// # } /// ``` pub async fn connect( conn_config: PubSubConnectionConfig, + group: NodeGroup, + locations: Arc, + mut moved: Receiver, ) -> Result<(Sender, Receiver), Box> { let (redis_tx, mut redis_rx) = unbounded_channel(); let mut conn = get_redis_connection(&conn_config.clone().into(), Some(redis_tx)).await?; - conn.subscribe(&conn_config.channel_name).await?; + conn.subscribe(&group.channel).await?; + conn.subscribe(&group.ack_channel).await?; - // Internal channel used to forward messages to the Redis channel - // that is used to send WebSocket messages to other nodes in the cluster. + // Internal channel used to forward messages to the channels that carry + // WebSocket messages to other nodes in the cluster. let (caller_tx, mut internal_rx) = channel(1024); - // Receiver from which the caller can receive messages from the Redis channel. + // Receiver from which the caller can receive messages from other nodes. let (internal_tx, caller_rx) = channel(1024); tokio::spawn(async move { + let mut group = group; + // Read by the tasks giving up the channels of groups this node has + // left, so one of them waiting out its grace period can tell that the + // node has since come back to the group it was about to give up. + let listening_to = Arc::new(RwLock::new(group.id.clone())); + // The group this node has taken a place in but is not yet listening to. + // Held until it is subscribed to, since the connection entries have + // already moved and messages are being published there. + let mut joining: Option = None; + let mut retry = interval(Duration::from_millis(RESUBSCRIBE_RETRY_MS)); + retry.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { tokio::select! { - Some(message) = redis_rx.recv() => { - debug!("received message from redis channel {}", conn_config.channel_name); - if message.kind == PushKind::Message { - match String::from_redis_value(&message.data[1]) { - Ok(value) => { - let wrapped_message: MessageWithSourceNode = match serde_json::from_str(&value) { - Ok(wrapped_message) => wrapped_message, - Err(e) => { - error!("error parsing message from redis channel {}: {}", conn_config.channel_name, e); - continue; - } - }; - if wrapped_message.source_node != conn_config.server_node_name { - // Messages will only be forwarded if they are not from the current node. - // Acknowledgements for messages that were not sent by the current node - // are ignored. - let should_send = match wrapped_message.message.clone() { - Message::Ack(ack_message) => { - ack_message.message_node == conn_config.server_node_name - } - Message::WebSocket(_) => true, - }; - if should_send - && (internal_tx.send(wrapped_message.message).await).is_err() { - error!("receiver dropped, stopping redis listener"); - break; - } - } - } - Err(e) => { - error!("error parsing message from redis channel {}: {}", conn_config.channel_name, e); - } - } + Some(push) = redis_rx.recv() => { + if push.kind != PushKind::Message { + continue; } - } - Some(message) = internal_rx.recv() => { - debug!("received message to forward to channel {}", conn_config.channel_name); - let wrapped_message = MessageWithSourceNode { - source_node: conn_config.server_node_name.clone(), - message, + let Ok(raw) = String::from_redis_value(&push.data[1]) else { + error!("could not read a message from a node group channel"); + continue; }; - let wrapped_message_json = match serde_json::to_string(&wrapped_message) { - Ok(json) => json, - Err(e) => { - error!("error serializing message to json: {e:?}"); + let wrapped: MessageWithSourceNode = match serde_json::from_str(&raw) { + Ok(wrapped) => wrapped, + Err(err) => { + error!("could not parse a message from a node group channel: {err}"); continue; } }; - let res: Result = conn.publish(&conn_config.channel_name, wrapped_message_json).await; - if let Err(e) = res { - error!("error publishing message to channel: {e:?}"); + // A node's own messages come back to it, since it is + // subscribed to the channel it publishes on. + if wrapped.source_node == conn_config.server_node_name { + continue; + } + // An acknowledgement is for the node that sent the message, + // and the rest of the group is only overhearing it. + let for_this_node = match &wrapped.message { + Message::Ack(ack) => ack.message_node == conn_config.server_node_name, + Message::WebSocket(_) => true, + }; + if for_this_node && internal_tx.send(wrapped.message).await.is_err() { + error!("receiver dropped, stopping the node group listener"); + break; } } - else => { - break; + Some(message) = internal_rx.recv() => { + publish(&mut conn, &conn_config, &locations, message).await; + } + Some(joined) = moved.recv() => { + joining = Some(joined); + follow(&mut conn, &mut joining, &mut group, &listening_to, &conn_config).await; + } + _ = retry.tick(), if joining.is_some() => { + follow(&mut conn, &mut joining, &mut group, &listening_to, &conn_config).await; } + else => break, } } }); @@ -172,6 +208,185 @@ pub async fn connect( Ok((caller_tx, caller_rx)) } +/// Takes up the channels of the group this node has moved into, and gives up +/// the ones it left. +/// +/// A node that has moved is already having messages published to the new +/// group, since its connection entries moved with it. Staying on the old +/// channels would lose every one of them, and nothing asks a second time +/// because the node is a member of the new group as far as anything else can +/// tell. So a move that could not be subscribed to is left outstanding to be +/// tried again rather than given up on. +async fn follow( + conn: &mut ConnectionWrapper, + joining: &mut Option, + group: &mut NodeGroup, + listening_to: &Arc>, + conn_config: &PubSubConnectionConfig, +) { + let Some(joined) = joining.clone() else { + return; + }; + + // Subscribed before the old one is given up, so the node is listening to + // both while any sender still holds the mapping it read a moment ago. + if let Err(err) = subscribe_to(conn, &joined).await { + error!( + node_group = %joined.id, + "could not subscribe to the group this node moved into, trying again in a moment: \ + {err}" + ); + return; + } + *joining = None; + + debug!(node_group = %joined.id, "following this node into another group"); + *listening_to.write().unwrap() = joined.id.clone(); + leave_behind( + conn.clone(), + std::mem::replace(group, joined), + listening_to.clone(), + conn_config.migration_grace_ms, + ); +} + +async fn subscribe_to(conn: &mut ConnectionWrapper, group: &NodeGroup) -> redis::RedisResult<()> { + conn.subscribe(&group.channel).await?; + conn.subscribe(&group.ack_channel).await +} + +/// Gives up the channels of a group this node has left, after waiting out the +/// grace period. +/// +/// The wait covers a sender that read the old mapping just before it changed +/// and published a moment later. +/// +/// The group is read again once the wait is over rather than trusted from when +/// this was scheduled, because a node can be dropped from a group and take a +/// place back in the one it came from within a single grace period, and giving +/// up those channels would leave it deaf to the group it is in. +fn leave_behind( + mut conn: ConnectionWrapper, + group: NodeGroup, + listening_to: Arc>, + grace_ms: u64, +) { + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(grace_ms)).await; + + let back_in_it = *listening_to.read().unwrap() == group.id; + if back_in_it { + debug!( + node_group = %group.id, + "this node is back in the group it left, keeping its channels" + ); + return; + } + + for channel in [&group.channel, &group.ack_channel] { + if let Err(err) = conn.unsubscribe(channel).await { + error!(channel = %channel, "failed to give up a channel after moving group: {err}"); + } + } + debug!(node_group = %group.id, "gave up the group this node left"); + }); +} + +/// Sends a message to the nodes that might be able to act on it. +async fn publish( + conn: &mut ConnectionWrapper, + conn_config: &PubSubConnectionConfig, + locations: &Arc, + message: Message, +) { + let channels = match &message { + Message::WebSocket(websocket_message) => { + match locations.group_for(&websocket_message.connection_id).await { + Ok(Some(group_id)) => { + vec![NodeGroup::new(&conn_config.key_prefix, group_id).channel] + } + Ok(None) => { + // Nothing has recorded the connection, which a client that + // connected a moment ago looks like. Every group hears it + // rather than the message being dropped for a client that + // is there. + debug!( + connection_id = %websocket_message.connection_id, + "no node group holds this connection, telling all of them" + ); + match every_group_channel(conn, &conn_config.key_prefix).await { + Ok(channels) => channels, + Err(err) => { + error!("could not read the node groups: {err}"); + return; + } + } + } + Err(err) => { + error!("could not read where a connection is: {err}"); + return; + } + } + } + Message::Ack(ack) => { + let node = node_key(&conn_config.key_prefix, &ack.message_node); + match conn.get(&node).await { + Ok(group_id) if !group_id.is_empty() => { + vec![NodeGroup::new(&conn_config.key_prefix, group_id).ack_channel] + } + Ok(_) => { + // The node that sent the message has gone, so nothing is + // waiting to hear that its message arrived. + debug!( + node = %ack.message_node, + "not acknowledging to a node that has stopped running" + ); + return; + } + Err(err) => { + error!("could not read which group a node belongs to: {err}"); + return; + } + } + } + }; + + let wrapped = MessageWithSourceNode { + source_node: conn_config.server_node_name.clone(), + message, + }; + let body = match serde_json::to_string(&wrapped) { + Ok(body) => body, + Err(err) => { + error!("could not serialise a message for another node: {err}"); + return; + } + }; + + if channels.is_empty() { + warn!("there are no node groups to send to, so a message has nowhere to go"); + return; + } + + for channel in channels { + if let Err(err) = conn.publish(&channel, body.clone()).await { + error!(channel = %channel, "failed to send a message to a node group: {err}"); + } + } +} + +/// Every group's channel, for a message that cannot be narrowed to one of them. +async fn every_group_channel( + conn: &mut ConnectionWrapper, + key_prefix: &str, +) -> redis::RedisResult> { + let group_ids = conn.smembers(&group_index_key(key_prefix)).await?; + Ok(group_ids + .into_iter() + .map(|group_id| NodeGroup::new(key_prefix, group_id).channel) + .collect()) +} + #[derive(Debug, Clone, Serialize, Deserialize)] struct MessageWithSourceNode { source_node: String, diff --git a/libs/runtime/ws/ws-redis/src/scripts/join_node_group.lua b/libs/runtime/ws/ws-redis/src/scripts/join_node_group.lua new file mode 100644 index 00000000..784eb326 --- /dev/null +++ b/libs/runtime/ws/ws-redis/src/scripts/join_node_group.lua @@ -0,0 +1,47 @@ +local index_key = KEYS[1] +local meta = ARGV[1] +local node = ARGV[2] +local capacity = tonumber(ARGV[3]) +local ttl_ms = tonumber(ARGV[4]) +local new_group_id = ARGV[5] + +local node_key = meta .. ':node:' .. node +local emptiest_id = nil +local emptiest_count = nil + +for _, group_id in ipairs(redis.call('SMEMBERS', index_key)) do + local members_key = meta .. ':node-group-members:' .. group_id + local live = 0 + local holds_this_node = false + + for _, member in ipairs(redis.call('SMEMBERS', members_key)) do + if member == node then + holds_this_node = true + live = live + 1 + elseif redis.call('EXISTS', meta .. ':node:' .. member) == 1 then + live = live + 1 + else + redis.call('SREM', members_key, member) + end + end + + if holds_this_node then + redis.call('SET', node_key, group_id, 'PX', ttl_ms) + return { group_id, 'held' } + end + + if live < capacity and (emptiest_count == nil or live < emptiest_count) then + emptiest_id = group_id + emptiest_count = live + end +end + +local group_id = emptiest_id +if group_id == nil then + group_id = new_group_id + redis.call('SADD', index_key, group_id) +end + +redis.call('SADD', meta .. ':node-group-members:' .. group_id, node) +redis.call('SET', node_key, group_id, 'PX', ttl_ms) +return { group_id, 'joined' } diff --git a/libs/runtime/ws/ws-redis/src/scripts/leave_node_group.lua b/libs/runtime/ws/ws-redis/src/scripts/leave_node_group.lua new file mode 100644 index 00000000..e9a84d3b --- /dev/null +++ b/libs/runtime/ws/ws-redis/src/scripts/leave_node_group.lua @@ -0,0 +1,19 @@ +local index_key = KEYS[1] +local meta = ARGV[1] +local node = ARGV[2] +local group_id = ARGV[3] + +local members_key = meta .. ':node-group-members:' .. group_id + +redis.call('SREM', members_key, node) +redis.call('DEL', meta .. ':node:' .. node) + +-- Counted in the same step that takes the group out of the index, so a node +-- joining cannot land in a group between the two and be left in one nothing +-- else can find. +if redis.call('SCARD', members_key) == 0 then + redis.call('SREM', index_key, group_id) + return 1 +end + +return 0 diff --git a/libs/runtime/ws/ws-redis/tests/cluster_test.rs b/libs/runtime/ws/ws-redis/tests/cluster_test.rs new file mode 100644 index 00000000..a14cd743 --- /dev/null +++ b/libs/runtime/ws/ws-redis/tests/cluster_test.rs @@ -0,0 +1,490 @@ +//! Two nodes serving real clients over one Redis deployment, which is the shape a +//! deployment has. The other tests here take the layers apart; these put them +//! together and let the registry decide what happens. + +use std::{ + net::{Ipv4Addr, SocketAddr}, + sync::Arc, + time::Duration, +}; + +use axum::{ + extract::{ + ws::{WebSocket, WebSocketUpgrade}, + State, + }, + response::Response, + routing::get, + Router, +}; +use celerity_helpers::{ + redis::ConnectionWrapper, + testing::{redis_config, redis_connection}, +}; + +use celerity_ws_redis::{ + forwarded::ForwardedMessages, + locations::ConnectionLocations, + node_group::{join_or_create, node_key, NodeGroupConfig}, + pubsub::{connect, PubSubConnectionConfig}, +}; +use celerity_ws_registry::{ + errors::WebSocketConnError, + registry::{ + SendContext, WebSocketConnRegistry, WebSocketConnRegistryConfig, WebSocketRegistrySend, + }, + types::{AckWorkerConfig, MessageType}, +}; +use futures::StreamExt; +use nanoid::nanoid; +use tokio::sync::{mpsc::channel, Mutex}; +use tokio_tungstenite::tungstenite; + +/// Clears anything a previous run left behind under a prefix, including the +/// message ids the run will use. +/// +/// A record of a forwarded message outlives the run that wrote it, so without +/// this a second run inside the window treats its first delivery as a duplicate +/// and delivers nothing. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str, message_ids: &[&str]) { + for message_id in message_ids { + conn.del(&format!("{prefix}:msg:{message_id}")) + .await + .unwrap(); + } + + let index_key = format!("{prefix}:{{group-meta}}:node-groups"); + for group_id in conn.smembers(&index_key).await.unwrap() { + let members_key = format!("{prefix}:{{group-meta}}:node-group-members:{group_id}"); + for member in conn.smembers(&members_key).await.unwrap() { + conn.del(&node_key(prefix, &member)).await.unwrap(); + } + conn.del(&members_key).await.unwrap(); + } + conn.del(&index_key).await.unwrap(); +} + +/// A node of the cluster, serving clients and joined up to the others. +struct ClusterNode { + registry: Arc, + addr: SocketAddr, + group_id: String, + /// Held for the life of the node. Dropping it would close the channel the + /// pubsub task watches for a group change, ending that arm of its select. + _moved: tokio::sync::mpsc::Sender, +} + +/// Starts a node with everything a deployment wires up, in the order +/// `Application::run` wires it. +async fn start_node(prefix: &str, name: &str, capacity: usize) -> ClusterNode { + let mut conn = redis_connection().await; + let group_config = NodeGroupConfig { + server_node_name: name.to_string(), + capacity, + node_ttl_ms: 30_000, + key_prefix: prefix.to_string(), + }; + let group = join_or_create(&mut conn, &group_config).await.unwrap(); + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + group.id.clone(), + group_config.node_ttl_ms, + ); + + let registry = Arc::new(WebSocketConnRegistry::new( + WebSocketConnRegistryConfig { + // Short enough that a test can watch a message run out of attempts. + ack_worker_config: Some(AckWorkerConfig { + message_action_check_interval_ms: Some(20), + message_timeout_ms: Some(100), + max_attempts: Some(3), + }), + server_node_name: name.to_string(), + }, + None, + )); + + let (moved_tx, moved_rx) = channel(4); + let (broadcaster, from_other_nodes) = connect( + PubSubConnectionConfig { + server_node_name: name.to_string(), + key_prefix: prefix.to_string(), + nodes: redis_config().nodes, + password: redis_config().password, + cluster_mode: redis_config().cluster_mode, + migration_grace_ms: 5_000, + }, + group.clone(), + locations.clone(), + moved_rx, + ) + .await + .unwrap(); + + registry.set_locations(locations).unwrap(); + registry + .set_forwarded_messages(ForwardedMessages::new( + conn.clone(), + prefix.to_string(), + 30_000, + )) + .unwrap(); + registry.set_broadcaster(broadcaster).unwrap(); + registry.clone().start_ack_worker(); + registry.clone().listen(from_other_nodes); + + let app: Router = Router::new() + .route("/ws", get(serve_client)) + .with_state(registry.clone()); + let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) + .await + .unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + ClusterNode { + registry, + addr, + group_id: group.id, + _moved: moved_tx, + } +} + +async fn serve_client( + State(registry): State>, + ws: WebSocketUpgrade, +) -> Response { + ws.on_upgrade(move |socket| handle_client(socket, registry)) +} + +/// What a node does for a client, cut down to the registration either side of a +/// read loop. +async fn handle_client(socket: WebSocket, registry: Arc) { + let (socket_tx, mut socket_rx) = socket.split(); + let connection_id = nanoid!(); + registry + .register_connection(connection_id.clone(), Arc::new(Mutex::new(socket_tx))) + .await; + + while let Some(Ok(_)) = socket_rx.next().await {} + + registry.deregister_connection(connection_id).await; +} + +async fn connect_client( + node: &ClusterNode, +) -> ( + tokio_tungstenite::WebSocketStream>, + String, +) { + let before: Vec = node + .registry + .get_connections() + .into_iter() + .map(|(id, _)| id) + .collect(); + let addr = node.addr; + let (socket, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let now: Vec = node + .registry + .get_connections() + .into_iter() + .map(|(id, _)| id) + .collect(); + if let Some(id) = now.into_iter().find(|id| !before.contains(id)) { + return (socket, id); + } + assert!( + tokio::time::Instant::now() < deadline, + "the connection should have been registered" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// A message for a client held by another node reaches it, and the sender hears +/// that it arrived. +#[test_log::test(tokio::test)] +async fn test_a_message_reaches_a_client_held_by_another_node() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-delivery"; + clear(&mut conn, prefix, &["m-1"]).await; + + // A group each, so the message is routed rather than overheard. + let sender = start_node(prefix, "api-node-1", 1).await; + let holder = start_node(prefix, "api-node-2", 1).await; + assert_ne!(sender.group_id, holder.group_id); + + let (mut client, connection_id) = connect_client(&holder).await; + + let sent = sender + .registry + .send_message( + connection_id, + "m-1".to_string(), + MessageType::Json, + r#"{"event":"update"}"#.to_string(), + Some(SendContext { + // Waiting on the other node to say it took the message on, + // which is the whole point of sending it this way. + wait_for_ack: true, + caller: None, + inform_clients: vec![], + }), + ) + .await; + assert!( + sent.is_ok(), + "the node holding the client should have acknowledged the message, got {sent:?}" + ); + + let received = tokio::time::timeout(Duration::from_secs(5), client.next()) + .await + .expect("the client should have been sent the message") + .unwrap() + .unwrap(); + assert_eq!( + received, + tungstenite::Message::Text(r#"{"event":"update"}"#.to_string()) + ); +} + +/// A message for a client no node holds is declared lost, and the clients named +/// are told. +#[test_log::test(tokio::test)] +async fn test_a_message_for_a_client_nobody_holds_is_declared_lost() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-loss"; + clear(&mut conn, prefix, &["m-1"]).await; + + let sender = start_node(prefix, "api-node-1", 1).await; + let _other = start_node(prefix, "api-node-2", 1).await; + + // Connected to the sending node, so it is somewhere the loss can be + // reported to. + let (mut watcher, watcher_id) = connect_client(&sender).await; + + // Bounded, because waiting on an acknowledgement that never comes and is + // never given up on would hang rather than fail. + let sent = tokio::time::timeout( + Duration::from_secs(10), + sender.registry.send_message( + "a-client-that-is-not-here".to_string(), + "m-1".to_string(), + MessageType::Json, + r#"{"event":"update"}"#.to_string(), + Some(SendContext { + wait_for_ack: true, + caller: Some("test-caller".to_string()), + inform_clients: vec![watcher_id], + }), + ), + ) + .await + .expect("a message nobody takes should run out of attempts rather than be waited on forever"); + assert!( + matches!(sent, Err(WebSocketConnError::MessageLost(ref id)) if id == "m-1"), + "a message nobody can take should be declared lost, got {sent:?}" + ); + + let received = tokio::time::timeout(Duration::from_secs(5), watcher.next()) + .await + .expect("the client should have been told about the lost message") + .unwrap() + .unwrap(); + let tungstenite::Message::Binary(bytes) = received else { + panic!("expected a binary lost message event, got {received:?}"); + }; + assert_eq!(bytes[..4], [0x1, 0x3, 0x0, 0x0]); + let body: serde_json::Value = serde_json::from_slice(&bytes[4..]).unwrap(); + assert_eq!(body["messageId"], "m-1"); + assert_eq!(body["caller"], "test-caller"); +} + +/// A client's whereabouts are written when it connects and taken away when it +/// goes, which is what lets the other nodes find it and stop trying. +#[test_log::test(tokio::test)] +async fn test_a_client_is_findable_while_it_is_connected() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-locations"; + clear(&mut conn, prefix, &[]).await; + + let node = start_node(prefix, "api-node-1", 1).await; + let (mut client, connection_id) = connect_client(&node).await; + + // Waited on rather than read once, because a connection is put in the + // node's own map before the record of where it is has been written, and + // connecting only waits for the first of those. + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let recorded: String = conn + .get(&format!("{prefix}:conn:{connection_id}")) + .await + .unwrap(); + if recorded == node.group_id { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "a connected client should be recorded against the group holding it, found \ + {recorded:?}" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + + client.close(None).await.unwrap(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while conn + .exists(&format!("{prefix}:conn:{connection_id}")) + .await + .unwrap() + { + assert!( + tokio::time::Instant::now() < deadline, + "a client that has gone should stop being findable" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// A message resent because its acknowledgement went missing is acknowledged +/// again and delivered once. +/// +/// The two halves matter equally. Delivering twice is the duplicate this +/// avoids; staying silent would have the sender run out of attempts and report +/// a message that did arrive as lost. +#[test_log::test(tokio::test)] +async fn test_a_resent_message_is_acknowledged_again_and_delivered_once() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-duplicates"; + clear(&mut conn, prefix, &["m-1"]).await; + + let sender = start_node(prefix, "api-node-1", 1).await; + let holder = start_node(prefix, "api-node-2", 1).await; + assert_ne!(sender.group_id, holder.group_id); + + let (mut client, connection_id) = connect_client(&holder).await; + + // The same id twice, which is what the sender does when it hears nothing + // back in time. + for attempt in 0..2 { + let sent = sender + .registry + .send_message( + connection_id.clone(), + "m-1".to_string(), + MessageType::Json, + r#"{"event":"update"}"#.to_string(), + Some(SendContext { + wait_for_ack: true, + caller: None, + inform_clients: vec![], + }), + ) + .await; + assert!( + sent.is_ok(), + "attempt {attempt} should have been acknowledged, got {sent:?}" + ); + } + + let received = tokio::time::timeout(Duration::from_secs(5), client.next()) + .await + .expect("the client should have been sent the message") + .unwrap() + .unwrap(); + assert_eq!( + received, + tungstenite::Message::Text(r#"{"event":"update"}"#.to_string()) + ); + + assert!( + tokio::time::timeout(Duration::from_millis(500), client.next()) + .await + .is_err(), + "the client should have been sent the message once, not once per attempt" + ); +} + +/// A message the holding node could not send is not left recorded as one it +/// forwarded. +/// +/// The record is written before the message goes out, since two copies arriving +/// together must not both find it absent. A copy that then fails to send has to +/// give the record back, or the next attempt is recognised as a duplicate and +/// acknowledged without ever reaching the client, which reports a message as +/// delivered that nobody received. +#[test_log::test(tokio::test)] +async fn test_a_message_that_could_not_be_sent_is_not_recorded_as_forwarded() { + let mut conn = redis_connection().await; + let prefix = "test-cluster-undelivered"; + clear(&mut conn, prefix, &["m-1"]).await; + + let sender = start_node(prefix, "api-node-1", 1).await; + let holder = start_node(prefix, "api-node-2", 1).await; + assert_ne!(sender.group_id, holder.group_id); + + let (mut client, connection_id) = connect_client(&holder).await; + + // Refused by the holding node when it comes to make a frame of it, which + // is a delivery that fails after the message has been taken as forwarded. + let sent = tokio::time::timeout( + Duration::from_secs(10), + sender.registry.send_message( + connection_id.clone(), + "m-1".to_string(), + MessageType::Binary, + "not base64 at all".to_string(), + Some(SendContext { + wait_for_ack: true, + caller: None, + inform_clients: vec![], + }), + ), + ) + .await + .expect("a message that cannot be sent should run out of attempts rather than hang"); + assert!( + matches!(sent, Err(WebSocketConnError::MessageLost(ref id)) if id == "m-1"), + "a message that never reached its client should be declared lost, got {sent:?}" + ); + + assert!( + !conn.exists(&format!("{prefix}:msg:m-1")).await.unwrap(), + "a message that was not sent should not be left recorded as forwarded" + ); + + // The same id again, as a sender retrying at the application level would. + // It has to be treated as a first delivery rather than a duplicate. + sender + .registry + .send_message( + connection_id, + "m-1".to_string(), + MessageType::Json, + r#"{"event":"second-attempt"}"#.to_string(), + None, + ) + .await + .unwrap(); + + let received = tokio::time::timeout(Duration::from_secs(5), client.next()) + .await + .expect("the client should have been sent the message on the second attempt") + .unwrap() + .unwrap(); + assert_eq!( + received, + tungstenite::Message::Text(r#"{"event":"second-attempt"}"#.into()), + "a message that failed to send once should still reach its client" + ); +} diff --git a/libs/runtime/ws/ws-redis/tests/forwarded_test.rs b/libs/runtime/ws/ws-redis/tests/forwarded_test.rs new file mode 100644 index 00000000..a30786b8 --- /dev/null +++ b/libs/runtime/ws/ws-redis/tests/forwarded_test.rs @@ -0,0 +1,68 @@ +use std::time::Duration; + +use celerity_helpers::testing::redis_connection; +use celerity_ws_redis::forwarded::ForwardedMessages; +use celerity_ws_registry::registry::ForwardedMessageStore; + +/// The first node to forward a message records it, and any node asking +/// afterwards is told it has already gone out. +#[test_log::test(tokio::test)] +async fn test_a_message_is_recognised_after_it_has_been_forwarded() { + let mut conn = redis_connection().await; + let prefix = "test-forwarded-recognise"; + conn.del(&format!("{prefix}:msg:m-1")).await.unwrap(); + + let forwarded = ForwardedMessages::new(conn.clone(), prefix.to_string(), 10_000); + + assert!( + !forwarded.record_and_check_forwarded("m-1").await.unwrap(), + "a message nothing has forwarded should be sent" + ); + assert!( + forwarded.record_and_check_forwarded("m-1").await.unwrap(), + "a message already forwarded should be recognised" + ); + + // Another node, which is the case that matters as a resend arrives wherever + // the connection is now, not necessarily where it was. + let elsewhere = ForwardedMessages::new(redis_connection().await, prefix.to_string(), 10_000); + assert!(elsewhere.record_and_check_forwarded("m-1").await.unwrap()); + + assert!( + !forwarded.record_and_check_forwarded("m-2").await.unwrap(), + "a different message should be its own" + ); + conn.del(&format!("{prefix}:msg:m-1")).await.unwrap(); + conn.del(&format!("{prefix}:msg:m-2")).await.unwrap(); +} + +/// A message is forgotten a fixed time after it was first forwarded, and a +/// resend does not keep it alive. +/// +/// An entry kept alive by the resends would outlive its usefulness and hold +/// memory for as long as the resends continued. +#[test_log::test(tokio::test)] +async fn test_a_forwarded_message_is_forgotten_on_its_own_schedule() { + let mut conn = redis_connection().await; + let prefix = "test-forwarded-expiry"; + conn.del(&format!("{prefix}:msg:m-1")).await.unwrap(); + + let forwarded = ForwardedMessages::new(conn.clone(), prefix.to_string(), 400); + assert!(!forwarded.record_and_check_forwarded("m-1").await.unwrap()); + + tokio::time::sleep(Duration::from_millis(250)).await; + assert!( + forwarded.record_and_check_forwarded("m-1").await.unwrap(), + "the message should still be recognised while its record lives" + ); + + // Past the original expiry, but only 250ms past the second call, which + // would still be inside the window if that call had reset it. + tokio::time::sleep(Duration::from_millis(250)).await; + assert!( + !forwarded.record_and_check_forwarded("m-1").await.unwrap(), + "the record should expire on the schedule set when the message was first forwarded" + ); + + conn.del(&format!("{prefix}:msg:m-1")).await.unwrap(); +} diff --git a/libs/runtime/ws/ws-redis/tests/locations_test.rs b/libs/runtime/ws/ws-redis/tests/locations_test.rs new file mode 100644 index 00000000..ddbc6358 --- /dev/null +++ b/libs/runtime/ws/ws-redis/tests/locations_test.rs @@ -0,0 +1,281 @@ +use std::time::Duration; + +use celerity_helpers::{redis::ConnectionWrapper, testing::redis_connection}; + +use celerity_ws_redis::{ + locations::ConnectionLocations, + node_group::{join_or_create, node_key, spawn_heartbeat, NodeGroup, NodeGroupConfig}, +}; +use celerity_ws_registry::registry::ConnectionLocationStore; +use tokio::sync::mpsc::{channel, Receiver}; + +fn config(prefix: &str, node: &str, node_ttl_ms: u64) -> NodeGroupConfig { + NodeGroupConfig { + server_node_name: node.to_string(), + capacity: 5, + node_ttl_ms, + key_prefix: prefix.to_string(), + } +} + +/// Clears anything a previous run left behind under a prefix, since a test that +/// fails never reaches its own cleanup. +/// +/// The connections are named rather than matched, because their entries are +/// spread across a cluster's slots by design and no one request reaches all of +/// them. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str, connection_ids: &[&str]) { + for connection_id in connection_ids { + conn.del(&format!("{prefix}:conn:{connection_id}")) + .await + .unwrap(); + } + + let index_key = format!("{prefix}:{{group-meta}}:node-groups"); + for group_id in conn.smembers(&index_key).await.unwrap() { + let members_key = format!("{prefix}:{{group-meta}}:node-group-members:{group_id}"); + for member in conn.smembers(&members_key).await.unwrap() { + conn.del(&node_key(prefix, &member)).await.unwrap(); + } + conn.del(&members_key).await.unwrap(); + } + conn.del(&index_key).await.unwrap(); +} + +async fn members(conn: &mut ConnectionWrapper, prefix: &str, group: &NodeGroup) -> Vec { + conn.smembers(&format!( + "{prefix}:{{group-meta}}:node-group-members:{}", + group.id + )) + .await + .unwrap() +} + +/// A heartbeat and the channel it reports a group change on. +fn heartbeat( + conn: ConnectionWrapper, + node_config: NodeGroupConfig, + group: NodeGroup, + locations: std::sync::Arc, +) -> ( + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle<()>, + Receiver, +) { + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let (moved_tx, moved_rx) = channel(4); + let handle = spawn_heartbeat(conn, node_config, group, locations, moved_tx, shutdown_rx); + (shutdown_tx, handle, moved_rx) +} + +/// A connection is recorded against the group holding it, and reading it back +/// is what tells a sender where to publish. +#[test_log::test(tokio::test)] +async fn test_a_connection_is_found_where_it_was_recorded() { + let mut conn = redis_connection().await; + let prefix = "test-locations-record"; + clear(&mut conn, prefix, &["conn-1"]).await; + + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + "group-1".to_string(), + 10_000, + ); + + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + None, + "a connection nothing has recorded should not be claimed by a group" + ); + + locations.record("conn-1").await.unwrap(); + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + Some("group-1".to_string()) + ); + + locations.forget("conn-1").await.unwrap(); + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + None, + "a connection that has gone should not still be claimed" + ); +} + +/// An entry nothing keeps alive expires, which is what stops a node that died +/// receiving messages for connections that died with it. +#[test_log::test(tokio::test)] +async fn test_an_entry_nothing_refreshes_expires() { + let mut conn = redis_connection().await; + let prefix = "test-locations-expiry"; + clear(&mut conn, prefix, &["conn-1"]).await; + + let locations = + ConnectionLocations::new(conn.clone(), prefix.to_string(), "group-1".to_string(), 200); + locations.record("conn-1").await.unwrap(); + + tokio::time::sleep(Duration::from_millis(400)).await; + assert_eq!(locations.group_for("conn-1").await.unwrap(), None); + + // Refreshing after the entry has gone puts it back, since this node still + // holds the connection whatever Redis has forgotten. + assert_eq!(locations.refresh().await.unwrap(), 1); + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + Some("group-1".to_string()) + ); +} + +/// The heartbeat keeps everything this node wrote alive, past the point where +/// any of it would have expired on its own. +#[test_log::test(tokio::test)] +async fn test_the_heartbeat_keeps_a_node_and_its_connections_alive() { + let mut conn = redis_connection().await; + let prefix = "test-heartbeat-alive"; + clear(&mut conn, prefix, &["conn-1"]).await; + + let node_config = config(prefix, "node-1", 300); + let group = join_or_create(&mut conn, &node_config).await.unwrap(); + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + group.id.clone(), + node_config.node_ttl_ms, + ); + locations.record("conn-1").await.unwrap(); + + let (shutdown_tx, handle, _moved) = heartbeat( + conn.clone(), + node_config.clone(), + group.clone(), + locations.clone(), + ); + + // Comfortably past the expiry, so anything still there is there because it + // was refreshed rather than because it had not run out yet. + tokio::time::sleep(Duration::from_millis(900)).await; + assert!( + conn.exists(&node_key(prefix, "node-1")).await.unwrap(), + "the node should still be saying it is running" + ); + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + Some(group.id.clone()), + "the connection should still be recorded against its group" + ); + + shutdown_tx.send(()).unwrap(); + handle.await.unwrap(); +} + +/// A node dropped from its group while it was slow takes a place again on the +/// next beat, rather than running on as a member of nothing. +/// +/// The group it left still has room, so it lands back in the same one and its +/// subscriptions go on being the right ones. +#[test_log::test(tokio::test)] +async fn test_a_node_dropped_from_its_group_rejoins_it() { + let mut conn = redis_connection().await; + let prefix = "test-heartbeat-rejoin"; + clear(&mut conn, prefix, &["conn-1"]).await; + + let node_config = config(prefix, "node-1", 300); + let group = join_or_create(&mut conn, &node_config).await.unwrap(); + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + group.id.clone(), + node_config.node_ttl_ms, + ); + + let (shutdown_tx, handle, _moved) = heartbeat( + conn.clone(), + node_config.clone(), + group.clone(), + locations.clone(), + ); + + // What another node would have done on finding this one's liveness key + // expired. + conn.srem( + &format!("{prefix}:{{group-meta}}:node-group-members:{}", group.id), + "node-1", + ) + .await + .unwrap(); + + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!( + members(&mut conn, prefix, &group).await, + vec!["node-1".to_string()], + "the node should have taken a place again, in the group it was already using" + ); + + shutdown_tx.send(()).unwrap(); + handle.await.unwrap(); +} + +/// Shutting down takes the node's membership and its connections away at once, +/// rather than leaving the group looking fuller than it is until the expiry +/// catches up. +#[test_log::test(tokio::test)] +async fn test_shutting_down_takes_everything_the_node_wrote_with_it() { + let mut conn = redis_connection().await; + let prefix = "test-heartbeat-shutdown"; + clear(&mut conn, prefix, &["conn-1"]).await; + + let node_config = config(prefix, "node-1", 10_000); + let group = join_or_create(&mut conn, &node_config).await.unwrap(); + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + group.id.clone(), + node_config.node_ttl_ms, + ); + locations.record("conn-1").await.unwrap(); + + let (shutdown_tx, handle, _moved) = heartbeat( + conn.clone(), + node_config.clone(), + group.clone(), + locations.clone(), + ); + + shutdown_tx.send(()).unwrap(); + handle.await.unwrap(); + + assert!(!conn.exists(&node_key(prefix, "node-1")).await.unwrap()); + assert!(members(&mut conn, prefix, &group).await.is_empty()); + assert_eq!( + locations.group_for("conn-1").await.unwrap(), + None, + "a node that shut down should not leave its connections claimed by a group it has left" + ); +} + +/// A connection whose entry could not be written still has to be one the node +/// keeps alive, since the refresh is the only thing that will ever write it. +/// Dropping it there would leave the connection unreachable from any other node +/// for as long as it lasted. +/// +/// The write is made to fail by asking for an expiry of nothing, which Redis +/// refuses. +#[test_log::test(tokio::test)] +async fn test_a_connection_is_kept_alive_even_where_its_entry_could_not_be_written() { + let conn = redis_connection().await; + let prefix = "test-locations-unwritable"; + + let locations = ConnectionLocations::new(conn, prefix.to_string(), "group-1".to_string(), 0); + + assert!( + locations.record("conn-1").await.is_err(), + "an expiry of nothing should be refused, otherwise this test proves nothing" + ); + + assert_eq!( + locations.forget_all().await.unwrap(), + 1, + "the connection should be one of this node's to keep alive and to take away" + ); +} diff --git a/libs/runtime/ws/ws-redis/tests/node_group_test.rs b/libs/runtime/ws/ws-redis/tests/node_group_test.rs new file mode 100644 index 00000000..d88ed7a7 --- /dev/null +++ b/libs/runtime/ws/ws-redis/tests/node_group_test.rs @@ -0,0 +1,311 @@ +use celerity_helpers::{redis::ConnectionWrapper, testing::redis_connection}; + +use celerity_ws_redis::node_group::{join_or_create, leave, node_key, NodeGroup, NodeGroupConfig}; + +/// A node's configuration under a key prefix of its own, so tests running +/// beside each other are not each other's cluster. +fn config(prefix: &str, node: &str, capacity: usize, node_ttl_ms: u64) -> NodeGroupConfig { + NodeGroupConfig { + server_node_name: node.to_string(), + capacity, + node_ttl_ms, + key_prefix: prefix.to_string(), + } +} + +/// Clears anything a previous run left behind under a prefix. A test that fails +/// never reaches its own cleanup, and the next run would otherwise be looking at +/// the last run's cluster. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str) { + let index_key = format!("{prefix}:{{group-meta}}:node-groups"); + for group_id in conn.smembers(&index_key).await.unwrap() { + let members_key = format!("{prefix}:{{group-meta}}:node-group-members:{group_id}"); + for member in conn.smembers(&members_key).await.unwrap() { + conn.del(&node_key(prefix, &member)).await.unwrap(); + } + conn.del(&members_key).await.unwrap(); + } + conn.del(&index_key).await.unwrap(); +} + +async fn members(conn: &mut ConnectionWrapper, prefix: &str, group: &NodeGroup) -> Vec { + conn.smembers(&format!( + "{prefix}:{{group-meta}}:node-group-members:{}", + group.id + )) + .await + .unwrap() +} + +async fn group_ids(conn: &mut ConnectionWrapper, prefix: &str) -> Vec { + conn.smembers(&format!("{prefix}:{{group-meta}}:node-groups")) + .await + .unwrap() +} + +/// Nodes fill a group before starting another one. +#[test_log::test(tokio::test)] +async fn test_a_group_is_filled_before_the_next_one_is_started() { + let mut conn = redis_connection().await; + let prefix = "test-fills-first"; + clear(&mut conn, prefix).await; + + let first = join_or_create(&mut conn, &config(prefix, "node-1", 2, 10_000)) + .await + .unwrap(); + let second = join_or_create(&mut conn, &config(prefix, "node-2", 2, 10_000)) + .await + .unwrap(); + assert_eq!( + first, second, + "a group with room should take the next node rather than a new group being started" + ); + + let third = join_or_create(&mut conn, &config(prefix, "node-3", 2, 10_000)) + .await + .unwrap(); + assert_ne!( + third.id, first.id, + "a group at capacity should send the next node to a group of its own" + ); + + // Named from the group's id, which is what a node subscribes to and what + // another node publishes to. + assert_eq!(third.channel, format!("{prefix}:node-group:{}", third.id)); + assert_eq!( + third.ack_channel, + format!("{prefix}:node-group-ack:{}", third.id) + ); + + for node in ["node-1", "node-2"] { + leave(&mut conn, &config(prefix, node, 2, 10_000), &first) + .await + .unwrap(); + } + leave(&mut conn, &config(prefix, "node-3", 2, 10_000), &third) + .await + .unwrap(); +} + +/// A node that stops saying it is running stops holding a place in its group. +/// +/// This is the case a subscriber count cannot see. The node is still in the +/// member set, and only its liveness key having expired tells the next node +/// that the place is free. +#[test_log::test(tokio::test)] +async fn test_a_node_that_stopped_running_gives_up_its_place() { + let mut conn = redis_connection().await; + let prefix = "test-expired-node"; + clear(&mut conn, prefix).await; + + let group = join_or_create(&mut conn, &config(prefix, "gone-node", 1, 200)) + .await + .unwrap(); + assert!(conn.exists(&node_key(prefix, "gone-node")).await.unwrap()); + + // Long enough for the liveness key to run out without it being refreshed, + // which is what a node dying looks like from anywhere else. + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + + let joined = join_or_create(&mut conn, &config(prefix, "live-node", 1, 10_000)) + .await + .unwrap(); + assert_eq!( + joined, group, + "a group whose only node has gone should have room again rather than being full" + ); + + let members = members(&mut conn, prefix, &group).await; + assert_eq!( + members, + vec!["live-node".to_string()], + "the node that stopped running should have been dropped from the member set" + ); + + leave(&mut conn, &config(prefix, "live-node", 1, 10_000), &group) + .await + .unwrap(); +} + +/// Leaving takes everything the node wrote with it, rather than leaving the +/// group looking fuller than it is until a TTL runs out. +#[test_log::test(tokio::test)] +async fn test_leaving_takes_the_membership_and_the_group_with_it() { + let mut conn = redis_connection().await; + let prefix = "test-graceful-leave"; + clear(&mut conn, prefix).await; + let node_config = config(prefix, "node-1", 5, 10_000); + + let group = join_or_create(&mut conn, &node_config).await.unwrap(); + leave(&mut conn, &node_config, &group).await.unwrap(); + + assert!( + !conn.exists(&node_key(prefix, "node-1")).await.unwrap(), + "a node that left should not still be saying it is running" + ); + assert!(members(&mut conn, prefix, &group).await.is_empty()); + assert!( + group_ids(&mut conn, prefix).await.is_empty(), + "a group nobody is in should not be left for the next node to find" + ); +} + +/// A node already in a group keeps the place it has. +/// +/// This is what makes the join the heartbeat as well. Every beat runs it, and a +/// node that is still a member comes back to the same group rather than being +/// counted into another one. +#[test_log::test(tokio::test)] +async fn test_a_node_already_in_a_group_keeps_its_place() { + let mut conn = redis_connection().await; + let prefix = "test-keeps-place"; + clear(&mut conn, prefix).await; + let node_config = config(prefix, "node-1", 5, 10_000); + + let joined = join_or_create(&mut conn, &node_config).await.unwrap(); + let again = join_or_create(&mut conn, &node_config).await.unwrap(); + assert_eq!(joined, again); + assert_eq!( + members(&mut conn, prefix, &joined).await, + vec!["node-1".to_string()], + "joining again should not count the node twice" + ); + + leave(&mut conn, &node_config, &joined).await.unwrap(); +} + +/// A node dropped from its group takes whatever place is free, which may be in +/// another group. +/// +/// Nothing keeps a place for a node that stopped saying it was running, so +/// returning is an ordinary join and the group it lands in is whichever has +/// room. +#[test_log::test(tokio::test)] +async fn test_a_dropped_node_takes_a_free_place_wherever_it_is() { + let mut conn = redis_connection().await; + let prefix = "test-dropped-takes-free"; + clear(&mut conn, prefix).await; + + let first = join_or_create(&mut conn, &config(prefix, "node-1", 1, 10_000)) + .await + .unwrap(); + // Dropped as another node would have dropped it, while a second node holds + // the only place the group has. + conn.srem( + &format!("{prefix}:{{group-meta}}:node-group-members:{}", first.id), + "node-1", + ) + .await + .unwrap(); + let second = join_or_create(&mut conn, &config(prefix, "node-2", 1, 10_000)) + .await + .unwrap(); + assert_eq!( + second, first, + "the freed place should be taken by the next node" + ); + + let returned = join_or_create(&mut conn, &config(prefix, "node-1", 1, 10_000)) + .await + .unwrap(); + assert_ne!( + returned.id, first.id, + "a node returning to a group that is full should take a place elsewhere" + ); + + leave(&mut conn, &config(prefix, "node-2", 1, 10_000), &first) + .await + .unwrap(); + leave(&mut conn, &config(prefix, "node-1", 1, 10_000), &returned) + .await + .unwrap(); +} + +/// Nodes starting together do not overfill a group. +/// +/// The case capacity is most likely to meet, since a rolling deploy or a +/// scale-out starts nodes at the same moment rather than one at a time. Reading +/// the members and adding to them separately would let every one of these see +/// room that the others were about to take. +#[test_log::test(tokio::test)] +async fn test_nodes_starting_together_do_not_overfill_a_group() { + let mut conn = redis_connection().await; + let prefix = "test-concurrent-join"; + clear(&mut conn, prefix).await; + + let joins = (0..12).map(|index| { + let node_config = config(prefix, &format!("node-{index}"), 2, 10_000); + async move { + let mut conn = redis_connection().await; + join_or_create(&mut conn, &node_config).await.unwrap() + } + }); + let joined: Vec<_> = futures::future::join_all(joins).await; + + for group_id in group_ids(&mut conn, prefix).await { + let members = conn + .smembers(&format!( + "{prefix}:{{group-meta}}:node-group-members:{group_id}" + )) + .await + .unwrap(); + assert!( + members.len() <= 2, + "a group of capacity 2 should never hold {} nodes, it holds {members:?}", + members.len() + ); + } + + assert_eq!( + joined.len(), + 12, + "every node should have come away with a group" + ); + + for (index, group) in joined.iter().enumerate() { + leave( + &mut conn, + &config(prefix, &format!("node-{index}"), 2, 10_000), + group, + ) + .await + .unwrap(); + } +} + +/// A node leaving a group others are still in takes only its own place, and +/// leaves the group where the rest can be found. +#[test_log::test(tokio::test)] +async fn test_leaving_a_group_others_are_in_leaves_the_group_alone() { + let mut conn = redis_connection().await; + let prefix = "test-leave-with-others"; + clear(&mut conn, prefix).await; + + let leaving = config(prefix, "node-1", 5, 10_000); + let staying = config(prefix, "node-2", 5, 10_000); + let group = join_or_create(&mut conn, &leaving).await.unwrap(); + assert_eq!( + join_or_create(&mut conn, &staying).await.unwrap(), + group, + "both nodes should be in the one group for this to test anything" + ); + + leave(&mut conn, &leaving, &group).await.unwrap(); + + assert_eq!( + members(&mut conn, prefix, &group).await, + vec!["node-2".to_string()], + "only the node that left should have given up its place" + ); + assert_eq!( + group_ids(&mut conn, prefix).await, + vec![group.id.clone()], + "a group still holding a node should stay where the next node can find it" + ); + assert!( + conn.exists(&node_key(prefix, "node-2")).await.unwrap(), + "a node that did not leave should still be saying it is running" + ); + + clear(&mut conn, prefix).await; +} diff --git a/libs/runtime/ws/ws-redis/tests/pubsub_test.rs b/libs/runtime/ws/ws-redis/tests/pubsub_test.rs index 92f15081..5793907b 100644 --- a/libs/runtime/ws/ws-redis/tests/pubsub_test.rs +++ b/libs/runtime/ws/ws-redis/tests/pubsub_test.rs @@ -1,110 +1,234 @@ -use std::collections::HashMap; +use std::{collections::HashMap, sync::Arc, time::Duration}; -use celerity_ws_redis::pubsub::{connect, PubSubConnectionConfig}; -use celerity_ws_registry::types::{AckMessage, Message, MessageType, WebSocketMessage}; +use celerity_helpers::{ + redis::{get_redis_connection, ConnectionWrapper}, + testing::{redis_config, redis_connection}, +}; + +use celerity_ws_redis::{ + locations::ConnectionLocations, + node_group::{join_or_create, leave, node_key, NodeGroup, NodeGroupConfig}, + pubsub::{connect, PubSubConnectionConfig}, +}; +use celerity_ws_registry::{ + registry::ConnectionLocationStore, + types::{AckMessage, Message, MessageType, WebSocketMessage}, +}; use tokio::sync::mpsc::{channel, Receiver, Sender}; -#[test_log::test(tokio::test)] -async fn test_publish_and_subscribe_to_redis_channel() { - let nodes = vec!["redis://127.0.0.1:6379/?protocol=resp3".to_string()]; - let (client1_tx, mut client1_rx) = connect(PubSubConnectionConfig { - server_node_name: "api-node-1".to_string(), - channel_name: "celerity_ws_messages".to_string(), - nodes: nodes.clone(), - password: None, - cluster_mode: false, - }) - .await - .unwrap(); +/// Clears anything a previous run left behind under a prefix, since a test that +/// fails never reaches its own cleanup. +/// +/// The connections are named rather than matched, because their entries are +/// spread across a cluster's slots by design and no one request reaches all of +/// them. +async fn clear(conn: &mut ConnectionWrapper, prefix: &str, connection_ids: &[&str]) { + for connection_id in connection_ids { + conn.del(&format!("{prefix}:conn:{connection_id}")) + .await + .unwrap(); + } + + let index_key = format!("{prefix}:{{group-meta}}:node-groups"); + for group_id in conn.smembers(&index_key).await.unwrap() { + let members_key = format!("{prefix}:{{group-meta}}:node-group-members:{group_id}"); + for member in conn.smembers(&members_key).await.unwrap() { + conn.del(&node_key(prefix, &member)).await.unwrap(); + } + conn.del(&members_key).await.unwrap(); + } + conn.del(&index_key).await.unwrap(); +} + +/// A node of a cluster, with everything a test needs to speak for it. +struct Node { + name: String, + group: NodeGroup, + tx: Sender, + rx: Receiver, + locations: Arc, + moved: Sender, + config: NodeGroupConfig, +} - let (client2_tx, mut client2_rx) = connect(PubSubConnectionConfig { - server_node_name: "api-node-2".to_string(), - channel_name: "celerity_ws_messages".to_string(), - nodes: nodes.clone(), - password: None, - cluster_mode: false, - }) +async fn start_node(prefix: &str, name: &str, capacity: usize) -> Node { + let mut conn = redis_connection().await; + let config = NodeGroupConfig { + server_node_name: name.to_string(), + capacity, + node_ttl_ms: 30_000, + key_prefix: prefix.to_string(), + }; + let group = join_or_create(&mut conn, &config).await.unwrap(); + let locations = ConnectionLocations::new( + conn.clone(), + prefix.to_string(), + group.id.clone(), + config.node_ttl_ms, + ); + + let (moved, moved_rx) = channel(4); + let (tx, rx) = connect( + PubSubConnectionConfig { + server_node_name: name.to_string(), + key_prefix: prefix.to_string(), + nodes: redis_config().nodes, + password: redis_config().password, + cluster_mode: redis_config().cluster_mode, + // Short, so a test watching the old channel go quiet is not waiting + // on a production grace period. + migration_grace_ms: 300, + }, + group.clone(), + locations.clone(), + moved_rx, + ) .await .unwrap(); - let (collect_client1_tx, mut collect_client1_rx) = channel(1024); - let (collect_client2_tx, mut collect_client2_rx) = channel(1024); + Node { + name: name.to_string(), + group, + tx, + rx, + locations, + moved, + config, + } +} + +/// Two nodes in groups of their own carry each other's traffic, and each one +/// only hears what is addressed to a connection its group holds. +#[test_log::test(tokio::test)] +async fn test_messages_reach_the_group_holding_the_connection() { + let mut conn = redis_connection().await; + let prefix = "test-pubsub-routing"; + clear(&mut conn, prefix, &["1", "2", "7", "probe"]).await; + + // Capacity of one, so the two nodes are in separate groups and a message + // only arrives by being routed rather than by everyone hearing everything. + let node1 = start_node(prefix, "api-node-1", 1).await; + let node2 = start_node(prefix, "api-node-2", 1).await; + // A third group, holding neither connection. Without it the test cannot + // tell routing from every node hearing everything, since a message that + // goes everywhere reaches the two that want it and is filtered out by the + // one that sent it. + let mut bystander = start_node(prefix, "api-node-3", 1).await; + assert_ne!(node1.group.id, node2.group.id); + assert_ne!(bystander.group.id, node1.group.id); + assert_ne!(bystander.group.id, node2.group.id); + + node1.locations.record("1").await.unwrap(); + node2.locations.record("2").await.unwrap(); + + let (collect_node1_tx, mut collect_node1_rx) = channel(1024); + let (collect_node2_tx, mut collect_node2_rx) = channel(1024); + + let Node { + tx: node1_tx, + rx: mut node1_rx, + .. + } = node1; + let Node { + tx: node2_tx, + rx: mut node2_rx, + .. + } = node2; tokio::spawn(async move { - // Client 1 sends messages that are intended for client 2. + // Node 1 sends messages that are for a connection node 2 holds. send_messages_and_listen( vec!["2".to_string()], - client1_tx, - &mut client1_rx, + node1_tx, + &mut node1_rx, "api-node-2".to_string(), - collect_client1_tx, + collect_node1_tx, ) .await; }); tokio::spawn(async move { - // Client 2 sends messages that are intended for client 1. send_messages_and_listen( vec!["1".to_string()], - client2_tx, - &mut client2_rx, + node2_tx, + &mut node2_rx, "api-node-1".to_string(), - collect_client2_tx, + collect_node2_tx, ) .await; }); - let mut collected = HashMap::>::new(); - let mut collected_count = 0; - let mut collected_acks = HashMap::::new(); - let mut ack_count = 0; - while collected_count < 200 || ack_count < 2 { - tokio::select! { - Some(message) = collect_client1_rx.recv() => { - match message { - Message::WebSocket(message) => { - collected.entry(message.connection_id).or_default().push(message.message); - collected_count += 1; - } - Message::Ack(ack_message) => { - collected_acks.insert("node1".to_string(), ack_message); - ack_count += 1; + let mut received_by_connection = HashMap::>::new(); + let mut messages_received = 0; + let mut acks_by_node = HashMap::::new(); + let mut acks_received = 0; + let gathering = async { + // A hundred messages each way, and one acknowledgement from each + // node for the last of them. + while messages_received < 200 || acks_received < 2 { + tokio::select! { + Some(message) = collect_node1_rx.recv() => { + match message { + Message::WebSocket(message) => { + received_by_connection + .entry(message.connection_id) + .or_default() + .push(message.message); + messages_received += 1; + } + Message::Ack(ack_message) => { + acks_by_node.insert("node1".to_string(), ack_message); + acks_received += 1; + } } } - } - Some(message) = collect_client2_rx.recv() => { - match message { - Message::WebSocket(message) => { - collected.entry(message.connection_id).or_default().push(message.message); - collected_count += 1; - } - Message::Ack(ack_message) => { - collected_acks.insert("node2".to_string(), ack_message); - ack_count += 1; + Some(message) = collect_node2_rx.recv() => { + match message { + Message::WebSocket(message) => { + received_by_connection + .entry(message.connection_id) + .or_default() + .push(message.message); + messages_received += 1; + } + Message::Ack(ack_message) => { + acks_by_node.insert("node2".to_string(), ack_message); + acks_received += 1; + } } } } - } - } + }; + tokio::time::timeout(Duration::from_secs(20), gathering) + .await + .expect("every message and acknowledgement should have arrived"); + + assert!( + bystander.rx.try_recv().is_err(), + "a group holding neither connection should have been told nothing" + ); - assert_eq!(collected.len(), 2); - assert_eq!(collected["1"], build_message_list("1", 100)); - assert_eq!(collected["2"], build_message_list("2", 100)); - assert_eq!(collected_acks.len(), 2); - // Node 1 should have received an acknowledgement for the message sent to node 2 - // that was forwarded for connection 2. assert_eq!( - collected_acks["node1"], + received_by_connection.len(), + 2, + "both connections should have been sent to, not one of them twice" + ); + assert_eq!(received_by_connection["1"], build_message_list("1", 100)); + assert_eq!(received_by_connection["2"], build_message_list("2", 100)); + assert_eq!(acks_by_node.len(), 2); + // Node 1 hears about the message it sent to the group holding connection 2, + // which means the acknowledgement found its way back to the sender's own + // group rather than to the group that sent it. + assert_eq!( + acks_by_node["node1"], AckMessage { message_id: "conn-2-msg-99".to_string(), message_node: "api-node-1".to_string(), } ); - // Node 2 should have received an acknowledgement for the message sent to node 1 - // that was forwarded for connection 1. assert_eq!( - collected_acks["node2"], + acks_by_node["node2"], AckMessage { message_id: "conn-1-msg-99".to_string(), message_node: "api-node-2".to_string(), @@ -112,6 +236,324 @@ async fn test_publish_and_subscribe_to_redis_channel() { ); } +/// A message for a connection nothing has recorded is offered to every group. +/// +/// A client that connected a moment ago looks exactly like this, and dropping +/// the message would lose it for a client that is there. +#[test_log::test(tokio::test)] +async fn test_a_message_for_an_unrecorded_connection_reaches_every_group() { + let mut conn = redis_connection().await; + let prefix = "test-pubsub-fanout"; + clear(&mut conn, prefix, &["1", "2", "7", "probe"]).await; + + let node1 = start_node(prefix, "api-node-1", 1).await; + let mut node2 = start_node(prefix, "api-node-2", 1).await; + assert_ne!(node1.group.id, node2.group.id); + + // Nothing records where connection 7 is, which is what a client that has + // only just connected looks like from another node. + node1 + .tx + .send(Message::WebSocket(WebSocketMessage { + connection_id: "7".to_string(), + message_id: "m-1".to_string(), + message_type: MessageType::Json, + source_node: node1.name.clone(), + message: r#"{"event":"update"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + + let received = tokio::time::timeout(Duration::from_secs(5), node2.rx.recv()) + .await + .expect("a message for a connection nobody claims should still be offered around") + .unwrap(); + let Message::WebSocket(received) = received else { + panic!("expected a websocket message, got {received:?}"); + }; + assert_eq!(received.message_id, "m-1"); + + leave(&mut conn, &node1.config, &node1.group).await.unwrap(); + leave(&mut conn, &node2.config, &node2.group).await.unwrap(); +} + +/// An acknowledgement is published to the ack mirror of the group holding the +/// node that sent the message. +/// +/// A node subscribes to both of its group's channels, so it would receive an +/// acknowledgement sent to either. Which one carries it is still part of the +/// protocol, and anything reading the mirror on its own would miss one sent to +/// the wrong channel, so this watches the channel rather than the node. +#[test_log::test(tokio::test)] +async fn test_an_acknowledgement_goes_to_the_ack_mirror_of_the_senders_group() { + let mut conn = redis_connection().await; + let prefix = "test-pubsub-ack-channel"; + clear(&mut conn, prefix, &["1", "2", "7", "probe"]).await; + + let sender = start_node(prefix, "api-node-1", 1).await; + let holder = start_node(prefix, "api-node-2", 1).await; + assert_ne!(sender.group.id, holder.group.id); + + // Watching the sender's ack mirror directly, as another implementation + // following the protocol would. + let (push_tx, mut push_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut watcher = get_redis_connection(&redis_config(), Some(push_tx)) + .await + .unwrap(); + watcher.subscribe(&sender.group.ack_channel).await.unwrap(); + + holder + .tx + .send(Message::Ack(AckMessage { + message_id: "m-1".to_string(), + message_node: sender.name.clone(), + })) + .await + .unwrap(); + + // Subscribing is itself announced on this channel, so the confirmation is + // read past rather than mistaken for the acknowledgement. + let published = async { + loop { + let push = push_rx.recv().await.unwrap(); + if push.kind == redis::PushKind::Message { + let payload: String = + redis::FromRedisValue::from_redis_value(&push.data[1]).unwrap(); + return payload; + } + } + }; + let payload = tokio::time::timeout(Duration::from_secs(5), published) + .await + .expect("the acknowledgement should have been published to the ack mirror"); + assert!( + payload.contains("m-1"), + "the ack mirror should have carried the acknowledgement, it carried {payload}" + ); + + leave(&mut conn, &sender.config, &sender.group) + .await + .unwrap(); + leave(&mut conn, &holder.config, &holder.group) + .await + .unwrap(); +} + +/// A node dropped from its group and then given a place back in it before the +/// grace period is up keeps listening to it. +/// +/// Giving up the old channels is scheduled when a node moves, and by the time +/// that comes around the node may be back where it started. Giving them up then +/// would leave it unable to receive messages from the group it is actually in, +/// with nothing to tell it so, since it believes it is subscribed. +#[test_log::test(tokio::test)] +async fn test_a_node_that_comes_back_to_the_group_it_left_keeps_receiveing_messages_from_it() { + let mut conn = redis_connection().await; + let prefix = "test-pubsub-return"; + clear(&mut conn, prefix, &["1", "2", "7", "probe"]).await; + + let sender = start_node(prefix, "api-node-1", 5).await; + let mut mover = start_node(prefix, "api-node-2", 5).await; + let home = mover.group.clone(); + + let elsewhere = NodeGroup::new(prefix, "somewhere-else".to_string()); + conn.sadd( + &format!("{prefix}:{{group-meta}}:node-groups"), + &elsewhere.id, + ) + .await + .unwrap(); + + // Away and back again, both inside the grace period the first move started. + mover.moved.send(elsewhere.clone()).await.unwrap(); + mover.locations.set_group(elsewhere.id.clone()); + mover.moved.send(home.clone()).await.unwrap(); + mover.locations.set_group(home.id.clone()); + mover.locations.record("2").await.unwrap(); + + // Long enough for the first move's grace period to have come and gone. + tokio::time::sleep(Duration::from_millis(600)).await; + + sender + .tx + .send(Message::WebSocket(WebSocketMessage { + connection_id: "2".to_string(), + message_id: "back-where-it-started".to_string(), + message_type: MessageType::Json, + source_node: sender.name.clone(), + message: r#"{"event":"back"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + assert_eq!( + next_message_id(&mut mover.rx).await, + "back-where-it-started", + "a node back in the group it left should still be listening to it" + ); +} + +/// A node that moves group hears its new channel straight away, and its old one +/// until the grace period is up. +/// +/// A sender reads where a connection is and publishes a moment later, so +/// messages are always in flight against a mapping that has just changed. +#[test_log::test(tokio::test)] +async fn test_a_node_that_moves_group_hears_both_until_the_grace_is_up() { + let mut conn = redis_connection().await; + let prefix = "test-pubsub-migration"; + clear(&mut conn, prefix, &["1", "2", "7", "probe"]).await; + + let sender = start_node(prefix, "api-node-1", 5).await; + let mut mover = start_node(prefix, "api-node-2", 5).await; + let left_behind = mover.group.clone(); + + // Somewhere else to be, which is what the heartbeat would have found. + let joined = NodeGroup::new(prefix, "a-group-of-its-own".to_string()); + conn.sadd(&format!("{prefix}:{{group-meta}}:node-groups"), &joined.id) + .await + .unwrap(); + mover.moved.send(joined.clone()).await.unwrap(); + mover.locations.set_group(joined.id.clone()); + mover.locations.record("2").await.unwrap(); + wait_until_listening(&sender.tx, &mut mover.rx, &sender.name, &mover.locations).await; + + // Addressed to the group it moved into. + sender + .tx + .send(Message::WebSocket(WebSocketMessage { + connection_id: "2".to_string(), + message_id: "after-the-move".to_string(), + message_type: MessageType::Json, + source_node: sender.name.clone(), + message: r#"{"event":"after"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + assert_eq!( + next_message_id(&mut mover.rx).await, + "after-the-move", + "a node should hear the group it has just joined" + ); + + // Addressed to the group it left, as a sender holding the old mapping + // would. + sender.locations.set_group(left_behind.id.clone()); + sender.locations.record("2").await.unwrap(); + sender + .tx + .send(Message::WebSocket(WebSocketMessage { + connection_id: "2".to_string(), + message_id: "still-in-flight".to_string(), + message_type: MessageType::Json, + source_node: sender.name.clone(), + message: r#"{"event":"in flight"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + assert_eq!( + next_message_id(&mut mover.rx).await, + "still-in-flight", + "a node should still hear the group it left while the grace period runs" + ); + + // Once the grace period is up the old channel is given up, and a message sent + // there is nobody's. + tokio::time::sleep(Duration::from_millis(600)).await; + sender + .tx + .send(Message::WebSocket(WebSocketMessage { + connection_id: "2".to_string(), + message_id: "too-late".to_string(), + message_type: MessageType::Json, + source_node: sender.name.clone(), + message: r#"{"event":"too late"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(500), mover.rx.recv()) + .await + .is_err(), + "a node should have given up the group it left once the grace period was up" + ); +} + +/// Waits until a node is listening to the group it has just moved into, by +/// offering it a message until one arrives. +/// +/// Being told it has moved and taking up the new group's channels are separate +/// steps, and nothing says when the second has happened. Redis cannot be asked +/// either, since it answers only for the subscribers of the node asked, which +/// in a cluster is not the one holding this subscription. +/// +/// Offered often, because the grace period on the group left behind is already +/// running by the time the first one lands. +async fn wait_until_listening( + tx: &Sender, + rx: &mut Receiver, + source_node: &str, + locations: &Arc, +) { + locations.record("probe").await.unwrap(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + tx.send(Message::WebSocket(WebSocketMessage { + connection_id: "probe".to_string(), + message_id: "probe".to_string(), + message_type: MessageType::Json, + source_node: source_node.to_string(), + message: r#"{"event":"probe"}"#.to_string(), + inform_clients_on_loss: None, + caller: None, + })) + .await + .unwrap(); + + // The probe itself, rather than whatever else may be queued, since + // anything else says nothing about the group just moved into. + if let Ok(Some(Message::WebSocket(received))) = + tokio::time::timeout(Duration::from_millis(5), rx.recv()).await + { + if received.connection_id == "probe" && received.message_id == "probe" { + break; + } + } + assert!( + tokio::time::Instant::now() < deadline, + "the node should have taken up the channels of the group it moved into" + ); + } + + // Whatever else was offered before the one that landed. + while tokio::time::timeout(Duration::from_millis(20), rx.recv()) + .await + .is_ok() + {} + locations.forget("probe").await.unwrap(); +} + +async fn next_message_id(rx: &mut Receiver) -> String { + let received = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .expect("a message should have arrived") + .unwrap(); + match received { + Message::WebSocket(message) => message.message_id, + other => panic!("expected a websocket message, got {other:?}"), + } +} + async fn send_messages_and_listen( dst_connection_ids: Vec, src_client_tx: Sender, diff --git a/libs/runtime/ws/ws-registry/src/acks.rs b/libs/runtime/ws/ws-registry/src/acks.rs index 3c8b95c4..f08d3fad 100644 --- a/libs/runtime/ws/ws-registry/src/acks.rs +++ b/libs/runtime/ws/ws-registry/src/acks.rs @@ -99,7 +99,6 @@ pub enum AckWorkerMessage { message_id: String, connection_id: String, }, - Check(String, Sender), Wait(String, Sender), } @@ -195,21 +194,6 @@ impl Worker { }) => { self.record_client_ack(message_id, connection_id).await; } - Some(AckWorkerMessage::Check(message_id, tx)) => { - let acks_guard = self.acks.lock().await; - let detailed_ack_status = acks_guard.get(&message_id).cloned(); - let final_ack_status = match detailed_ack_status { - Some(detailed_ack_status) => detailed_ack_status.status, - None => AckStatus::Lost, - }; - if tx.send(final_ack_status).is_err() { - error!( - "sender dropped before receiving acknowledgement \ - status for message {}", - message_id - ); - } - } Some(AckWorkerMessage::Wait(message_id, tx)) => { // Spawn a separate task to handle the ack wait without blocking // the main worker loop. diff --git a/libs/runtime/ws/ws-registry/src/errors.rs b/libs/runtime/ws/ws-registry/src/errors.rs index 57b855d2..e94a4761 100644 --- a/libs/runtime/ws/ws-registry/src/errors.rs +++ b/libs/runtime/ws/ws-registry/src/errors.rs @@ -13,6 +13,18 @@ pub enum WebSocketConnError { // 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), + // The shared record of where a connection is could not be written or taken + // away. The connection itself is unaffected, and what is lost is the other + // nodes being able to find it. + ConnectionLocationError(String), + // The shared record of what has been forwarded to a client could not be + // read or written. The message is forwarded anyway, so what is risked is a + // client seeing it twice rather than not at all. + ForwardedMessageError(String), + // Something a registry is given once was given to it twice. Naming what, + // since the second one is refused and the caller is about to act as though + // it had been taken. + AlreadyAttached(String), } impl Display for WebSocketConnError { @@ -28,6 +40,13 @@ impl Display for WebSocketConnError { WebSocketConnError::MalformedBinaryMessage(e) => { write!(f, "MalformedBinaryMessage: {e}") } + WebSocketConnError::ConnectionLocationError(e) => { + write!(f, "ConnectionLocationError: {e}") + } + WebSocketConnError::ForwardedMessageError(e) => { + write!(f, "ForwardedMessageError: {e}") + } + WebSocketConnError::AlreadyAttached(e) => write!(f, "AlreadyAttached: {e}"), } } } diff --git a/libs/runtime/ws/ws-registry/src/registry.rs b/libs/runtime/ws/ws-registry/src/registry.rs index 3ae83ac5..6c12acf3 100644 --- a/libs/runtime/ws/ws-registry/src/registry.rs +++ b/libs/runtime/ws/ws-registry/src/registry.rs @@ -29,6 +29,49 @@ use crate::{ /// makes that ownership impossible to get wrong. pub type WebSocketConnSender = SplitSink; +/// What this node has already forwarded to a client, shared with the other +/// nodes so that a message resent because an acknowledgement went missing is +/// not delivered a second time. +/// +/// A resend arrives at whichever node holds the connection now, which may not +/// be the node that delivered it the first time, so remembering it in one +/// process is not enough. +#[async_trait] +pub trait ForwardedMessageStore: Send + Sync + Debug { + /// Records a message as forwarded and says whether it already was. + /// + /// One call rather than a check and a write. The answer is needed before + /// the message goes out, so a deferred write would only leave a window in + /// which two copies both find it absent. + async fn record_and_check_forwarded( + &self, + message_id: &str, + ) -> Result; + + /// Gives up the record of a message, for one that was taken as forwarded + /// and then could not be sent. + /// + /// The record is written before the message goes out, since two copies + /// arriving together must not both find it absent. A copy that then fails + /// to send has to revert to the previous state, or the next attempt is recognised + /// as a duplicate and acknowledged without ever reaching the client. + async fn forget_forwarded(&self, message_id: &str) -> Result<(), WebSocketConnError>; +} + +/// Where the cluster records which node group holds a connection. +/// +/// The registry knows a connection is here; only the deployment's shared store +/// can make that fact reachable from another node. Implemented outside this +/// crate by whatever that store is. +#[async_trait] +pub trait ConnectionLocationStore: Send + Sync + Debug { + /// Records that this node holds a connection. + async fn record(&self, connection_id: &str) -> Result<(), WebSocketConnError>; + + /// Takes the record away, once the client has gone. + async fn forget(&self, connection_id: &str) -> Result<(), WebSocketConnError>; +} + // Additional context for sending messages to a connection in a WebSocket registry. #[derive(Default)] pub struct SendContext { @@ -98,7 +141,19 @@ pub struct WebSocketConnRegistry { // for in-process broadcasting. Typically, there will be a single receiver in the same process // that will broadcast messages to all other nodes in the cluster via a pub/sub mechanism // over a network protocol. - broadcaster: Option>, + // + // Written once, and possibly after the registry is already serving, because + // reaching whatever carries messages between nodes is asynchronous and the + // registry is built before there is a runtime to do it in. + broadcaster: OnceLock>, + // Where each connection is, for a deployment whose nodes have to find each + // other's clients. Absent on a single node, which needs no such record + // because every connection it is asked about is either its own or nowhere. + locations: OnceLock>, + // What has already been forwarded to a client, shared across the cluster. + // Absent on a single node, where a message is only ever relayed to this + // node once because there is nowhere else for it to come from. + forwarded: OnceLock>, // The name of the server node that the registry is running on. // This is used to identify the source node of a message when broadcasting // messages to other nodes in the cluster. @@ -110,16 +165,73 @@ impl WebSocketConnRegistry { config: WebSocketConnRegistryConfig, broadcaster: Option>, ) -> Self { + let broadcaster_slot = OnceLock::new(); + if let Some(broadcaster) = broadcaster { + let _ = broadcaster_slot.set(broadcaster); + } + Self { ack_worker_config: config.ack_worker_config, connections: Arc::new(RwLock::new(HashMap::new())), ack_sender: Mutex::new(None), client_ack_sender: OnceLock::new(), - broadcaster, + broadcaster: broadcaster_slot, + locations: OnceLock::new(), + forwarded: OnceLock::new(), server_node_name: config.server_node_name, } } + /// Hands the registry the channel that carries its messages to the other + /// nodes. + /// + /// This is separate from construction because reaching that channel means + /// connecting to a shared store, which needs a runtime, and the registry is + /// built before there is one. A registry serves a single node until this is + /// set, and a cluster afterwards. + /// + /// A second one is refused, since it would take over messages the first is + /// still waiting on acknowledgements for. + pub fn set_broadcaster( + &self, + broadcaster: Sender, + ) -> Result<(), WebSocketConnError> { + self.broadcaster.set(broadcaster).map_err(|_| { + WebSocketConnError::AlreadyAttached( + "the registry already has something carrying its messages between nodes" + .to_string(), + ) + }) + } + + /// Hands the registry where it should record what it has forwarded. + /// + /// Set alongside the broadcaster and refused twice for the same reason. + pub fn set_forwarded_messages( + &self, + forwarded: Arc, + ) -> Result<(), WebSocketConnError> { + self.forwarded.set(forwarded).map_err(|_| { + WebSocketConnError::AlreadyAttached( + "the registry already has somewhere to record what it has forwarded".to_string(), + ) + }) + } + + /// Hands the registry where it should record the connections it holds. + /// + /// Set alongside the broadcaster and refused twice for the same reason. + pub fn set_locations( + &self, + locations: Arc, + ) -> Result<(), WebSocketConnError> { + self.locations.set(locations).map_err(|_| { + WebSocketConnError::AlreadyAttached( + "the registry already has somewhere to record its connections".to_string(), + ) + }) + } + /// Starts the worker that tracks acknowledgements from clients. /// /// Started whatever the deployment, unlike the worker for acknowledgements @@ -279,7 +391,7 @@ impl WebSocketConnRegistry { /// to other nodes in the cluster, this must be called before setting up the listener /// and any `send_message` calls. pub fn start_ack_worker(self: Arc) { - if self.broadcaster.is_some() { + if self.broadcaster.get().is_some() { // Only start the ack worker if the broadcaster is present as the extra // resilience provided by the ack worker is only needed when broadcasting // messages to other nodes in the cluster. @@ -347,40 +459,68 @@ impl WebSocketConnRegistry { match message { RegistryMessage::WebSocket(message) => { debug!(connection_id = %message.connection_id, "received message from other node"); - if self.has_received_ack(message.message_id.clone()).await { - info!(message_id = %message.message_id, "already received acknowledgement for message from other node, skipping duplicate message"); - continue; - } - if let Some(connection) = self.get_connection(message.connection_id.clone()) { + // Asked here rather than on the way in, because + // every node in the group receives the message and + // only this one holds the connection. A node that + // cannot deliver would otherwise claim the message + // as forwarded, leaving the node that can to treat + // its first delivery as a duplicate. + let already_forwarded = + self.already_forwarded(&message.message_id).await; debug!( connection_id = %message.connection_id, "acquiring lock to send message to connection: {}", message.connection_id.clone() ); - let mut connection = connection.lock().await; - debug!(connection_id = %message.connection_id, "sending message to connection: {}", message.connection_id); - let ws_message = + // A message already forwarded is acknowledged + // again without being sent again. Staying silent + // would have the sender resend until its attempts + // ran out and then report a message that did + // arrive as lost, which is worse than the + // duplicate this avoids. + let delivered = if already_forwarded { + info!( + message_id = %message.message_id, + "this message has already been forwarded to its client, \ + acknowledging it again without sending it again" + ); + true + } else { + let mut connection = connection.lock().await; + debug!(connection_id = %message.connection_id, "sending message to connection: {}", message.connection_id); match create_ws_message(message.message_type, message.message) { - Ok(msg) => msg, + Ok(ws_message) => match connection.send(ws_message).await { + Ok(()) => true, + Err(e) => { + error!( + connection_id = %message.connection_id, + "failed to send message to websocket connection: {e:?}" + ); + false + } + }, Err(e) => { error!( connection_id = %message.connection_id, "failed to decode message for cluster relay: {e:?}", ); - continue; + false } - }; - let send_result = connection.send(ws_message).await; - if let Err(e) = send_result { - error!( - connection_id = %message.connection_id, - "failed to send message to websocket connection: {e:?}" - ); + } + }; + + if !delivered { + // The record is given back, so the sender's + // next attempt is a first delivery rather than + // a duplicate acknowledgement without the actual message + // being sent. + self.forget_forwarded(&message.message_id).await; + continue; } - if let Some(broadcaster) = &self.broadcaster { + if let Some(broadcaster) = self.broadcaster.get() { if broadcaster .send(RegistryMessage::Ack(AckMessage { message_id: message.message_id.clone(), @@ -406,6 +546,94 @@ impl WebSocketConnRegistry { }); } + /// Takes a connection, and tells the rest of the cluster where it is. + /// + /// A failure to record it is logged rather than returned. The connection + /// works either way, and what a caller could do with the error is refuse a + /// client whose only problem is that other nodes cannot reach it yet, which + /// the next heartbeat repairs. + pub async fn register_connection( + &self, + connection_id: String, + ws: Arc>, + ) { + self.add_connection(connection_id.clone(), ws); + + if let Some(locations) = self.locations.get() { + if let Err(err) = locations.record(&connection_id).await { + error!( + connection_id = %connection_id, + "failed to record where a connection is, so other nodes cannot reach it \ + until the next heartbeat: {err}" + ); + } + } + } + + /// Drops a connection, and takes away the record of where it was. + /// + /// Removed locally first, so a message can never be handed to a connection + /// this node has already stopped holding. + pub async fn deregister_connection(&self, connection_id: String) { + self.remove_connection(connection_id.clone()); + + if let Some(locations) = self.locations.get() { + if let Err(err) = locations.forget(&connection_id).await { + error!( + connection_id = %connection_id, + "failed to take away the record of where a connection was, so messages will \ + be published here for it until the record expires: {err}" + ); + } + } + } + + /// Whether this message has already been forwarded to its client. + /// + /// A store that cannot answer is taken as a no. Forwarding twice is a + /// nuisance; refusing to forward on the strength of a failed lookup is a + /// message the client never gets. + async fn already_forwarded(&self, message_id: &str) -> bool { + let Some(forwarded) = self.forwarded.get() else { + return false; + }; + + match forwarded.record_and_check_forwarded(message_id).await { + Ok(already) => already, + Err(err) => { + error!( + message_id = %message_id, + "could not tell whether this message has already been forwarded, \ + sending it rather than holding it back: {err}" + ); + false + } + } + } + + /// Gives up the record of a message this node took as forwarded and then + /// could not send. + /// + /// A failure here leaves the record in place, which costs the message a + /// delivery, so it is worth saying loudly. + async fn forget_forwarded(&self, message_id: &str) { + let Some(forwarded) = self.forwarded.get() else { + return; + }; + + if let Err(err) = forwarded.forget_forwarded(message_id).await { + error!( + message_id = %message_id, + "could not give up the record of a message that was not sent, so a later \ + attempt will be taken for one already delivered: {err}" + ); + } + } + + /// Takes a connection without telling anything else about it. + /// + /// For a single node, and for the callers inside this crate that have + /// already dealt with the record. pub fn add_connection(&self, connection_id: String, ws: Arc>) { self.connections.write().unwrap().insert(connection_id, ws); } @@ -435,22 +663,6 @@ impl WebSocketConnRegistry { .collect() } - async fn has_received_ack(&self, message_id: String) -> bool { - if let Some(ack_sender) = self.ack_sender.lock().await.as_ref() { - let (ack_tx, ack_rx) = tokio::sync::oneshot::channel(); - ack_sender - .send(AckWorkerMessage::Check(message_id.clone(), ack_tx)) - .await - .expect("ack worker channel unexpectedly closed"); - let ack_status = ack_rx - .await - .expect("oneshot channel for ack status check unexpectedly closed"); - ack_status == AckStatus::Received - } else { - false - } - } - async fn record_received_ack(&self, message_id: String) { if let Some(ack_sender) = self.ack_sender.lock().await.as_ref() { ack_sender @@ -568,7 +780,7 @@ impl WebSocketRegistrySend for WebSocketConnRegistry { debug!(connection_id = %connection_id, "sending message to connection: {}", connection_id); let ws_message = create_ws_message(message_type, message)?; connection.send(ws_message).await?; - } else if let Some(broadcaster) = &self.broadcaster { + } else if let Some(broadcaster) = self.broadcaster.get() { let send_ctx = ctx.unwrap_or_default(); debug!(connection_id = %connection_id, "connection not found locally, preparing to send message to broadcaster"); self.record_pending_ack( @@ -1417,7 +1629,9 @@ mod tests { let registry = conn_info.registry.clone(); async move { let (socket_tx, _socket_rx) = socket.split(); - registry.add_connection(nanoid!(), Arc::new(Mutex::new(socket_tx))); + registry + .register_connection(nanoid!(), Arc::new(Mutex::new(socket_tx))) + .await; } .boxed() } @@ -1430,6 +1644,27 @@ mod tests { ws.on_upgrade(create_unwatched_socket(conn_info)) } + /// Serves the unwatched handler, returning where to connect to it. + async fn serve_unwatched(registry: Arc) -> SocketAddr { + let app: Router = Router::new() + .route("/ws", get(unwatched_connection_handler)) + .with_state(ConnectionInfo { + connection_id: None, + other_connection_id: None, + missing_connection_id: None, + registry, + }); + + let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) + .await + .unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + addr + } + /// A client that has gone does not cost the others their notification. /// /// Naming a client that can no longer be written to is ordinary, since a @@ -1528,4 +1763,139 @@ mod tests { let body: MessageLostBody = serde_json::from_slice(&bytes[4..]).unwrap(); assert_eq!(body.message_id, "m-1"); } + + /// Somewhere to record connections that remembers what it was told, and can + /// be asked to fail. + #[derive(Debug, Default)] + struct RecordingLocations { + recorded: std::sync::Mutex>, + forgotten: std::sync::Mutex>, + failing: bool, + } + + #[async_trait] + impl ConnectionLocationStore for RecordingLocations { + async fn record(&self, connection_id: &str) -> Result<(), WebSocketConnError> { + self.recorded + .lock() + .unwrap() + .push(connection_id.to_string()); + if self.failing { + return Err(WebSocketConnError::ConnectionLocationError( + "the store is not answering".to_string(), + )); + } + Ok(()) + } + + async fn forget(&self, connection_id: &str) -> Result<(), WebSocketConnError> { + self.forgotten + .lock() + .unwrap() + .push(connection_id.to_string()); + if self.failing { + return Err(WebSocketConnError::ConnectionLocationError( + "the store is not answering".to_string(), + )); + } + Ok(()) + } + } + + fn local_registry() -> Arc { + Arc::new(WebSocketConnRegistry::new( + WebSocketConnRegistryConfig { + ack_worker_config: None, + server_node_name: "node1".to_string(), + }, + None, + )) + } + + /// A connection is recorded where the rest of the cluster can find it, and + /// the record goes when the connection does. + #[test_log::test(tokio::test)] + async fn test_a_connection_is_recorded_and_then_forgotten() { + let registry = local_registry(); + let locations = Arc::new(RecordingLocations::default()); + registry.set_locations(locations.clone()).unwrap(); + + let addr = serve_unwatched(registry.clone()).await; + let (_socket, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + wait_for_connection_count(®istry, 1).await; + let connection_id = registry.get_connections()[0].0.clone(); + + assert_eq!( + *locations.recorded.lock().unwrap(), + vec![connection_id.clone()], + "the cluster should have been told where the connection is" + ); + + registry.deregister_connection(connection_id.clone()).await; + assert_eq!(*locations.forgotten.lock().unwrap(), vec![connection_id]); + assert!(registry.get_connections().is_empty()); + } + + /// A store that cannot be written to does not cost the client its + /// connection. + /// + /// The connection works locally either way, and the record is written again + /// by the next heartbeat. Refusing a client over it would turn a repairable + /// fault into a visible one. + #[test_log::test(tokio::test)] + async fn test_a_connection_survives_a_store_that_is_not_answering() { + let registry = local_registry(); + registry + .set_locations(Arc::new(RecordingLocations { + failing: true, + ..Default::default() + })) + .unwrap(); + + let addr = serve_unwatched(registry.clone()).await; + let (mut socket, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws")) + .await + .unwrap(); + wait_for_connection_count(®istry, 1).await; + + // Still usable, which is the point. A record nothing could write is + // repaired by the next heartbeat. + socket + .send(tungstenite::Message::Text("still here".to_string())) + .await + .unwrap(); + } + + /// What carries messages between nodes can be attached after the registry + /// is built, and only once. + #[test_log::test(tokio::test)] + async fn test_the_broadcaster_is_attached_once_and_then_used() { + let registry = local_registry(); + let (tx, mut rx) = tokio::sync::mpsc::channel(4); + registry.set_broadcaster(tx.clone()).unwrap(); + assert!( + registry.set_broadcaster(tx).is_err(), + "a second broadcaster would take over messages the first is waiting on" + ); + + registry + .send_message( + "a-connection-on-another-node".to_string(), + "m-1".to_string(), + MessageType::Json, + r#"{"event":"update"}"#.to_string(), + None, + ) + .await + .unwrap(); + + let sent = rx.recv().await.expect("the message should have been sent"); + let RegistryMessage::WebSocket(sent) = sent else { + panic!("expected a websocket message, got {sent:?}"); + }; + assert_eq!(sent.connection_id, "a-connection-on-another-node"); + assert_eq!(sent.message_id, "m-1"); + } } diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..513d14cc --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,10 @@ +# Pinned so that a Rust release cannot turn unrelated work red. +# +# CI takes whatever stable is on the day it runs, so a new lint or a lint that +# has grown stricter arrives without anybody choosing it, and it arrives on +# whichever branch happens to build next. Moving this file is how the toolchain +# changes, which makes the fallout a change somebody reviews rather than a +# surprise on an unrelated pull request. +[toolchain] +channel = "1.98.0" +components = ["clippy", "rustfmt"]