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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use super::Reconnectable;
use std::io;
use std::time::Duration;
use strum::Display;
use tokio::sync::watch;
use tokio::task::JoinHandle;
#[derive(Clone)]
pub struct ConnectionWatcher(pub(super) watch::Receiver<ConnectionState>);
impl ConnectionWatcher {
pub async fn next(&mut self) -> Option<ConnectionState> {
self.0.changed().await.ok()?;
Some(self.last())
}
pub fn has_changed(&self) -> bool {
self.0.has_changed().ok().unwrap_or(false)
}
pub fn last(&self) -> ConnectionState {
*self.0.borrow()
}
pub fn on_change<F>(&self, mut f: F) -> JoinHandle<()>
where
F: FnMut(ConnectionState) + Send + 'static,
{
let rx = self.0.clone();
tokio::spawn(async move {
let mut watcher = Self(rx);
while let Some(state) = watcher.next().await {
f(state);
}
})
}
}
#[derive(Copy, Clone, Debug, Display, PartialEq, Eq)]
#[strum(serialize_all = "snake_case")]
pub enum ConnectionState {
Reconnecting,
Connected,
Disconnected,
}
impl ConnectionState {
pub fn is_reconnecting(&self) -> bool {
matches!(self, Self::Reconnecting)
}
pub fn is_connected(&self) -> bool {
matches!(self, Self::Connected)
}
pub fn is_disconnected(&self) -> bool {
matches!(self, Self::Disconnected)
}
}
#[derive(Clone, Debug)]
pub enum ReconnectStrategy {
Fail,
ExponentialBackoff {
base: Duration,
factor: f64,
max_duration: Option<Duration>,
max_retries: Option<usize>,
timeout: Option<Duration>,
},
FibonacciBackoff {
base: Duration,
max_duration: Option<Duration>,
max_retries: Option<usize>,
timeout: Option<Duration>,
},
FixedInterval {
interval: Duration,
max_retries: Option<usize>,
timeout: Option<Duration>,
},
}
impl Default for ReconnectStrategy {
fn default() -> Self {
Self::Fail
}
}
impl ReconnectStrategy {
pub async fn reconnect<T: Reconnectable>(&mut self, reconnectable: &mut T) -> io::Result<()> {
if self.is_fail() {
return Err(io::Error::from(io::ErrorKind::ConnectionAborted));
}
let mut previous_sleep = None;
let mut current_sleep = self.initial_sleep_duration();
let mut retries_remaining = self.max_retries();
let timeout = self.timeout();
let max_duration = self.max_duration();
let mut result = Ok(());
while retries_remaining.is_none() || retries_remaining > Some(0) {
result = match timeout {
Some(timeout) => {
match tokio::time::timeout(timeout, reconnectable.reconnect()).await {
Ok(x) => x,
Err(x) => Err(x.into()),
}
}
None => reconnectable.reconnect().await,
};
if result.is_ok() {
return Ok(());
}
if let Some(remaining) = retries_remaining.as_mut() {
if *remaining > 0 {
*remaining -= 1;
}
}
tokio::time::sleep(current_sleep).await;
let next_sleep = self.adjust_sleep(previous_sleep, current_sleep);
previous_sleep = Some(current_sleep);
current_sleep = if let Some(duration) = max_duration {
std::cmp::min(next_sleep, duration)
} else {
next_sleep
};
}
result
}
pub fn is_fail(&self) -> bool {
matches!(self, Self::Fail)
}
pub fn is_exponential_backoff(&self) -> bool {
matches!(self, Self::ExponentialBackoff { .. })
}
pub fn is_fibonacci_backoff(&self) -> bool {
matches!(self, Self::FibonacciBackoff { .. })
}
pub fn is_fixed_interval(&self) -> bool {
matches!(self, Self::FixedInterval { .. })
}
pub fn max_duration(&self) -> Option<Duration> {
match self {
ReconnectStrategy::Fail => None,
ReconnectStrategy::ExponentialBackoff { max_duration, .. } => *max_duration,
ReconnectStrategy::FibonacciBackoff { max_duration, .. } => *max_duration,
ReconnectStrategy::FixedInterval { .. } => None,
}
}
pub fn max_retries(&self) -> Option<usize> {
match self {
ReconnectStrategy::Fail => None,
ReconnectStrategy::ExponentialBackoff { max_retries, .. } => *max_retries,
ReconnectStrategy::FibonacciBackoff { max_retries, .. } => *max_retries,
ReconnectStrategy::FixedInterval { max_retries, .. } => *max_retries,
}
}
pub fn timeout(&self) -> Option<Duration> {
match self {
ReconnectStrategy::Fail => None,
ReconnectStrategy::ExponentialBackoff { timeout, .. } => *timeout,
ReconnectStrategy::FibonacciBackoff { timeout, .. } => *timeout,
ReconnectStrategy::FixedInterval { timeout, .. } => *timeout,
}
}
fn initial_sleep_duration(&self) -> Duration {
match self {
ReconnectStrategy::Fail => Duration::new(0, 0),
ReconnectStrategy::ExponentialBackoff { base, .. } => *base,
ReconnectStrategy::FibonacciBackoff { base, .. } => *base,
ReconnectStrategy::FixedInterval { interval, .. } => *interval,
}
}
fn adjust_sleep(&self, prev: Option<Duration>, curr: Duration) -> Duration {
match self {
ReconnectStrategy::Fail => Duration::new(0, 0),
ReconnectStrategy::ExponentialBackoff { factor, .. } => {
let next_millis = (curr.as_millis() as f64) * factor;
Duration::from_millis(if next_millis > (std::u64::MAX as f64) {
std::u64::MAX
} else {
next_millis as u64
})
}
ReconnectStrategy::FibonacciBackoff { .. } => {
let prev = prev.unwrap_or_else(|| Duration::new(0, 0));
prev.checked_add(curr).unwrap_or(Duration::MAX)
}
ReconnectStrategy::FixedInterval { .. } => curr,
}
}
}