use std::collections::VecDeque;
use std::time::Duration;
use crate::correctness::{check_in_range_f64, check_predicate_true, CorrectnessResult};
pub const RECONNECT_WINDOW: Duration = Duration::from_secs(120);
pub const RECONNECT_WINDOW_ATTEMPTS: usize = 3;
pub const RECONNECT_MIN_DELAY: Duration = Duration::from_secs(1);
#[derive(Debug, Default, Clone)]
pub struct ReconnectThrottle {
recent_attempts: VecDeque<std::time::Instant>,
}
impl ReconnectThrottle {
pub fn gated_delay(&mut self, backoff_delay: Duration) -> Duration {
self.prune_expired();
if self.recent_attempts.len() >= RECONNECT_WINDOW_ATTEMPTS {
backoff_delay.max(RECONNECT_MIN_DELAY)
} else {
backoff_delay
}
}
pub fn record_attempt(&mut self) {
self.prune_expired();
self.recent_attempts.push_back(std::time::Instant::now());
}
pub fn attempts_in_window(&self) -> usize {
self.recent_attempts.len()
}
fn prune_expired(&mut self) {
while self
.recent_attempts
.front()
.is_some_and(|oldest| oldest.elapsed() > RECONNECT_WINDOW)
{
self.recent_attempts.pop_front();
}
}
}
#[derive(Debug, Clone)]
pub struct ExponentialBackoff {
delay_initial: Duration,
delay_max: Duration,
delay_current: Duration,
factor: f64,
jitter_ms: u64,
immediate_first: bool,
immediate_first_original: bool,
}
impl ExponentialBackoff {
pub fn new(
delay_initial: Duration,
delay_max: Duration,
factor: f64,
jitter_ms: u64,
immediate_first: bool,
) -> CorrectnessResult<Self> {
check_predicate_true(!delay_initial.is_zero(), "delay_initial must be non-zero")?;
check_predicate_true(
delay_max >= delay_initial,
"delay_max must be >= delay_initial",
)?;
check_in_range_f64(factor, 1.0, 100.0, "factor")?;
Ok(Self {
delay_initial,
delay_max,
delay_current: delay_initial,
factor,
jitter_ms,
immediate_first,
immediate_first_original: immediate_first,
})
}
pub fn next_duration(&mut self) -> Duration {
if self.immediate_first && self.delay_current == self.delay_initial {
self.immediate_first = false;
return Duration::ZERO;
}
use rand::Rng;
let jitter = rand::thread_rng().gen_range(0..=self.jitter_ms);
let base = std::cmp::min(
self.delay_current,
self.delay_max.saturating_sub(Duration::from_millis(self.jitter_ms)),
);
let with_jitter = base + Duration::from_millis(jitter);
let floor = std::cmp::min(self.delay_initial, self.delay_max);
let clamped = with_jitter.clamp(floor, self.delay_max);
let next_nanos = (self.delay_current.as_nanos() as f64 * self.factor) as u64;
self.delay_current =
Duration::from_nanos(next_nanos.min(self.delay_max.as_nanos() as u64));
clamped
}
pub const fn reset(&mut self) {
self.delay_current = self.delay_initial;
self.immediate_first = self.immediate_first_original;
}
pub const fn current_delay(&self) -> Duration {
self.delay_current
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_jitter_exponential_growth_and_cap() {
let mut b = ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_millis(1600),
2.0,
0,
false,
)
.unwrap();
assert_eq!(b.next_duration(), Duration::from_millis(100));
assert_eq!(b.next_duration(), Duration::from_millis(200));
assert_eq!(b.next_duration(), Duration::from_millis(400));
assert_eq!(b.next_duration(), Duration::from_millis(800));
assert_eq!(b.next_duration(), Duration::from_millis(1600));
assert_eq!(b.next_duration(), Duration::from_millis(1600));
}
#[test]
fn validation_errors() {
assert!(ExponentialBackoff::new(Duration::ZERO, Duration::from_secs(1), 2.0, 0, false)
.is_err());
assert!(ExponentialBackoff::new(
Duration::from_secs(2),
Duration::from_secs(1),
2.0,
0,
false
)
.is_err());
assert!(ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_secs(1),
150.0,
0,
false
)
.is_err());
assert!(ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_secs(1),
0.5,
0,
false
)
.is_err());
}
#[test]
fn immediate_first_only_once_and_reset_restores() {
let mut b = ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_millis(1600),
2.0,
0,
true,
)
.unwrap();
assert_eq!(b.next_duration(), Duration::ZERO);
assert_eq!(b.next_duration(), Duration::from_millis(100));
assert_eq!(b.next_duration(), Duration::from_millis(200));
b.reset();
assert_eq!(b.next_duration(), Duration::ZERO);
assert_eq!(b.current_delay(), Duration::from_millis(100));
}
#[test]
fn jitter_within_bounds_and_never_exceeds_max() {
let mut b = ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_secs(1),
2.0,
500,
false,
)
.unwrap();
while b.current_delay() < Duration::from_secs(1) {
b.next_duration();
}
for _ in 0..200 {
let d = b.next_duration();
assert!(!d.is_zero(), "饱和期延迟不得为零");
assert!(d <= Duration::from_secs(1), "延迟不得超过 delay_max");
}
}
#[test]
fn jitter_spreads_at_cap() {
let mut b = ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_secs(1),
2.0,
500,
false,
)
.unwrap();
while b.current_delay() < Duration::from_secs(1) {
b.next_duration();
}
let mut distinct = std::collections::HashSet::new();
for _ in 0..100 {
distinct.insert(b.next_duration());
}
assert!(distinct.len() >= 2, "饱和期抖动必须保持离散分布");
}
#[test]
fn throttle_passes_below_threshold() {
let mut t = ReconnectThrottle::default();
for _ in 0..RECONNECT_WINDOW_ATTEMPTS {
assert_eq!(t.gated_delay(Duration::ZERO), Duration::ZERO);
t.record_attempt();
}
}
#[test]
fn throttle_floors_once_threshold_trips() {
let mut t = ReconnectThrottle::default();
for _ in 0..RECONNECT_WINDOW_ATTEMPTS {
t.record_attempt();
}
assert_eq!(t.gated_delay(Duration::ZERO), RECONNECT_MIN_DELAY);
assert_eq!(
t.gated_delay(Duration::from_millis(25)),
RECONNECT_MIN_DELAY
);
assert_eq!(t.gated_delay(Duration::from_secs(5)), Duration::from_secs(5));
}
}