From d8ac52b77d5669ac46667d9a2b9700338d5cc1e5 Mon Sep 17 00:00:00 2001 From: maia Date: Tue, 24 Nov 2026 19:06:32 +0100 Subject: [PATCH] swarm-nats-auth: keep trying to reach the queue instead of exiting The responder made one connect and ended on its first refusal. In a pod the queue's own container starts beside it, and the responder's startup (a store login and four key loads) can finish before the server listens, so every new pod started with a crash and a restart that `RESTARTS` could not tell from a real failure. The client now connects in the background (retry_on_initial_connect), with the library's own delays, and logs one warn line per failed attempt, so a server that never comes up still shows in the log. The health endpoint's /readyz already follows the connection state, so the pod is not Ready until the responder is connected. The "connected" log line moves to the connect event; the line after the subscribe says "subscribed". Closes #6841 --- swarm-nats-auth/src/main.rs | 88 ++++++++++++++++++++++++++++++++++--- 1 file changed, 82 insertions(+), 6 deletions(-) diff --git a/swarm-nats-auth/src/main.rs b/swarm-nats-auth/src/main.rs index 987911873..9bee8a94d 100644 --- a/swarm-nats-auth/src/main.rs +++ b/swarm-nats-auth/src/main.rs @@ -260,11 +260,7 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul let (callout_xkey, issuer, user_seed) = load_callout_keys(&keys).await?; let client_secret = load_client_secret(&keys, &args).await?; let store = swarm_agent_verify::Store::new(settings, args.store_cert_role.clone()); - let client = async_nats::ConnectOptions::with_nkey(user_seed) - .name("swarm-nats-auth") - .connect(&args.nats_url) - .await - .with_context(|| format!("connect to {}", args.nats_url))?; + let client = connect(user_seed, &args.nats_url).await?; swarm_queue_client::ready_when_connected(&health, &client); let requests = client .subscribe(AUTH_SUBJECT) @@ -273,7 +269,7 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul tracing::info!( nats_url = %args.nats_url, subject = AUTH_SUBJECT, - "swarm-nats-auth: connected, awaiting authorization requests" + "swarm-nats-auth: subscribed, awaiting authorization requests" ); let responder = Arc::new(Responder { @@ -485,6 +481,55 @@ fn open_request( } } +/// The longest wait between two attempts to reach the server. +const MAX_CONNECT_DELAY: std::time::Duration = std::time::Duration::from_secs(4); + +/// The wait before attempt number `attempt` (counted from 1) to reach the +/// server: none for the first, then doubling from 2 ms up to +/// [`MAX_CONNECT_DELAY`], which is the library's own default. +fn connect_delay(attempt: usize) -> std::time::Duration { + if attempt <= 1 { + return std::time::Duration::ZERO; + } + let exponent = u32::try_from(attempt - 1).unwrap_or(u32::MAX); + std::time::Duration::from_millis(2_u64.saturating_pow(exponent)).min(MAX_CONNECT_DELAY) +} + +/// A client for the queue, signed in with the callout user's nkey. +/// +/// It does not wait for the server: in a pod this container starts beside the +/// queue's own, and the responder finishes its startup (a store login and the +/// key loads) before the server listens, which a connect that fails once turns +/// into a crash on every new pod. The client keeps trying in the background +/// instead, one `warn` line per failed attempt so a server that never comes up +/// still shows in the log, and the health endpoint's `/readyz` says not ready +/// until the connection is up (see [`swarm_queue_client::ready_when_connected`]), +/// so the pod is not Ready before the responder can answer. +async fn connect(user_seed: String, nats_url: &str) -> anyhow::Result { + async_nats::ConnectOptions::with_nkey(user_seed) + .name("swarm-nats-auth") + .retry_on_initial_connect() + // Called before each attempt, so every call after the first follows a + // failed one (this also covers a connection that drops later). + .reconnect_delay_callback(|attempt| { + if attempt > 1 { + tracing::warn!( + attempt, + "swarm-nats-auth: the NATS server is not answering yet; trying again" + ); + } + connect_delay(attempt) + }) + .event_callback(|event| async move { + if matches!(event, async_nats::Event::Connected) { + tracing::info!("swarm-nats-auth: connected to the NATS server"); + } + }) + .connect(nats_url) + .await + .with_context(|| format!("connect to {nats_url}")) +} + /// The callout xkey, the issuer key, and the user key's seed, read from the /// store and never created here; see `xkey` and `nkey`. async fn load_callout_keys( @@ -605,6 +650,37 @@ async fn introspected( mod tests { use super::*; + /// The wait before each attempt is the library's own default: none, then + /// doubling from 2 ms, capped at 4 s. + #[test] + fn the_connect_delay_doubles_to_its_cap() { + use std::time::Duration; + assert_eq!(connect_delay(0), Duration::ZERO); + assert_eq!(connect_delay(1), Duration::ZERO); + assert_eq!(connect_delay(2), Duration::from_millis(2)); + assert_eq!(connect_delay(3), Duration::from_millis(4)); + assert_eq!(connect_delay(10), Duration::from_millis(512)); + assert_eq!(connect_delay(13), MAX_CONNECT_DELAY); + assert_eq!(connect_delay(usize::MAX), MAX_CONNECT_DELAY); + } + + /// A server that is not listening yet must not end the responder: the pod + /// starts the responder beside the server, and a connect that fails once + /// crashed the container on every new pod. The client comes back at once, + /// connecting in the background, and says it is not connected, which is + /// what keeps `/readyz` not ready. + #[tokio::test] + async fn a_server_that_is_not_listening_does_not_end_the_connect() { + let seed = nkeys::KeyPair::new_user().seed().expect("a user seed"); + let client = connect(seed, "nats://127.0.0.1:0") + .await + .expect("the connect returns without a server"); + assert!( + swarm_queue_client::ensure_connected(&client).is_err(), + "a client with no server is not connected, so the pod is not ready" + ); + } + /// The responder's flags, parsed the way `main` parses them. fn responder(argv: [&str; N]) -> Result { Cli::try_parse_from(argv).map(|cli| {