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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#![expect(
clippy::module_name_repetitions,
reason = "Connection types expose their domain in the name for clarity"
)]
use std::sync::Arc;
use std::time::Instant;
use backoff::backoff::Backoff as _;
use futures::{SinkExt as _, StreamExt as _};
use serde_json::{Value, json};
use tokio::net::TcpStream;
use tokio::sync::{broadcast, mpsc, watch};
use tokio::time::{interval, sleep, timeout};
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async, tungstenite::Message};
use super::config::Config;
use super::error::WsError;
use super::interest::InterestTracker;
use super::types::request::SubscriptionRequest;
use super::types::response::{WsMessage, parse_if_interested};
use crate::{
Result,
error::{Error, Kind},
};
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
/// Broadcast channel capacity for incoming messages.
const BROADCAST_CAPACITY: usize = 1024;
/// Connection state tracking.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
/// Not connected
Disconnected,
/// Attempting to connect
Connecting,
/// Successfully connected
Connected {
/// When the connection was established
since: Instant,
},
/// Reconnecting after failure
Reconnecting {
/// Current reconnection attempt number
attempt: u32,
},
}
impl ConnectionState {
/// Check if the connection is currently active.
#[must_use]
pub const fn is_connected(self) -> bool {
matches!(self, Self::Connected { .. })
}
}
/// Manages WebSocket connection lifecycle, reconnection, and heartbeat.
#[derive(Clone)]
pub struct ConnectionManager {
/// Watch channel sender for state changes (enables reconnection detection)
state_tx: watch::Sender<ConnectionState>,
/// Watch channel receiver for state changes (for use in checking the current state)
state_rx: watch::Receiver<ConnectionState>,
/// Sender channel for outgoing messages
sender_tx: mpsc::UnboundedSender<String>,
/// Broadcast sender for incoming messages
broadcast_tx: broadcast::Sender<WsMessage>,
}
impl ConnectionManager {
/// Create a new connection manager and start the connection loop.
///
/// The `interest` tracker is used to determine which message types to deserialize.
/// Only messages that have active consumers will be fully parsed.
pub fn new(endpoint: String, config: Config, interest: &Arc<InterestTracker>) -> Result<Self> {
let (sender_tx, sender_rx) = mpsc::unbounded_channel();
let (broadcast_tx, _) = broadcast::channel(BROADCAST_CAPACITY);
let (state_tx, state_rx) = watch::channel(ConnectionState::Disconnected);
// Spawn connection task
let connection_config = config;
let connection_endpoint = endpoint;
let broadcast_tx_clone = broadcast_tx.clone();
let connection_interest = Arc::clone(interest);
let state_tx_clone = state_tx.clone();
tokio::spawn(async move {
Self::connection_loop(
connection_endpoint,
connection_config,
sender_rx,
broadcast_tx_clone,
connection_interest,
state_tx_clone,
)
.await;
});
Ok(Self {
state_tx,
state_rx,
sender_tx,
broadcast_tx,
})
}
/// Main connection loop with automatic reconnection.
async fn connection_loop(
endpoint: String,
config: Config,
mut sender_rx: mpsc::UnboundedReceiver<String>,
broadcast_tx: broadcast::Sender<WsMessage>,
interest: Arc<InterestTracker>,
state_tx: watch::Sender<ConnectionState>,
) {
let mut attempt = 0_u32;
let mut backoff: backoff::ExponentialBackoff = config.reconnect.clone().into();
loop {
let state_rx = state_tx.subscribe();
_ = state_tx.send(ConnectionState::Connecting);
// Attempt connection
match connect_async(&endpoint).await {
Ok((ws_stream, _)) => {
attempt = 0;
backoff.reset();
_ = state_tx.send(ConnectionState::Connected {
since: Instant::now(),
});
// Handle connection
if let Err(e) = Self::handle_connection(
ws_stream,
&mut sender_rx,
&broadcast_tx,
state_rx,
config.clone(),
&interest,
)
.await
{
#[cfg(feature = "tracing")]
tracing::error!("Error handling connection: {e:?}");
#[cfg(not(feature = "tracing"))]
let _ = &e;
}
}
Err(e) => {
let error = Error::with_source(Kind::WebSocket, WsError::Connection(e));
#[cfg(feature = "tracing")]
tracing::warn!("Unable to connect: {error:?}");
#[cfg(not(feature = "tracing"))]
let _ = &error;
attempt = attempt.saturating_add(1);
}
}
// Check if we should stop reconnecting
if let Some(max) = config.reconnect.max_attempts
&& attempt >= max
{
_ = state_tx.send(ConnectionState::Disconnected);
break;
}
// Update state and wait with exponential backoff
_ = state_tx.send(ConnectionState::Reconnecting { attempt });
if let Some(duration) = backoff.next_backoff() {
sleep(duration).await;
}
}
}
/// Handle an active WebSocket connection.
async fn handle_connection(
ws_stream: WsStream,
sender_rx: &mut mpsc::UnboundedReceiver<String>,
broadcast_tx: &broadcast::Sender<WsMessage>,
state_rx: watch::Receiver<ConnectionState>,
config: Config,
interest: &Arc<InterestTracker>,
) -> Result<()> {
let (mut write, mut read) = ws_stream.split();
// Channel to notify heartbeat loop when PONG is received
let (pong_tx, pong_rx) = watch::channel(Instant::now());
let (ping_tx, mut ping_rx) = mpsc::unbounded_channel();
let heartbeat_handle = tokio::spawn(async move {
Self::heartbeat_loop(ping_tx, state_rx, &config, pong_rx).await;
});
loop {
tokio::select! {
// Handle incoming messages
Some(msg) = read.next() => {
match msg {
Ok(Message::Text(text)) if text == "PONG" => {
_ = pong_tx.send(Instant::now());
}
Ok(Message::Text(text)) => {
#[cfg(feature = "tracing")]
tracing::trace!(%text, "Received WebSocket text message");
// Only deserialize message types that have active consumers
match parse_if_interested(text.as_bytes(), &interest.get()) {
Ok(messages) => {
for message in messages {
#[cfg(feature = "tracing")]
tracing::trace!(?message, "Parsed WebSocket message");
_ = broadcast_tx.send(message);
}
}
Err(e) => {
#[cfg(feature = "tracing")]
tracing::warn!(%text, error = %e, "Failed to parse WebSocket message");
#[cfg(not(feature = "tracing"))]
let _ = (&text, &e);
}
}
}
Ok(Message::Close(_)) => {
heartbeat_handle.abort();
return Err(Error::with_source(
Kind::WebSocket,
WsError::ConnectionClosed,
))
}
Err(e) => {
heartbeat_handle.abort();
return Err(Error::with_source(
Kind::WebSocket,
WsError::Connection(e),
));
}
_ => {
// Ignore binary frames and unsolicited PONG replies.
}
}
}
// Handle outgoing messages from subscriptions
Some(text) = sender_rx.recv() => {
if write.send(Message::Text(text.into())).await.is_err() {
break;
}
}
// Handle PING requests from heartbeat loop
Some(()) = ping_rx.recv() => {
if write.send(Message::Text("PING".into())).await.is_err() {
break;
}
}
// Check if connection is still active
else => {
break;
}
}
}
// Cleanup
heartbeat_handle.abort();
Ok(())
}
/// Heartbeat loop that sends PING messages and monitors PONG responses.
async fn heartbeat_loop(
ping_tx: mpsc::UnboundedSender<()>,
state_rx: watch::Receiver<ConnectionState>,
config: &Config,
mut pong_rx: watch::Receiver<Instant>,
) {
let mut ping_interval = interval(config.heartbeat_interval);
loop {
ping_interval.tick().await;
// Check if still connected
if !state_rx.borrow().is_connected() {
break;
}
// Mark current PONG state as seen before sending PING
// This prevents changed() from returning immediately due to a stale PONG
drop(pong_rx.borrow_and_update());
// Send PING request to message loop
let ping_sent = Instant::now();
if ping_tx.send(()).is_err() {
// Message loop has terminated
break;
}
// Wait for PONG within timeout
let pong_result = timeout(config.heartbeat_timeout, pong_rx.changed()).await;
match pong_result {
Ok(Ok(())) => {
let last_pong = *pong_rx.borrow_and_update();
if last_pong < ping_sent {
#[cfg(feature = "tracing")]
tracing::debug!(
"PONG received but older than last PING, connection may be stale"
);
break;
}
}
Ok(Err(_)) => {
// Channel closed, connection is terminating
break;
}
Err(_) => {
// Timeout waiting for PONG
#[cfg(feature = "tracing")]
tracing::warn!(
"Heartbeat timeout: no PONG received within {:?}",
config.heartbeat_timeout
);
break;
}
}
}
}
/// Send a subscription request to the WebSocket server.
pub fn send(&self, message: &SubscriptionRequest) -> Result<()> {
let mut v = serde_json::to_value(message)?;
// Only expose credentials when serializing on the wire, otherwise do not include
// credentials in other serialization contexts
if let Some(creds) = message.auth.as_ref() {
let auth = json!({
"apiKey": creds.key.to_string(),
"secret": creds.secret.reveal(),
"passphrase": creds.passphrase.reveal(),
});
if let Value::Object(ref mut obj) = v {
obj.insert("auth".to_owned(), auth);
}
}
let json = serde_json::to_string(&v)?;
self.sender_tx
.send(json)
.map_err(|_e| WsError::ConnectionClosed)?;
Ok(())
}
/// Get the current connection state.
#[must_use]
pub fn state(&self) -> ConnectionState {
*self.state_rx.borrow()
}
/// Subscribe to incoming messages.
///
/// Each call returns a new independent receiver. Multiple subscribers can
/// receive messages concurrently without blocking each other.
#[must_use]
pub fn subscribe(&self) -> broadcast::Receiver<WsMessage> {
self.broadcast_tx.subscribe()
}
/// Subscribe to connection state changes.
///
/// Returns a receiver that notifies when the connection state changes.
/// This is useful for detecting reconnections and re-establishing subscriptions.
#[must_use]
pub fn state_receiver(&self) -> watch::Receiver<ConnectionState> {
self.state_tx.subscribe()
}
}