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| {