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