pushwire-client 0.1.1

Generic multiplexed push client with WebSocket and SSE transports
Documentation
use std::time::Duration;

/// Policy controlling automatic reconnection behavior.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ReconnectPolicy {
    /// Whether automatic reconnection is enabled.
    pub enabled: bool,
    /// Initial delay before first reconnect attempt.
    pub initial_delay: Duration,
    /// Maximum delay between reconnect attempts.
    pub max_delay: Duration,
    /// Multiplier applied to delay after each failed attempt.
    pub backoff_factor: f64,
    /// Maximum number of retries. `None` = infinite.
    pub max_retries: Option<u32>,
    /// Add random jitter to delay to prevent thundering herd.
    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 {
    /// Disabled reconnection — connection failure is permanent.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }

    /// Compute delay for the nth attempt (0-indexed).
    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)
    }

    /// Whether we should retry after the given number of attempts.
    pub fn should_retry(&self, attempts: u32) -> bool {
        self.enabled && self.max_retries.is_none_or(|max| attempts < max)
    }
}