moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Exponential backoff for subscription drivers that pause on
//! transient errors before retrying. Mirror of TS
//! `Effect.retryWithBackoff` — minus the Effect typeclass machinery.
//!
//! The driver pattern:
//!
//! ```ignore
//! let mut backoff = ExponentialBackoff::default();
//! loop {
//!     if cancel.is_cancelled() { break; }
//!     match pull_batch().await {
//!         Ok(batch) => {
//!             backoff.reset();
//!             runtime.apply(|s| fold(s, batch)).await?;
//!         }
//!         Err(_) => {
//!             let wait = backoff.next_delay();
//!             moonproof_utils::rt::sleep(wait).await;
//!         }
//!     }
//! }
//! ```

use std::time::Duration;

/// Exponential backoff with cap. `next_delay` doubles the previous
/// delay (clamped to `max_delay`) and returns it; `reset` zeroes the
/// state.
#[derive(Debug, Clone)]
pub struct ExponentialBackoff {
    current: Duration,
    initial: Duration,
    max: Duration,
    multiplier: u32,
    jitter: bool,
}

impl ExponentialBackoff {
    /// Default — 100ms initial, doubles up to 30s.
    #[must_use]
    pub fn new() -> Self {
        Self {
            current: Duration::ZERO,
            initial: Duration::from_millis(100),
            max: Duration::from_secs(30),
            multiplier: 2,
            jitter: false,
        }
    }

    /// Add up to +25% random jitter to every returned delay so many
    /// clients recovering from the same outage don't reconnect in
    /// lockstep.
    #[must_use]
    pub fn with_jitter(mut self) -> Self {
        self.jitter = true;
        self
    }

    #[must_use]
    pub fn with_initial(mut self, initial: Duration) -> Self {
        self.initial = initial;
        self
    }

    #[must_use]
    pub fn with_max(mut self, max: Duration) -> Self {
        self.max = max;
        self
    }

    #[must_use]
    pub fn with_multiplier(mut self, multiplier: u32) -> Self {
        self.multiplier = multiplier.max(1);
        self
    }

    /// Compute the next delay and advance internal state. First call
    /// returns the initial delay; subsequent calls double until
    /// hitting the cap.
    pub fn next_delay(&mut self) -> Duration {
        if self.current.is_zero() {
            self.current = self.initial;
        } else {
            // Saturating multiplication via nanoseconds so the cap
            // applies cleanly without overflow.
            let next_nanos = self
                .current
                .as_nanos()
                .saturating_mul(u128::from(self.multiplier));
            let max_nanos = self.max.as_nanos();
            let clamped = next_nanos.min(max_nanos);
            self.current = Duration::from_nanos(u64::try_from(clamped).unwrap_or(u64::MAX));
        }
        if self.jitter {
            // Stdlib-only jitter source; cryptographic quality is
            // irrelevant here, spread is all that matters.
            let nanos = u64::try_from(self.current.as_nanos()).unwrap_or(u64::MAX);
            let seed = moonproof_utils::rt::SystemTime::now()
                .duration_since(moonproof_utils::rt::UNIX_EPOCH)
                .map_or(0, |d| u64::from(d.subsec_nanos()));
            let jitter = nanos / 4;
            let extra = if jitter == 0 { 0 } else { seed % jitter };
            self.current
                .checked_add(Duration::from_nanos(extra))
                .unwrap_or(self.current)
        } else {
            self.current
        }
    }

    /// Reset state — call after a successful operation so the next
    /// failure starts the ladder over.
    pub fn reset(&mut self) {
        self.current = Duration::ZERO;
    }

    /// Current delay without advancing state.
    #[must_use]
    pub fn current(&self) -> Duration {
        self.current
    }
}

impl Default for ExponentialBackoff {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn first_call_returns_initial() {
        let mut b = ExponentialBackoff::new();
        assert_eq!(b.next_delay(), Duration::from_millis(100));
    }

    #[test]
    fn doubles_each_call_up_to_cap() {
        let mut b = ExponentialBackoff::new()
            .with_initial(Duration::from_millis(50))
            .with_max(Duration::from_millis(400));
        assert_eq!(b.next_delay(), Duration::from_millis(50));
        assert_eq!(b.next_delay(), Duration::from_millis(100));
        assert_eq!(b.next_delay(), Duration::from_millis(200));
        assert_eq!(b.next_delay(), Duration::from_millis(400));
        // Capped.
        assert_eq!(b.next_delay(), Duration::from_millis(400));
    }

    #[test]
    fn reset_returns_to_initial() {
        let mut b = ExponentialBackoff::new();
        b.next_delay();
        b.next_delay();
        b.reset();
        assert_eq!(b.current(), Duration::ZERO);
        assert_eq!(b.next_delay(), Duration::from_millis(100));
    }

    #[test]
    fn custom_multiplier_applies() {
        let mut b = ExponentialBackoff::new()
            .with_initial(Duration::from_millis(100))
            .with_multiplier(3)
            .with_max(Duration::from_secs(60));
        assert_eq!(b.next_delay(), Duration::from_millis(100));
        assert_eq!(b.next_delay(), Duration::from_millis(300));
        assert_eq!(b.next_delay(), Duration::from_millis(900));
    }

    #[test]
    fn jitter_stays_within_base_and_plus_25pct() {
        // Jitter only adds (never subtracts) and is capped at +25%, so
        // every sample sits in [base, base * 1.25].
        let base = Duration::from_secs(4);
        for _ in 0..64 {
            let mut b = ExponentialBackoff::new()
                .with_initial(base)
                .with_max(base)
                .with_jitter();
            let d = b.next_delay();
            assert!(d >= base, "jitter must not shrink the delay: {d:?}");
            assert!(
                d <= base + base / 4,
                "jitter must not exceed +25%: {d:?} > {:?}",
                base + base / 4
            );
        }
    }

    #[test]
    fn jitter_still_respects_the_cap_ladder() {
        // With jitter on, the pre-jitter ladder still doubles toward
        // the cap — jitter rides on top of the capped value.
        let mut b = ExponentialBackoff::new()
            .with_initial(Duration::from_secs(1))
            .with_max(Duration::from_secs(2))
            .with_jitter();
        // current (pre-jitter) advances 1s -> 2s -> capped 2s.
        b.next_delay();
        b.next_delay();
        let third = b.next_delay();
        assert!(third >= Duration::from_secs(2));
        assert!(third <= Duration::from_secs(2) + Duration::from_millis(500));
    }
}