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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use std::fmt::{self, Debug};
use std::sync::Arc;
use std::time::Duration;
use crate::channel::{connect_websocket, TrySendError, WebSocketReceiver};
use crate::error::{Error, Result};
use crate::model::outgoing::OutgoingMessage;
#[cfg(feature = "async-tungstenite09")]
use async_tungstenite09 as async_tungstenite;
#[cfg(feature = "async-std-runtime")]
use async_std::task;
#[cfg(feature = "async-std-runtime")]
use async_std::task::sleep;
use async_tungstenite::tungstenite::Error as WsError;
use futures::stream::StreamExt;
use log::{info, warn};
#[cfg(feature = "tokio-runtime")]
use tokio::task;
#[cfg(feature = "tokio-runtime")]
use tokio::time::sleep;
#[cfg(feature = "tokio02-runtime")]
use tokio02::task;
#[cfg(feature = "tokio02-runtime")]
use tokio02::time::delay_for as sleep;
use url::Url;
pub mod channel;
pub mod handler;
pub mod model;
use channel::{control_channel, ControlReceiver, ControlSender};
use handler::Handler;
use model::SharedBrokerState;
#[derive(Debug)]
pub(crate) struct Broker {
broker_rx: ControlReceiver,
handler: Handler,
reconnect: ReconnectConfig,
url: Url,
}
#[derive(Clone)]
pub struct ReconnectCondition {
inner: ReconnectConditionKind,
}
impl Debug for ReconnectCondition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("ReconnectCondition")
.field(&self.inner)
.finish()
}
}
#[derive(Clone)]
enum ReconnectConditionKind {
Always,
Never,
UnexpectedReset,
Custom(Arc<dyn Fn(&Error) -> bool + Send + Sync + 'static>),
}
impl Debug for ReconnectConditionKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReconnectConditionKind::Always => f.debug_tuple("Always").finish(),
ReconnectConditionKind::Never => f.debug_tuple("Never").finish(),
ReconnectConditionKind::UnexpectedReset => f.debug_tuple("UnexpectedReset").finish(),
ReconnectConditionKind::Custom(_) => f.debug_tuple("Custom").finish(),
}
}
}
impl ReconnectCondition {
pub fn always() -> Self {
ReconnectCondition {
inner: ReconnectConditionKind::Always,
}
}
pub fn never() -> Self {
ReconnectCondition {
inner: ReconnectConditionKind::Never,
}
}
pub fn unexpected_reset() -> Self {
ReconnectCondition {
inner: ReconnectConditionKind::UnexpectedReset,
}
}
pub fn custom<F>(f: F) -> Self
where
F: Fn(&Error) -> bool + Send + Sync + 'static,
{
ReconnectCondition {
inner: ReconnectConditionKind::Custom(Arc::new(f)),
}
}
fn should_reconnect(&self, err: &Error) -> bool {
match &self.inner {
ReconnectConditionKind::Always => true,
ReconnectConditionKind::Never => false,
ReconnectConditionKind::UnexpectedReset => {
let ws = match err {
Error::WebSocket(ws) => ws,
_ => return false,
};
use std::io::ErrorKind;
match ws.as_ref() {
WsError::Protocol(_) => true,
WsError::Io(e) => {
e.kind() == ErrorKind::ConnectionReset || e.kind() == ErrorKind::BrokenPipe
}
_ => false,
}
}
ReconnectConditionKind::Custom(f) => f(err),
}
}
}
impl Default for ReconnectCondition {
fn default() -> ReconnectCondition {
ReconnectCondition::unexpected_reset()
}
}
#[derive(Debug, Clone)]
pub struct ReconnectConfig {
pub interval: Duration,
pub condition: ReconnectCondition,
pub retry_send: bool,
}
impl ReconnectConfig {
pub fn none() -> ReconnectConfig {
ReconnectConfig::with_condition(ReconnectCondition::never())
}
pub fn with_condition(condition: ReconnectCondition) -> ReconnectConfig {
ReconnectConfig {
condition,
..Default::default()
}
}
pub fn with_interval(interval: Duration) -> ReconnectConfig {
ReconnectConfig {
interval,
..Default::default()
}
}
}
impl Default for ReconnectConfig {
fn default() -> ReconnectConfig {
ReconnectConfig {
interval: Duration::from_secs(5),
condition: ReconnectCondition::default(),
retry_send: true,
}
}
}
impl Broker {
pub async fn spawn(
url: Url,
reconnect: ReconnectConfig,
) -> Result<(ControlSender, SharedBrokerState)> {
let state = SharedBrokerState::working();
let shared_state = SharedBrokerState::clone(&state);
let (broker_tx, broker_rx) = control_channel(SharedBrokerState::clone(&state));
task::spawn(async move {
let mut broker = Broker {
url,
broker_rx,
reconnect,
handler: Handler::new(),
};
if let Some(err) = broker.run().await {
state.set_error(err).await;
} else {
state.set_exited().await;
}
std::mem::drop(broker);
});
Ok((broker_tx, shared_state))
}
async fn run(&mut self) -> Option<Error> {
let mut remaining_message = None;
loop {
let err = match self.task(remaining_message.take()).await {
Ok(()) => {
info!("broker: exited normally");
return None;
}
Err(e) => e,
};
info!("broker: task exited with error: {:?}", err.error);
if !self.reconnect.condition.should_reconnect(&err.error) {
warn!("broker: died with error");
return Some(err.error);
}
if self.reconnect.retry_send {
remaining_message = err.remaining_message;
}
info!(
"broker: attempt to reconnect in {:?}",
self.reconnect.interval
);
sleep(self.reconnect.interval).await;
}
}
async fn clean_handler(&mut self, websocket_rx: &mut WebSocketReceiver) -> Result<()> {
if self.handler.is_empty() {
return Ok(());
}
info!("broker: handler is not empty, enter receiving loop");
while !self.handler.is_empty() {
let msg = websocket_rx.recv().await?;
self.handler.handle(msg).await?;
}
Ok(())
}
async fn task(
&mut self,
remaining_message: Option<OutgoingMessage>,
) -> std::result::Result<(), TaskError> {
use futures::future::{self, Either};
let (mut websocket_tx, mut websocket_rx) = match connect_websocket(self.url.clone()).await {
Ok(x) => x,
Err(error) => {
return Err(TaskError {
remaining_message,
error,
});
}
};
info!("broker: started");
if let Some(message) = remaining_message {
websocket_tx.try_send(message).await?;
}
for message in self.handler.restore_messages() {
websocket_tx.try_send(message).await?;
}
loop {
let t1 = websocket_rx.recv();
let t2 = self.broker_rx.next();
futures::pin_mut!(t1, t2);
match future::select(t1, t2).await {
Either::Left((msg, _)) => {
while let Some(ctrl) = self.broker_rx.try_recv() {
#[cfg(feature = "inspect-contents")]
log::debug!("broker: received control {:?}", ctrl);
if let Some(out) = self.handler.control(ctrl) {
websocket_tx.try_send(out).await?
}
}
self.handler.handle(msg?).await?;
}
Either::Right((Some(ctrl), _)) => {
#[cfg(feature = "inspect-contents")]
log::debug!("broker: received control {:?}", ctrl);
if let Some(out) = self.handler.control(ctrl) {
websocket_tx.try_send(out).await?
}
}
Either::Right((None, _)) => {
info!("broker: all controls terminated, exiting gracefully");
return Ok(self.clean_handler(&mut websocket_rx).await?);
}
}
}
}
}
#[derive(Debug, Clone)]
struct TaskError {
remaining_message: Option<OutgoingMessage>,
error: Error,
}
impl From<Error> for TaskError {
fn from(error: Error) -> TaskError {
TaskError {
remaining_message: None,
error,
}
}
}
impl From<TrySendError> for TaskError {
fn from(err: TrySendError) -> TaskError {
let TrySendError { message, error } = err;
TaskError {
remaining_message: Some(message),
error,
}
}
}