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
//! WebSocket connection management - high-performance wrapper around tokio-tungstenite
use super::types::{
ConnectionId, ConnectionState, WebSocketConfig, WebSocketError, WebSocketMessage,
WebSocketResult,
};
use futures_util::{SinkExt, StreamExt};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, RwLock};
use tokio::time;
use tokio_tungstenite::{accept_async, tungstenite, WebSocketStream};
use tracing::{debug, error, info};
/// WebSocket connection wrapper - clean API over tokio-tungstenite
#[derive(Clone)]
pub struct WebSocketConnection {
/// Unique connection identifier
pub id: ConnectionId,
/// Connection state
state: Arc<RwLock<ConnectionState>>,
/// Connection metadata
metadata: Arc<RwLock<ConnectionMetadata>>,
/// Message sender channel
sender: mpsc::UnboundedSender<WebSocketMessage>,
/// Configuration
_config: WebSocketConfig,
}
/// Connection metadata for tracking and debugging
#[derive(Debug, Clone)]
pub struct ConnectionMetadata {
/// When the connection was established
pub connected_at: Instant,
/// Remote address if available
pub remote_addr: Option<String>,
/// User agent if available
pub user_agent: Option<String>,
/// Custom metadata
pub custom: HashMap<String, String>,
/// Message statistics
pub stats: ConnectionStats,
}
/// Connection statistics
#[derive(Debug, Clone, Default)]
pub struct ConnectionStats {
/// Total messages sent
pub messages_sent: u64,
/// Total messages received
pub messages_received: u64,
/// Total bytes sent
pub bytes_sent: u64,
/// Total bytes received
pub bytes_received: u64,
/// Last activity timestamp
pub last_activity: Option<Instant>,
}
impl WebSocketConnection {
/// Create a new WebSocket connection from a TCP stream
pub async fn from_stream<S>(stream: S, config: WebSocketConfig) -> WebSocketResult<Self>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let id = ConnectionId::new();
let ws_stream = accept_async(stream).await?;
let (sender, receiver) = mpsc::unbounded_channel();
let state = Arc::new(RwLock::new(ConnectionState::Connected));
let metadata = Arc::new(RwLock::new(ConnectionMetadata {
connected_at: Instant::now(),
remote_addr: None,
user_agent: None,
custom: HashMap::new(),
stats: ConnectionStats::default(),
}));
// Start the connection handler task
let connection = Self {
id,
state: state.clone(),
metadata: metadata.clone(),
sender,
_config: config.clone(),
};
// Spawn the connection handler
tokio::spawn(Self::handle_connection(
id, ws_stream, receiver, state, metadata, config,
));
info!("WebSocket connection established: {}", id);
Ok(connection)
}
/// Send a message to the WebSocket
pub async fn send(&self, message: WebSocketMessage) -> WebSocketResult<()> {
if !self.is_active().await {
return Err(WebSocketError::ConnectionClosed);
}
self.sender
.send(message)
.map_err(|_| WebSocketError::SendQueueFull)?;
Ok(())
}
/// Send a text message
pub async fn send_text<T: Into<String>>(&self, text: T) -> WebSocketResult<()> {
self.send(WebSocketMessage::text(text)).await
}
/// Send a binary message
pub async fn send_binary<T: Into<Vec<u8>>>(&self, data: T) -> WebSocketResult<()> {
self.send(WebSocketMessage::binary(data)).await
}
/// Send a ping
pub async fn ping<T: Into<Vec<u8>>>(&self, data: T) -> WebSocketResult<()> {
self.send(WebSocketMessage::ping(data)).await
}
/// Close the connection
pub async fn close(&self) -> WebSocketResult<()> {
self.send(WebSocketMessage::close()).await?;
let mut state = self.state.write().await;
*state = ConnectionState::Closing;
Ok(())
}
/// Close the connection with a reason
pub async fn close_with_reason(&self, code: u16, reason: String) -> WebSocketResult<()> {
self.send(WebSocketMessage::close_with_reason(code, reason))
.await?;
let mut state = self.state.write().await;
*state = ConnectionState::Closing;
Ok(())
}
/// Get the current connection state
pub async fn state(&self) -> ConnectionState {
self.state.read().await.clone()
}
/// Check if the connection is active
pub async fn is_active(&self) -> bool {
self.state().await.is_active()
}
/// Check if the connection is closed
pub async fn is_closed(&self) -> bool {
self.state().await.is_closed()
}
/// Get connection metadata
pub async fn metadata(&self) -> ConnectionMetadata {
self.metadata.read().await.clone()
}
/// Update connection metadata
pub async fn set_metadata(&self, key: String, value: String) {
let mut metadata = self.metadata.write().await;
metadata.custom.insert(key, value);
}
/// Get connection statistics
pub async fn stats(&self) -> ConnectionStats {
self.metadata.read().await.stats.clone()
}
/// Connection handler - runs the actual WebSocket loop
async fn handle_connection<S>(
id: ConnectionId,
mut ws_stream: WebSocketStream<S>,
mut receiver: mpsc::UnboundedReceiver<WebSocketMessage>,
state: Arc<RwLock<ConnectionState>>,
metadata: Arc<RwLock<ConnectionMetadata>>,
config: WebSocketConfig,
) where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
debug!("Starting WebSocket handler for connection: {}", id);
// Set up ping interval if configured
let mut ping_interval = config
.ping_interval
.map(|interval| time::interval(Duration::from_secs(interval)));
loop {
tokio::select! {
// Handle incoming messages from WebSocket
ws_msg = ws_stream.next() => {
match ws_msg {
Some(Ok(msg)) => {
let elif_msg = WebSocketMessage::from(msg);
// Update stats
{
let mut meta = metadata.write().await;
meta.stats.messages_received += 1;
meta.stats.last_activity = Some(Instant::now());
// Estimate bytes received
let bytes = match &elif_msg {
WebSocketMessage::Text(s) => s.len() as u64,
WebSocketMessage::Binary(b) => b.len() as u64,
_ => 0,
};
meta.stats.bytes_received += bytes;
}
// Handle control frames automatically
match &elif_msg {
WebSocketMessage::Ping(data) => {
if config.auto_pong {
let pong_msg = tungstenite::Message::Pong(data.clone());
if let Err(e) = ws_stream.send(pong_msg).await {
error!("Failed to send pong for {}: {}", id, e);
break;
}
}
}
WebSocketMessage::Close(_) => {
info!("Received close frame for connection: {}", id);
break;
}
_ => {
// For now, we just log other messages
// In a full implementation, we'd route these to handlers
debug!("Received message on {}: {:?}", id, elif_msg.message_type());
}
}
}
Some(Err(e)) => {
error!("WebSocket error for {}: {}", id, e);
let mut state_lock = state.write().await;
*state_lock = ConnectionState::Failed(e.to_string());
break;
}
None => {
info!("WebSocket stream ended for connection: {}", id);
break;
}
}
}
// Handle outgoing messages from application
app_msg = receiver.recv() => {
match app_msg {
Some(msg) => {
// Update stats
{
let mut meta = metadata.write().await;
meta.stats.messages_sent += 1;
meta.stats.last_activity = Some(Instant::now());
// Estimate bytes sent
let bytes = match &msg {
WebSocketMessage::Text(s) => s.len() as u64,
WebSocketMessage::Binary(b) => b.len() as u64,
_ => 0,
};
meta.stats.bytes_sent += bytes;
}
let tungstenite_msg = tungstenite::Message::from(msg);
if let Err(e) = ws_stream.send(tungstenite_msg).await {
error!("Failed to send message for {}: {}", id, e);
let mut state_lock = state.write().await;
*state_lock = ConnectionState::Failed(e.to_string());
break;
}
}
None => {
debug!("Application message channel closed for: {}", id);
break;
}
}
}
// Handle ping interval
_ = async {
if let Some(ref mut interval) = ping_interval {
interval.tick().await;
} else {
// If no ping interval, wait indefinitely
std::future::pending::<()>().await;
}
} => {
// Send ping
let ping_msg = tungstenite::Message::Ping(vec![]);
if let Err(e) = ws_stream.send(ping_msg).await {
error!("Failed to send ping for {}: {}", id, e);
break;
}
debug!("Sent ping to connection: {}", id);
}
}
}
// Connection cleanup
let mut state_lock = state.write().await;
if !matches!(*state_lock, ConnectionState::Failed(_)) {
*state_lock = ConnectionState::Closed;
}
info!("WebSocket connection handler finished: {}", id);
}
}
impl Drop for WebSocketConnection {
fn drop(&mut self) {
debug!("Dropping WebSocket connection: {}", self.id);
}
}