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
use std::{
fmt,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
use futures::{
future::{self, Either},
Future,
};
use tokio_executor::{DefaultExecutor, Executor};
use tokio_timer::Timeout;
use crate::error::{self, ConnectionReason};
type WorkFn<T, A> =
dyn Fn(&T, A) -> Box<dyn Future<Item = (), Error = error::Error> + Send> + Send + Sync;
type ConnFn<T> = dyn Fn() -> Box<dyn Future<Item = T, Error = error::Error> + Send> + Send + Sync;
pub(crate) struct Reconnect<A, T> {
state: Arc<RwLock<ReconnectState<T>>>,
work_fn: Arc<WorkFn<T, A>>,
conn_fn: Arc<ConnFn<T>>,
}
impl<A, T> fmt::Debug for Reconnect<A, T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Reconnect")
.field("state", &self.state)
.field("work_fn", &String::from("REDACTED"))
.field("conn_fn", &String::from("REDACTED"))
.finish()
}
}
pub(crate) fn reconnect<A, T, W, C>(
w: W,
c: C,
) -> impl Future<Item = Reconnect<A, T>, Error = error::Error>
where
A: Send + 'static,
W: Fn(&T, A) -> Box<dyn Future<Item = (), Error = error::Error> + Send> + Send + Sync + 'static,
C: Fn() -> Box<dyn Future<Item = T, Error = error::Error> + Send> + Send + Sync + 'static,
T: Clone + Send + Sync + 'static,
{
let r = Reconnect {
state: Arc::new(RwLock::new(ReconnectState::NotConnected)),
work_fn: Arc::new(w),
conn_fn: Arc::new(c),
};
r.reconnect().map(|()| r)
}
enum ReconnectState<T> {
NotConnected,
Connected(T),
ConnectionFailed(Mutex<Option<error::Error>>),
Connecting,
}
impl<T> fmt::Debug for ReconnectState<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ReconnectState::")?;
match self {
NotConnected => write!(f, "NotConnected"),
Connected(_) => write!(f, "Connected"),
ConnectionFailed(_) => write!(f, "ConnectionFailed"),
Connecting => write!(f, "Connecting"),
}
}
}
use self::ReconnectState::*;
const CONNECTION_TIMEOUT_SECONDS: u64 = 10;
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(CONNECTION_TIMEOUT_SECONDS);
impl<A, T> Reconnect<A, T>
where
A: Send + 'static,
T: Clone + Send + Sync + 'static,
{
fn call_work(&self, t: &T, a: A) -> impl Future<Item = (), Error = error::Error> {
let reconnect = self.clone();
(self.work_fn)(t, a).map_err(move |e| {
match e {
error::Error::IO(_) | error::Error::Unexpected(_) => {
log::error!("Error in work_fn will force connection closed, next command will attempt to re-establish it: {}", e);
reconnect.disconnect();
reconnect.reconnect_spawn();
}
_ => ()
}
e
})
}
fn disconnect(&self) {
let mut state = self.state.write().expect("Cannot obtain a write lock");
*state = NotConnected;
}
pub(crate) fn do_work(&self, a: A) -> impl Future<Item = (), Error = error::Error> {
let rv = {
let state = self.state.read().expect("Cannot obtain read lock");
match *state {
NotConnected => Either::B(future::err(error::Error::Connection(
ConnectionReason::NotConnected,
))),
Connected(ref t) => return Either::A(self.call_work(t, a)),
ConnectionFailed(ref e) => {
let mut lock = e.lock().expect("Poisioned lock");
let e = match lock.take() {
Some(e) => e,
None => error::Error::Connection(ConnectionReason::NotConnected),
};
Either::B(future::err(e))
}
Connecting => {
return Either::B(future::err(error::Error::Connection(
ConnectionReason::Connecting,
)));
}
}
};
self.reconnect_spawn();
rv
}
fn reconnect(&self) -> impl Future<Item = (), Error = error::Error> {
let mut state = self.state.write().expect("Cannot obtain write lock");
log::info!("Attempting to reconnect, current state: {:?}", *state);
match *state {
Connected(_) => {
return Either::B(future::err(error::Error::Connection(
ConnectionReason::Connected,
)));
}
Connecting => {
return Either::B(future::err(error::Error::Connection(
ConnectionReason::Connecting,
)));
}
NotConnected | ConnectionFailed(_) => (),
}
*state = ReconnectState::Connecting;
let reconnect = self.clone();
let connect_f = Timeout::new((self.conn_fn)(), CONNECTION_TIMEOUT).map_err(|e| {
if e.is_inner() {
e.into_inner().unwrap()
} else if e.is_elapsed() {
error::internal(format!(
"Connection timed-out after {} seconds",
CONNECTION_TIMEOUT_SECONDS
))
} else if e.is_inner() {
error::internal(format!("Error timing-out connection: {}", e))
} else {
unreachable!("A surprise fourth type of timer error has occurred")
}
});
let connect_f = connect_f.then(move |t| {
let mut state = reconnect.state.write().expect("Cannot obtain write lock");
match *state {
NotConnected | Connecting => match t {
Ok(t) => {
log::info!("Connection established");
*state = Connected(t);
Ok(())
}
Err(e) => {
log::error!("Connection cannot be established: {}", e);
*state = ConnectionFailed(Mutex::new(Some(e)));
Err(error::Error::Connection(ConnectionReason::ConnectionFailed))
}
},
ConnectionFailed(_) => {
panic!("The connection state wasn't reset before connecting")
}
Connected(_) => panic!("A connected state shouldn't be attempting to reconnect"),
}
});
Either::A(connect_f)
}
fn reconnect_spawn(&self) {
let reconnect_f = self
.reconnect()
.map_err(|e| log::error!("Error asynchronously reconnecting: {}", e));
let mut executor = DefaultExecutor::current();
executor
.spawn(Box::new(reconnect_f))
.expect("Cannot spawn asynchronous reconnection");
}
}
impl<A, T> Clone for Reconnect<A, T> {
fn clone(&self) -> Self {
Reconnect {
state: self.state.clone(),
work_fn: self.work_fn.clone(),
conn_fn: self.conn_fn.clone(),
}
}
}