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