From bd6d499ab80ca5270dd4e23617ab3284b0de85e2 Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 21:44:22 +0100 Subject: [PATCH] swarm-queue-client: take the token rotation backoff from backon --- Cargo.lock | 1 + swarm-queue-client/Cargo.toml | 3 + swarm-queue-client/src/lib.rs | 216 ++++++++++++++++++---------------- 3 files changed, 117 insertions(+), 103 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 84f34b100..d4ccd29c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5705,6 +5705,7 @@ dependencies = [ "anyhow", "async-nats", "axum", + "backon", "data-encoding", "futures-util", "hive-types", diff --git a/swarm-queue-client/Cargo.toml b/swarm-queue-client/Cargo.toml index 9d3a6fd65..afd5483c1 100644 --- a/swarm-queue-client/Cargo.toml +++ b/swarm-queue-client/Cargo.toml @@ -89,6 +89,9 @@ router-todo = ["async-nats/jetstream"] # above - the connect itself needs none of them. anyhow = { workspace = true, optional = true } async-nats.workspace = true +# The wait between failed token rotations (`rotation_backoff`), the policy +# `hive-agent`'s queue connect already takes from it. +backon.workspace = true hive-types = { workspace = true, optional = true } # `agent_status::roster` collects the stream's subject listing. futures-util = { workspace = true, optional = true } diff --git a/swarm-queue-client/src/lib.rs b/swarm-queue-client/src/lib.rs index 516f684f9..20073317f 100644 --- a/swarm-queue-client/src/lib.rs +++ b/swarm-queue-client/src/lib.rs @@ -1332,9 +1332,9 @@ fn rotation_wait(rotate_in: Option) -> std::time::Duration /// identity provider. /// /// A failed mint costs nothing yet, the current token has [`TOKEN_REFRESH_SKEW`] -/// left. It is retried after [`ROTATION_FLOOR`], then twice as long after each -/// further failure up to [`ROTATION_RETRY_CAP`], with jitter, and the first -/// success restores the normal schedule. If every try fails the connection +/// left. It is retried after [`ROTATION_RETRY_FIRST`], then twice as long after each +/// further failure up to [`ROTATION_RETRY_CAP`], with jitter (see +/// [`rotation_backoff`]), and the first success restores the normal schedule. If every try fails the connection /// still ends at the expiry and the reconnect path takes over, as it did /// before this task existed. /// @@ -1350,13 +1350,13 @@ async fn rotate_before_expiry( http: reqwest::Client, cfg: QueueConfig, ) { - let mut failures = 0; + let mut retry = None; loop { rotation_pass( &cache, - &mut failures, + &mut retry, + rotation_backoff, tokio::time::sleep, - rotation_jitter, || async { // `rotate` looks again once it holds the lock: the token may // have been replaced by a reconnect during the sleep, and the @@ -1376,68 +1376,73 @@ async fn rotate_before_expiry( } /// The longest [`rotate_before_expiry`] waits between tries while rotations -/// keep failing. The wait doubles from [`ROTATION_FLOOR`] up to here, so an -/// identity provider that refuses is asked every few minutes, not every -/// [`ROTATION_FLOOR`]. +/// keep failing, before jitter. The wait doubles from [`ROTATION_RETRY_FIRST`] up +/// to here, so an identity provider that refuses is asked every few minutes, +/// not every few seconds. const ROTATION_RETRY_CAP: std::time::Duration = std::time::Duration::from_mins(5); -/// How long to wait before the next try after `failures` rotations in a row -/// failed: [`ROTATION_FLOOR`] after the first, doubling, at most -/// [`ROTATION_RETRY_CAP`]. -fn rotation_retry_wait(failures: u32) -> std::time::Duration { - let doublings = failures.saturating_sub(1).min(16); - ROTATION_FLOOR - .saturating_mul(2u32.pow(doublings)) - .min(ROTATION_RETRY_CAP) +/// How long [`rotate_before_expiry`] waits after the first failed rotation. +/// +/// Short, because a rotation starts only [`TOKEN_REFRESH_SKEW`] before the token +/// expires and the retries have to fit in that window: waits of 2, 4, 8, 16 and +/// 32 s put the rotation and five retries before the expiry, at 0, 2, 6, 14, 30 +/// and 62 s (a first wait of 30 s would get three tries). +const ROTATION_RETRY_FIRST: std::time::Duration = std::time::Duration::from_secs(2); + +/// The waits between tries while rotations keep failing, without jitter: +/// [`ROTATION_RETRY_FIRST`], doubling, at most [`ROTATION_RETRY_CAP`], and no limit +/// on the tries. The same `backon` policy `hive-agent` takes for its own queue +/// connect; the retry is the only thing that keeps the token fresh, so it never +/// gives up. +fn rotation_builder() -> backon::ExponentialBuilder { + backon::ExponentialBuilder::default() + .with_min_delay(ROTATION_RETRY_FIRST) + .with_max_delay(ROTATION_RETRY_CAP) + .without_max_times() } -/// Up to a fifth of `wait`, from the clock's sub-second reading: enough to -/// spread clients that failed together, with no randomness dependency. -fn rotation_jitter(wait: std::time::Duration) -> std::time::Duration { - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |since| u128::from(since.subsec_nanos())); - let span = wait.as_nanos() / 5; - let extra = nanos.checked_rem(span.saturating_add(1)).unwrap_or(0); - std::time::Duration::from_nanos(u64::try_from(extra).unwrap_or(0)) +/// A fresh run of waits after the first failed rotation: [`rotation_builder`] +/// with jitter, which adds up to the wait again, to spread the clients that +/// failed together. +fn rotation_backoff() -> backon::ExponentialBackoff { + use backon::BackoffBuilder as _; + rotation_builder().with_jitter().build() } /// One look of [`rotate_before_expiry`]: sleep, then `rotate`, which says -/// whether it replaced the token. `failures` counts the rotations that failed -/// in a row. +/// whether it replaced the token. `retry` holds the waits of the rotations that +/// failed in a row, and is `None` while they work. /// -/// The wait is [`rotation_wait`] while rotations work, and -/// [`rotation_retry_wait`] plus `jitter(wait)` once one has failed. A -/// rotation that worked, and a look that found nothing due because a reconnect -/// replaced the token, both end the failures that were counted. `sleep` and -/// `jitter` are parameters so a test drives the passes without a clock. -async fn rotation_pass( +/// The wait is [`rotation_wait`] while `retry` is `None`, and its next wait +/// once a rotation has failed; `build` starts it. A rotation that worked, and a +/// look that found nothing due because a reconnect replaced the token, both +/// drop it, so the next failure starts at [`ROTATION_RETRY_FIRST`] again. `sleep` is a +/// parameter and `build` a choice of the caller, so a test drives the passes +/// without a clock or jitter. +async fn rotation_pass( cache: &TokenCache, - failures: &mut u32, + retry: &mut Option, + build: impl FnOnce() -> B, sleep: S, - jitter: J, rotate: R, ) where + B: Iterator, S: FnOnce(std::time::Duration) -> SFut, SFut: Future, - J: FnOnce(std::time::Duration) -> std::time::Duration, R: FnOnce() -> RFut, RFut: Future>, { - let wait = if *failures == 0 { - rotation_wait(cache.rotate_in().await) - } else { - let wait = rotation_retry_wait(*failures); - wait + jitter(wait) + let wait = match retry { + None => rotation_wait(cache.rotate_in().await), + Some(waits) => waits.next().unwrap_or(ROTATION_RETRY_CAP), }; sleep(wait).await; match rotate().await { - Ok(_) => *failures = 0, + Ok(_) => *retry = None, Err(e) => { - *failures = failures.saturating_add(1); + retry.get_or_insert_with(build); tracing::warn!( error = %chain(&e), - failures = *failures, "minting the next queue token ahead of expiry failed; retrying" ); } @@ -1485,6 +1490,8 @@ mod tests { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use backon::BackoffBuilder as _; + use super::*; /// A store holding `secret`, counting how often it is read. @@ -2021,26 +2028,25 @@ mod tests { } /// One [`rotation_pass`] against `clock`'s cache: the sleep is recorded - /// and moves the clock by that much, `jitter` is added to a retry wait, + /// and moves the clock by that much, the retry waits carry no jitter, /// and the rotation mints a fresh token when `mints` and fails otherwise. /// Returns the wait the pass slept. async fn pass( clock: &FakeClock, cache: &TokenCache, - failures: &mut u32, - jitter: std::time::Duration, + retry: &mut Option, mints: bool, ) -> std::time::Duration { let slept = std::sync::Mutex::new(std::time::Duration::ZERO); rotation_pass( cache, - failures, + retry, + || rotation_builder().build(), |wait| { *slept.lock().expect("not poisoned") = wait; clock.advance(wait.as_secs()); async {} }, - |_| jitter, || { cache.rotate(move || async move { if mints { @@ -2066,46 +2072,32 @@ mod tests { #[tokio::test] async fn failed_rotations_back_off_and_a_success_resets_the_wait() { let secs = std::time::Duration::from_secs; - let none = std::time::Duration::ZERO; let clock = FakeClock::starting_at(START); let (cache, mints) = (clock.cache(), AtomicUsize::new(0)); take(&cache, &mints).await; - let mut failures = 0; + let mut retry = None; // The first look waits for the rotation to fall due, as before. assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, + pass(&clock, &cache, &mut retry, false).await, secs(3599 - 120) ); - for expected in [30, 60, 120] { + for expected in [2, 4, 8, 16, 32, 64, 128, 256, 300, 300] { assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, + pass(&clock, &cache, &mut retry, false).await, secs(expected) ); } - assert_eq!(failures, 4); - // Jitter is added to the retry wait. + // A success resets the retry, and the next wait is the schedule's. + assert_eq!(pass(&clock, &cache, &mut retry, true).await, secs(300)); + assert!(retry.is_none()); assert_eq!( - pass(&clock, &cache, &mut failures, secs(7), false).await, - secs(240 + 7) - ); - - // A success resets the count, and the next wait is the schedule's. - assert_eq!( - pass(&clock, &cache, &mut failures, none, true).await, - secs(300) - ); - assert_eq!(failures, 0); - assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, + pass(&clock, &cache, &mut retry, false).await, secs(3599 - 120) ); - // Presence control: the failure after the reset starts at the floor. - assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, - secs(30) - ); + // Presence control: the failure after the reset starts at the first retry wait. + assert_eq!(pass(&clock, &cache, &mut retry, false).await, secs(2)); } /// A reconnect that mints while the rotation is failing replaces the @@ -2114,55 +2106,73 @@ mod tests { #[tokio::test] async fn a_token_replaced_by_a_reconnect_ends_the_failure_backoff() { let secs = std::time::Duration::from_secs; - let none = std::time::Duration::ZERO; let clock = FakeClock::starting_at(START); let (cache, mints) = (clock.cache(), AtomicUsize::new(0)); take(&cache, &mints).await; - let mut failures = 0; + let mut retry = None; - pass(&clock, &cache, &mut failures, none, false).await; - assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, - secs(30) - ); - assert_eq!(failures, 2); + pass(&clock, &cache, &mut retry, false).await; + assert_eq!(pass(&clock, &cache, &mut retry, false).await, secs(2)); + assert!(retry.is_some()); // The reconnect callback mints; the cached token was inside its skew. assert_eq!(take(&cache, &mints).await, "token-2"); assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, - secs(60), + pass(&clock, &cache, &mut retry, false).await, + secs(4), "this look still waited the retry wait" ); - assert_eq!(failures, 0, "nothing was due, so no rotation ran"); + assert!(retry.is_none(), "nothing was due, so no rotation ran"); assert_eq!( - pass(&clock, &cache, &mut failures, none, false).await, - secs(3599 - 120 - 60) + pass(&clock, &cache, &mut retry, false).await, + secs(3599 - 120 - 4) ); } #[test] - fn the_retry_wait_doubles_from_the_floor_to_the_cap() { + fn the_retry_wait_doubles_from_the_first_wait_to_the_cap_and_never_gives_up() { let secs = std::time::Duration::from_secs; - let waits: Vec<_> = (1..=7).map(rotation_retry_wait).collect(); - assert_eq!( - waits, - [30, 60, 120, 240, 300, 300, 300].map(secs), - "5 min is the cap" - ); - assert_eq!(rotation_retry_wait(u32::MAX), ROTATION_RETRY_CAP); + let mut waits = rotation_builder().build(); + let first: Vec<_> = waits.by_ref().take(10).collect(); + assert_eq!(first, [2, 4, 8, 16, 32, 64, 128, 256, 300, 300].map(secs)); + // The default `backon` policy stops after three tries; this one must not. + assert_eq!(waits.take(10_000).count(), 10_000); } + /// A rotation starts [`TOKEN_REFRESH_SKEW`] before the expiry; the retries + /// have to land inside it, five of them, and the sixth falls after. #[test] - fn the_rotation_jitter_stays_within_a_fifth_of_the_wait() { - let wait = std::time::Duration::from_mins(2); - for _ in 0..1000 { - assert!(rotation_jitter(wait) <= wait / 5); + fn five_retries_land_before_the_token_expires() { + let mut at = std::time::Duration::ZERO; + let landed = rotation_builder() + .build() + .take_while(|wait| { + at += *wait; + at <= TOKEN_REFRESH_SKEW + }) + .count(); + assert_eq!(landed, 5); + } + + /// The jitter adds to the wait and never takes from it, at most the wait + /// again, so a cluster that failed together does not retry together. + #[test] + fn the_rotation_backoff_adds_jitter_within_the_wait() { + let secs = std::time::Duration::from_secs; + let plain: Vec<_> = rotation_builder().build().take(20).collect(); + let mut spread = false; + for _ in 0..50 { + let jittered: Vec<_> = rotation_backoff().take(20).collect(); + for (plain, jittered) in plain.iter().zip(&jittered) { + assert!( + jittered >= plain && *jittered <= *plain * 2, + "{jittered:?} not in [{plain:?}, 2x]" + ); + spread |= jittered != plain; + } } - assert_eq!( - rotation_jitter(std::time::Duration::ZERO), - std::time::Duration::ZERO - ); + assert!(spread, "no wait was jittered"); + assert_eq!(plain[0], secs(2)); } /// The first attempt after a disconnect is immediate; the backoff, and its