Skip to main content

open_net/api/ws/
reconnect.rs

1use crate::{NetError, Result};
2use std::time::{Duration, Instant};
3
4/// Automatic retry policy for one connection cycle; defaults to jittered exponential backoff.
5#[derive(Clone, Debug)]
6pub enum ReconnectPolicy {
7    /// Do not retry failed connections or reconnect after termination.
8    Disabled,
9    /// Retry with jittered exponential backoff and count/elapsed-time limits.
10    Backoff(
11        /// Retry count, delay, and elapsed-time limits for the cycle.
12        BackoffConfig,
13    ),
14}
15
16impl Default for ReconnectPolicy {
17    fn default() -> Self {
18        Self::Backoff(BackoffConfig::default())
19    }
20}
21
22impl ReconnectPolicy {
23    /// Creates a jittered exponential backoff policy without a retry-count or
24    /// cycle-elapsed-time limit.
25    ///
26    /// The delay caps remain the safe defaults from [`BackoffConfig::default`],
27    /// so an unavailable endpoint does not turn retries into a busy loop. A
28    /// session still stops promptly when it is cancelled or closed.
29    /// The policy does not change
30    /// [`ConnectOptions::connect_timeout`](crate::ws::ConnectOptions::connect_timeout); callers
31    /// that also want an unlimited initial connection wait must set that option
32    /// to `None` explicitly.
33    pub fn long_running() -> Self {
34        Self::Backoff(BackoffConfig::unlimited())
35    }
36
37    /// Validates the selected retry policy.
38    pub fn validate(&self) -> Result<()> {
39        match self {
40            Self::Disabled => Ok(()),
41            Self::Backoff(config) => config.validate(),
42        }
43    }
44}
45
46/// Full-jitter exponential backoff parameters; each wait is random from zero to its cap.
47#[derive(Clone, Debug)]
48pub struct BackoffConfig {
49    /// Additional retries after the initial attempt (6 by default; zero disables retries).
50    pub max_retries: usize,
51    /// First retry's random delay cap (250 ms by default); later caps grow by powers of two.
52    pub initial_delay: Duration,
53    /// Maximum random delay cap (8 s by default), which must not be below the initial delay.
54    pub max_delay: Duration,
55    /// Maximum cycle elapsed time including attempts and waits (30 s default); `None` is unlimited.
56    pub max_elapsed: Option<Duration>,
57}
58
59impl Default for BackoffConfig {
60    fn default() -> Self {
61        Self {
62            max_retries: 6,
63            initial_delay: Duration::from_millis(250),
64            max_delay: Duration::from_secs(8),
65            max_elapsed: Some(Duration::from_secs(30)),
66        }
67    }
68}
69
70impl BackoffConfig {
71    /// Creates a backoff configuration with no retry-count or cycle-elapsed-time
72    /// limit while retaining the default jitter delay caps.
73    ///
74    /// `usize::MAX` is used as the retry-count sentinel because the public
75    /// configuration stores a count. The worker treats it as the largest
76    /// representable number of additional attempts and still propagates
77    /// cancellation and shutdown immediately.
78    pub fn unlimited() -> Self {
79        Self {
80            max_retries: usize::MAX,
81            max_elapsed: None,
82            ..Self::default()
83        }
84    }
85
86    /// Validates delay ordering and monotonic deadline representability.
87    pub fn validate(&self) -> Result<()> {
88        validate_duration(self.initial_delay, "reconnect.initial_delay")?;
89        validate_duration(self.max_delay, "reconnect.max_delay")?;
90        if let Some(max_elapsed) = self.max_elapsed {
91            validate_duration(max_elapsed, "reconnect.max_elapsed")?;
92        }
93        if self.max_delay < self.initial_delay {
94            return Err(NetError::config(
95                "reconnect.max_delay",
96                "must be greater than or equal to reconnect.initial_delay",
97            ));
98        }
99        Ok(())
100    }
101}
102
103fn validate_duration(value: Duration, field: &str) -> Result<()> {
104    if value.is_zero() {
105        return Err(NetError::config(field, "must be greater than zero"));
106    }
107    if Instant::now().checked_add(value).is_none() {
108        return Err(NetError::config(
109            field,
110            "must fit a monotonic Instant deadline",
111        ));
112    }
113    Ok(())
114}
115
116#[cfg(test)]
117#[path = "reconnect_tests.rs"]
118mod tests;