Struct Backoff
pub struct Backoff { /* private fields */ }Expand description
A seeded, jittered, capped exponential backoff, with a limit on attempts.
next_delay draws the next wait, or says the attempts
are spent; reset starts again after a success. The state is
the caller’s to keep between runs, so a run that returns and is driven again
does not restart the doubling unless the caller says so.
§Examples
use core::num::NonZeroU32;
use core::time::Duration;
use happenstance_sync::runner::Backoff;
let cap = Duration::from_secs(30);
let mut backoff = Backoff::new(Duration::from_millis(100), cap, 0x5EED)?
.with_attempts(NonZeroU32::MIN.saturating_add(2));
let drawn: Vec<Duration> = core::iter::from_fn(|| backoff.next_delay()).collect();
assert_eq!(drawn.len(), 3, "three attempts, then spent");
assert!(drawn.iter().all(|delay| *delay <= cap));Implementations§
§impl Backoff
impl Backoff
pub const DEFAULT_ATTEMPTS: NonZeroU32
pub const DEFAULT_ATTEMPTS: NonZeroU32
How many delays a backoff draws before it is spent, unless
with_attempts says otherwise. Ten doublings
of a 100 ms base, capped at 30 s, wait about a minute in all.
pub const fn new(
base: Duration,
cap: Duration,
seed: u64,
) -> Result<Self, BackoffError>
pub const fn new( base: Duration, cap: Duration, seed: u64, ) -> Result<Self, BackoffError>
A backoff whose first delay is at most base, doubling to at most cap,
jittered from seed, spent after DEFAULT_ATTEMPTS.
A zero cap (and so a zero base) is accepted: every delay is zero,
and a run retries without waiting until the attempts are spent. That
suits a test or a caller that paces retries itself; a deployment wants
a cap above zero.
§Errors
BackoffError::BaseAboveCap if base exceeds cap.
pub const fn with_attempts(self, attempts: NonZeroU32) -> Self
pub const fn with_attempts(self, attempts: NonZeroU32) -> Self
The same backoff, spent after attempts delays.
pub fn next_delay(&mut self) -> Option<Duration>
pub fn next_delay(&mut self) -> Option<Duration>
The next delay, or None once the attempts are spent.
The n-th delay since the last reset (from zero) is drawn uniformly from
[c/2, c] for c = min(cap, base · 2ⁿ), so none exceeds the cap.
pub const fn reset(&mut self)
pub const fn reset(&mut self)
Starts the doubling and the attempt count again, after a success. The generator keeps its place, so the next sequence is not the last one.