diff --git a/swarm-queue-client/src/lib.rs b/swarm-queue-client/src/lib.rs index c9589ffbe..516f684f9 100644 --- a/swarm-queue-client/src/lib.rs +++ b/swarm-queue-client/src/lib.rs @@ -1332,9 +1332,11 @@ 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, so it is retried no sooner than [`ROTATION_FLOOR`] later, not -/// hammered; the same floor holds after a rotation that worked. If every try fails the connection still ends at the expiry and the -/// reconnect path takes over, as it did before this task existed. +/// 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 +/// still ends at the expiry and the reconnect path takes over, as it did +/// before this task existed. /// /// Runs for the life of the process, like the client it keeps: it holds a clone /// of the `Client`, so dropping the caller's clones never closes the @@ -1348,24 +1350,96 @@ async fn rotate_before_expiry( http: reqwest::Client, cfg: QueueConfig, ) { + let mut failures = 0; loop { - tokio::time::sleep(rotation_wait(cache.rotate_in().await)).await; - // `rotate` looks again once it holds the lock: the token may have been - // replaced by a reconnect during the sleep, and the clock may have moved. - match cache.rotate(|| mint_token(&http, &cfg, None, None)).await { - Ok(false) => {} - Ok(true) => { - if let Err(e) = client.force_reconnect().await { + rotation_pass( + &cache, + &mut failures, + 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 + // clock may have moved. + let rotated = cache.rotate(|| mint_token(&http, &cfg, None, None)).await?; + if rotated && let Err(e) = client.force_reconnect().await { tracing::warn!( error = %e, "reconnecting to the queue with the next token failed" ); } - } - Err(e) => tracing::warn!( + Ok(rotated) + }, + ) + .await; + } +} + +/// 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`]. +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) +} + +/// 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)) +} + +/// 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. +/// +/// 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( + cache: &TokenCache, + failures: &mut u32, + sleep: S, + jitter: J, + rotate: R, +) where + 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) + }; + sleep(wait).await; + match rotate().await { + Ok(_) => *failures = 0, + Err(e) => { + *failures = failures.saturating_add(1); + tracing::warn!( error = %chain(&e), + failures = *failures, "minting the next queue token ahead of expiry failed; retrying" - ), + ); } } } @@ -1946,6 +2020,151 @@ mod tests { assert_eq!(mints.load(Ordering::SeqCst), 2, "the connect did not mint"); } + /// 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 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, + mints: bool, + ) -> std::time::Duration { + let slept = std::sync::Mutex::new(std::time::Duration::ZERO); + rotation_pass( + cache, + failures, + |wait| { + *slept.lock().expect("not poisoned") = wait; + clock.advance(wait.as_secs()); + async {} + }, + |_| jitter, + || { + cache.rotate(move || async move { + if mints { + Ok(CachedToken { + token: "rotated".to_owned(), + lifetime: std::time::Duration::from_secs(3599), + }) + } else { + Err(Error::ClientSecret { + path: "secret".to_owned(), + source: std::io::Error::other("the identity provider refused"), + }) + } + }) + }, + ) + .await; + *slept.lock().expect("not poisoned") + } + + /// A refused rotation is retried after the floor, then twice as long each + /// time, and a rotation that works puts the schedule back. + #[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; + + // The first look waits for the rotation to fall due, as before. + assert_eq!( + pass(&clock, &cache, &mut failures, none, false).await, + secs(3599 - 120) + ); + for expected in [30, 60, 120] { + assert_eq!( + pass(&clock, &cache, &mut failures, none, false).await, + secs(expected) + ); + } + assert_eq!(failures, 4); + + // Jitter is added to the retry wait. + 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, + 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) + ); + } + + /// A reconnect that mints while the rotation is failing replaces the + /// token under the loop; the next look finds nothing due and the wait is + /// the schedule's again, not the retry wait. + #[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; + + pass(&clock, &cache, &mut failures, none, false).await; + assert_eq!( + pass(&clock, &cache, &mut failures, none, false).await, + secs(30) + ); + assert_eq!(failures, 2); + + // 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), + "this look still waited the retry wait" + ); + assert_eq!(failures, 0, "nothing was due, so no rotation ran"); + assert_eq!( + pass(&clock, &cache, &mut failures, none, false).await, + secs(3599 - 120 - 60) + ); + } + + #[test] + fn the_retry_wait_doubles_from_the_floor_to_the_cap() { + 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); + } + + #[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); + } + assert_eq!( + rotation_jitter(std::time::Duration::ZERO), + std::time::Duration::ZERO + ); + } + /// The first attempt after a disconnect is immediate; the backoff, and its /// cap, protect the identity provider from the second attempt on. #[test]