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
use std::time::Duration;
pub type DurationIterator = Box<dyn Iterator<Item = Duration> + Send + Sync>;
pub struct ReconnectOptions {
pub retries_to_attempt_fn: Box<dyn Fn() -> DurationIterator + Send + Sync>,
pub exit_if_first_connect_fails: bool,
pub on_connect_callback: Box<dyn Fn() + Send + Sync>,
pub on_disconnect_callback: Box<dyn Fn() + Send + Sync>,
pub on_connect_fail_callback: Box<dyn Fn() + Send + Sync>,
}
impl ReconnectOptions {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
ReconnectOptions {
retries_to_attempt_fn: Box::new(get_standard_reconnect_strategy),
exit_if_first_connect_fails: true,
on_connect_callback: Box::new(|| {}),
on_disconnect_callback: Box::new(|| {}),
on_connect_fail_callback: Box::new(|| {}),
}
}
pub fn with_retries_generator<F, I, IN>(mut self, retries_generator: F) -> Self
where
F: 'static + Send + Sync + Fn() -> IN,
I: 'static + Send + Sync + Iterator<Item = Duration>,
IN: IntoIterator<IntoIter = I, Item = Duration>,
{
self.retries_to_attempt_fn = Box::new(move || Box::new(retries_generator().into_iter()));
self
}
pub fn with_exit_if_first_connect_fails(mut self, value: bool) -> Self {
self.exit_if_first_connect_fails = value;
self
}
pub fn with_on_connect_callback(mut self, cb: impl Fn() + 'static + Send + Sync) -> Self {
self.on_connect_callback = Box::new(cb);
self
}
pub fn with_on_disconnect_callback(mut self, cb: impl Fn() + 'static + Send + Sync) -> Self {
self.on_disconnect_callback = Box::new(cb);
self
}
pub fn with_on_connect_fail_callback(mut self, cb: impl Fn() + 'static + Send + Sync) -> Self {
self.on_connect_fail_callback = Box::new(cb);
self
}
}
fn get_standard_reconnect_strategy() -> DurationIterator {
let initial_attempts = vec![
Duration::from_secs(5),
Duration::from_secs(10),
Duration::from_secs(20),
Duration::from_secs(30),
Duration::from_secs(40),
Duration::from_secs(50),
Duration::from_secs(60),
Duration::from_secs(60 * 2),
Duration::from_secs(60 * 5),
Duration::from_secs(60 * 10),
Duration::from_secs(60 * 20),
];
let repeat = std::iter::repeat(Duration::from_secs(60 * 30));
let forever_iterator = initial_attempts.into_iter().chain(repeat);
Box::new(forever_iterator)
}