use std::time::Duration;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ReconnectPolicy {
pub enabled: bool,
pub initial_delay: Duration,
pub max_delay: Duration,
pub backoff_factor: f64,
pub max_retries: Option<u32>,
pub jitter: bool,
}
impl Default for ReconnectPolicy {
fn default() -> Self {
Self {
enabled: true,
initial_delay: Duration::from_millis(100),
max_delay: Duration::from_secs(30),
backoff_factor: 2.0,
max_retries: None,
jitter: true,
}
}
}
impl ReconnectPolicy {
pub fn disabled() -> Self {
Self {
enabled: false,
..Default::default()
}
}
pub fn delay_for_attempt(&self, attempt: u32) -> Duration {
let base = self.initial_delay.as_secs_f64() * self.backoff_factor.powi(attempt as i32);
let clamped = base.min(self.max_delay.as_secs_f64());
Duration::from_secs_f64(clamped)
}
pub fn should_retry(&self, attempts: u32) -> bool {
self.enabled && self.max_retries.is_none_or(|max| attempts < max)
}
}