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::{
error::DataError,
event::MarketEvent,
exchange::StreamSelector,
subscription::{SubKind, Subscription},
Identifier, MarketStream,
};
use futures::StreamExt;
use std::time::Duration;
use tokio::sync::mpsc;
use tracing::{error, info, warn};
pub const STARTING_RECONNECT_BACKOFF_MS: u64 = 125;
pub async fn consume<Exchange, Kind>(
subscriptions: Vec<Subscription<Exchange, Kind>>,
exchange_tx: mpsc::UnboundedSender<MarketEvent<Kind::Event>>,
) -> DataError
where
Exchange: StreamSelector<Kind>,
Kind: SubKind,
Subscription<Exchange, Kind>: Identifier<Exchange::Channel> + Identifier<Exchange::Market>,
{
let exchange = Exchange::ID;
info!(
%exchange,
?subscriptions,
policy = "retry connection with exponential backoff",
"MarketStream consumer loop running",
);
let mut attempt: u32 = 0;
let mut backoff_ms: u64 = STARTING_RECONNECT_BACKOFF_MS;
loop {
attempt += 1;
backoff_ms *= 2;
info!(%exchange, attempt, "attempting to initialise MarketStream");
let mut stream = match Exchange::Stream::init(&subscriptions).await {
Ok(stream) => {
info!(%exchange, attempt, "successfully initialised MarketStream");
attempt = 0;
backoff_ms = STARTING_RECONNECT_BACKOFF_MS;
stream
}
Err(error) => {
error!(%exchange, attempt, ?error, "failed to initialise MarketStream");
if attempt == 1 {
return error;
} else {
continue;
}
}
};
while let Some(event_result) = stream.next().await {
match event_result {
Ok(market_event) => {
let _ = exchange_tx.send(market_event).map_err(|err| {
error!(
payload = ?err.0,
why = "receiver dropped",
"failed to send Event<MarketData> to Exchange receiver"
);
});
}
Err(error) if error.is_terminal() => {
error!(
%exchange,
%error,
action = "re-initialising Stream",
"consumed DataError from MarketStream",
);
break;
}
Err(error) => {
warn!(
%exchange,
%error,
action = "skipping message",
"consumed DataError from MarketStream",
);
continue;
}
}
}
warn!(
%exchange,
backoff_ms,
action = "attempt re-connection after backoff",
"exchange MarketStream unexpectedly ended"
);
tokio::time::sleep(Duration::from_millis(backoff_ms)).await;
}
}