From 9338c6d51bd550de31548744656da9111ee2f7f2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:40:58 -0500 Subject: [PATCH] fix(client-rust): CLI batch mode reuses one channel per connection; bench backs off on failure (CRS-004, #257) --- clients/rust/crates/mxgw-cli/src/batch.rs | 3 + clients/rust/crates/mxgw-cli/src/bench.rs | 17 +++++- clients/rust/crates/mxgw-cli/src/cli.rs | 22 +++++++ clients/rust/crates/mxgw-cli/src/connect.rs | 66 ++++++++++++++++++++- clients/rust/crates/mxgw-cli/src/tests.rs | 13 ++++ 5 files changed, 116 insertions(+), 5 deletions(-) diff --git a/clients/rust/crates/mxgw-cli/src/batch.rs b/clients/rust/crates/mxgw-cli/src/batch.rs index 5411ed93..2d9744d0 100644 --- a/clients/rust/crates/mxgw-cli/src/batch.rs +++ b/clients/rust/crates/mxgw-cli/src/batch.rs @@ -25,6 +25,9 @@ pub(crate) const BATCH_EOR: &str = "__MXGW_BATCH_EOR__"; /// one worker parked on `ReadFile`; that is acceptable here because no other /// future on the main task needs to run while we wait for the next command. pub(crate) async fn run_batch() -> Result<(), Error> { + // One channel per distinct connection for the whole session, not one per line. + crate::connect::enable_batch_reuse(); + let stdin = io::stdin(); let stdout = io::stdout(); diff --git a/clients/rust/crates/mxgw-cli/src/bench.rs b/clients/rust/crates/mxgw-cli/src/bench.rs index eda3856e..1b70ad2c 100644 --- a/clients/rust/crates/mxgw-cli/src/bench.rs +++ b/clients/rust/crates/mxgw-cli/src/bench.rs @@ -11,6 +11,9 @@ use zb_mom_ww_mxgateway_client::{next_correlation_id, Error}; use crate::cli::*; use crate::connect::*; +/// Pause after a failed `read_bulk` so a down gateway is not retried in a hot loop. +const FAILURE_BACKOFF: Duration = Duration::from_millis(100); + /// Drive the cross-language ReadBulk stress benchmark from Rust: opens its /// own session, subscribes to `bulk_size` tags so the worker's per-session /// value cache populates from real OnDataChange events, hammers ReadBulk in @@ -86,9 +89,14 @@ pub(crate) async fn run_bench_read_bulk( // setup is amortised before the measurement window opens. let warmup_deadline = Instant::now() + Duration::from_secs(warmup_seconds); while Instant::now() < warmup_deadline { - let _ = session + if session .read_bulk(server_handle, tags_ref, timeout_ms_param) - .await; + .await + .is_err() + { + // Back off so a dead gateway is not hammered in a hot loop. + tokio::time::sleep(FAILURE_BACKOFF).await; + } } // Steady-state measurement window: capture per-call latency as @@ -119,7 +127,10 @@ pub(crate) async fn run_bench_read_bulk( } } } - Err(_) => failed_calls += 1, + Err(_) => { + failed_calls += 1; + tokio::time::sleep(FAILURE_BACKOFF).await; + } } } let steady_elapsed = steady_start.elapsed(); diff --git a/clients/rust/crates/mxgw-cli/src/cli.rs b/clients/rust/crates/mxgw-cli/src/cli.rs index 70c757db..332305ef 100644 --- a/clients/rust/crates/mxgw-cli/src/cli.rs +++ b/clients/rust/crates/mxgw-cli/src/cli.rs @@ -543,6 +543,28 @@ pub(crate) struct ConnectionArgs { } impl ConnectionArgs { + /// Identity of the connection for batch-mode client reuse: every field that + /// changes how the channel is dialed, including the API key actually + /// resolved (flag or environment variable). Held in memory only. + pub(crate) fn cache_key(&self) -> String { + let api_key = self + .api_key + .clone() + .or_else(|| env::var(&self.api_key_env).ok()) + .unwrap_or_default(); + format!( + "{}|{}|{}|{:?}|{:?}|{}|{}|{}", + self.endpoint, + api_key, + !self.tls || self.plaintext, + self.ca_file, + self.server_name_override, + self.require_certificate_validation, + self.connect_timeout_seconds, + self.call_timeout_seconds + ) + } + pub(crate) fn options(&self) -> ClientOptions { let mut options = ClientOptions::new(self.endpoint.clone()) .with_plaintext(!self.tls || self.plaintext) diff --git a/clients/rust/crates/mxgw-cli/src/connect.rs b/clients/rust/crates/mxgw-cli/src/connect.rs index 227f67e5..5e0cb732 100644 --- a/clients/rust/crates/mxgw-cli/src/connect.rs +++ b/clients/rust/crates/mxgw-cli/src/connect.rs @@ -1,15 +1,77 @@ //! Gateway and Galaxy client construction helpers. +//! +//! In `batch` mode every command line is dispatched through the same helpers. +//! Dialing a fresh channel per line (TCP + TLS handshake + HTTP/2 settings + CA +//! file read) defeats the point of batch mode, so [`enable_batch_reuse`] turns +//! on a per-process cache that hands out clones of one client per distinct +//! connection. Clones share the underlying channel. + +use std::collections::HashMap; +use std::sync::Mutex; use zb_mom_ww_mxgateway_client::{Error, GalaxyClient, GatewayClient}; use crate::cli::*; +#[derive(Default)] +struct BatchClients { + gateway: HashMap, + galaxy: HashMap, +} + +/// `None` outside batch mode (every command dials its own channel). +static BATCH_CLIENTS: Mutex> = Mutex::new(None); + +/// Reuse one gateway/Galaxy client per distinct connection for the rest of the +/// process. Called once by the batch loop. +pub(crate) fn enable_batch_reuse() { + *BATCH_CLIENTS.lock().expect("batch client cache poisoned") = Some(BatchClients::default()); +} + pub(crate) async fn connect(connection: ConnectionArgs) -> Result { - GatewayClient::connect(connection.options()).await + let key = connection.cache_key(); + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_ref() + { + if let Some(client) = clients.gateway.get(&key) { + return Ok(client.clone()); + } + } + + let client = GatewayClient::connect(connection.options()).await?; + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_mut() + { + clients.gateway.insert(key, client.clone()); + } + Ok(client) } pub(crate) async fn connect_galaxy(connection: ConnectionArgs) -> Result { - GalaxyClient::connect(connection.options()).await + let key = connection.cache_key(); + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_ref() + { + if let Some(client) = clients.galaxy.get(&key) { + return Ok(client.clone()); + } + } + + let client = GalaxyClient::connect(connection.options()).await?; + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_mut() + { + clients.galaxy.insert(key, client.clone()); + } + Ok(client) } pub(crate) async fn session_for( diff --git a/clients/rust/crates/mxgw-cli/src/tests.rs b/clients/rust/crates/mxgw-cli/src/tests.rs index 6beb5144..fc163ee4 100644 --- a/clients/rust/crates/mxgw-cli/src/tests.rs +++ b/clients/rust/crates/mxgw-cli/src/tests.rs @@ -453,3 +453,16 @@ fn alarm_feed_snapshot_status_renders_in_summary_and_json() { let value = crate::events::alarm_feed_message_to_json(&message); assert_eq!(value["snapshotStatus"]["truncated"], true); } + +#[test] +fn batch_cache_key_separates_distinct_connections_and_merges_identical_ones() { + let first = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_1"]); + let same = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_1"]); + let other_endpoint = + connection_from_ping(&["--endpoint", "http://b:1", "--api-key", "mxgw_x_1"]); + let other_key = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_2"]); + + assert_eq!(first.cache_key(), same.cache_key()); + assert_ne!(first.cache_key(), other_endpoint.cache_key()); + assert_ne!(first.cache_key(), other_key.cache_key()); +}