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
385
386
// WebSocket type definitions.
//
// Note : This file is included via include!() in websocket.rs
// All imports are done in the parent module.
// =====================================
// WebSocket Streaming Types
// =====================================
/// WebSocket connection state
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum WebSocketState
{
/// WebSocket is disconnected
Disconnected,
/// WebSocket is in the process of connecting
Connecting,
/// WebSocket is connected and ready for communication
Connected,
/// WebSocket is reconnecting after a disconnection
Reconnecting,
/// WebSocket is in an error state
Error,
}
/// WebSocket-specific error types
#[ derive( Debug ) ]
pub enum WebSocketError
{
/// Connection failed
ConnectionFailed( String ),
/// Protocol error
ProtocolError( String ),
/// Authentication failed
AuthenticationFailed( String ),
/// Compression error
CompressionError( String ),
/// Message queue overflow
QueueOverflow,
/// Heartbeat timeout
HeartbeatTimeout,
/// Invalid message format
InvalidMessage( String ),
/// Connection pool exhausted
PoolExhausted,
/// Streaming error with message and optional error code
StreamingError {
/// Error message
message : String,
/// Optional error code
code : Option< u16 >
},
/// Generic WebSocket error
Generic( String ),
}
/// WebSocket connection metrics
#[ derive( Debug, Clone ) ]
pub struct WebSocketMetrics
{
/// Total messages sent
pub messages_sent : u64,
/// Total messages received
pub messages_received : u64,
/// Connection uptime in seconds
pub uptime_seconds : u64,
/// Number of reconnection attempts
pub reconnection_attempts : u32,
/// Average message latency in milliseconds
pub average_latency_ms : u32,
/// Current queue size
pub queue_size : usize,
/// Number of compression errors
pub compression_errors : u32,
/// Number of heartbeat failures
pub heartbeat_failures : u32,
/// Total bytes sent
pub bytes_sent : u64,
/// Total bytes received
pub bytes_received : u64,
/// Number of heartbeats sent
pub heartbeat_count : u64,
/// Number of reconnection attempts made
pub reconnect_count : u32,
/// Connection uptime as Duration
pub uptime : core::time::Duration,
/// Compression ratio (0.0 to 1.0)
pub compression_ratio : f64,
/// Creation timestamp for uptime calculation
pub created_at : std::time::Instant,
}
/// WebSocket configuration
#[ derive( Debug, Clone ) ]
pub struct WebSocketConfig
{
/// WebSocket server URL
pub url : String,
/// Connection timeout
pub timeout : Duration,
/// Maximum reconnection attempts
pub max_reconnection_attempts : u32,
/// Reconnection delay
pub reconnection_delay : Duration,
/// Enable compression
pub enable_compression : bool,
/// Heartbeat interval
pub heartbeat_interval : Duration,
/// Maximum queue size
pub max_queue_size : usize,
/// Authentication token
pub auth_token : Option< String >,
/// Enable automatic reconnection
pub enable_auto_reconnect : bool,
/// Connection pool size
pub pool_size : usize,
/// HTTP fallback URL
pub http_fallback_url : Option< String >,
}
/// Message queue entry for reliable delivery
#[ derive( Debug, Clone ) ]
pub struct QueuedMessage
{
/// Unique message ID
pub id : String,
/// Message content
pub content : String,
/// Message priority (higher = more important)
pub priority : u32,
/// Timestamp when message was queued
pub timestamp : Instant,
/// Number of retry attempts
pub retry_count : u32,
/// Maximum retry attempts for this message
pub max_retries : u32,
}
/// Message queue for reliable delivery
#[ derive( Debug ) ]
pub struct MessageQueue
{
/// Queue storage (priority queue)
pub queue : Arc< Mutex< Vec< QueuedMessage > > >,
/// Maximum queue size
pub max_size : usize,
/// Queue metrics
pub metrics : Arc< RwLock< WebSocketMetrics > >,
}
/// WebSocket connection pool entry
#[ derive( Debug ) ]
pub struct PooledConnection
{
/// Connection ID
pub id : String,
/// Connection state
pub state : Arc< RwLock< WebSocketState > >,
/// Connection establishment time
pub established_at : Instant,
/// Last activity timestamp
pub last_activity : Arc< RwLock< Instant > >,
/// Number of active streams
pub active_streams : Arc< RwLock< u32 > >,
/// Connection-specific metrics
pub metrics : Arc< RwLock< WebSocketMetrics > >,
}
/// WebSocket connection pool for connection reuse
#[ derive( Debug ) ]
pub struct ConnectionPool
{
/// Pool of connections
pub connections : Arc< RwLock< Vec< PooledConnection > > >,
/// Maximum pool size
pub max_size : usize,
/// Connection timeout before cleanup
pub connection_timeout : Duration,
/// Pool metrics
pub metrics : Arc< RwLock< WebSocketMetrics > >,
}
/// Authentication context for WebSocket connections
#[ derive( Debug, Clone ) ]
pub struct WebSocketAuth
{
/// Authentication token
pub token : Option< String >,
/// Token expiry time
pub expires_at : Option< Instant >,
/// Refresh token
pub refresh_token : Option< String >,
/// Authentication scheme (Bearer, Basic, etc.)
pub scheme : String,
}
/// WebSocket authentication method
#[ derive( Debug, Clone ) ]
pub enum WebSocketAuthMethod
{
/// Bearer token authentication
Bearer( String ),
/// Basic authentication with username and password
Basic {
/// Username for authentication
username : String,
/// Password for authentication
password : String
},
/// API key authentication
ApiKey( String ),
/// Custom authentication
Custom( String ),
/// Bearer token authentication (alias)
BearerToken( String ),
/// No authentication
None,
}
/// Connection type for fallback scenarios
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum ConnectionType
{
/// WebSocket connection
WebSocket,
/// HTTP fallback connection
HttpFallback,
}
/// Authentication status
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum AuthStatus
{
/// Not authenticated
NotAuthenticated,
/// Authenticated successfully
Authenticated,
/// Authentication failed
Failed,
}
/// WebSocket error handling strategy
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum WebSocketErrorHandling
{
/// Fail fast on any error
FailFast,
/// Resilient error handling with retries
Resilient,
/// Ignore non-critical errors
Ignore,
}
/// Recovery status after connection issues
#[ derive( Debug, Clone ) ]
pub struct RecoveryStatus
{
/// Number of errors encountered
pub error_count : u32,
/// Number of recovery attempts made
pub recovery_attempts : u32,
/// Whether recovery is complete
pub is_recovered : bool,
}
/// WebSocket pool for managing multiple connections
#[ derive( Debug ) ]
pub struct WebSocketPool
{
/// Pool configuration
pub config : WebSocketPoolConfig,
/// Connection pool
pub pool : ConnectionPool,
/// Number of active connections
pub active_connections : std::sync::Arc< std::sync::Mutex< usize > >,
/// Cached connections by URL
pub connections : std::sync::Arc< std::sync::Mutex< std::collections::HashMap< String, WebSocketConnection > > >,
}
/// Pool statistics
#[ derive( Debug, Clone ) ]
pub struct PoolStatistics
{
/// Number of active connections
pub active_connections : usize,
/// Number of idle connections
pub idle_connections : usize,
/// Total number of connections
pub total_connections : usize,
/// Length of the connection queue
pub queue_length : usize,
}
/// WebSocket client implementation
#[ derive( Debug ) ]
pub struct WebSocketClient
{
/// Configuration
pub config : WebSocketConfig,
/// Current connection state
pub state : Arc< RwLock< WebSocketState > >,
/// Message queue for reliable delivery
pub message_queue : MessageQueue,
/// Connection pool
pub connection_pool : ConnectionPool,
/// Authentication context
pub auth : Option< WebSocketAuth >,
/// Client metrics
pub metrics : Arc< RwLock< WebSocketMetrics > >,
/// HTTP client for fallback
pub http_client : Option< reqwest::Client >,
}
/// WebSocket connection wrapper
#[ derive( Debug, Clone ) ]
pub struct WebSocketConnection
{
/// Connection ID
pub id : String,
/// Connection state
pub state : Arc< RwLock< WebSocketState > >,
/// Associated client
pub client_id : String,
/// Connection establishment time
pub established_at : Instant,
/// Last message timestamp
pub last_message_at : Arc< RwLock< Instant > >,
/// Connection metrics
pub metrics : Arc< RwLock< WebSocketMetrics > >,
/// Connection type (WebSocket or HTTP fallback)
pub connection_type : ConnectionType,
}
/// WebSocket message types
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub enum WebSocketMessage
{
/// Text message
Text( String ),
/// Binary message
Binary( Vec< u8 > ),
/// Ping message
Ping( Vec< u8 > ),
/// Pong message
Pong( Vec< u8 > ),
/// Close message
Close( Option< ( u16, String ) > ),
}
/// WebSocket pool configuration
#[ derive( Debug, Clone ) ]
pub struct WebSocketPoolConfig
{
/// Maximum connections in pool
pub max_connections : usize,
/// Minimum connections to maintain
pub min_connections : usize,
/// Connection timeout
pub connection_timeout : Duration,
/// Enable connection multiplexing
pub enable_multiplexing : bool,
}
/// Queue information for WebSocket connections
#[ derive( Debug, Clone ) ]
pub struct QueueInfo
{
/// Current queue size
pub size : usize,
/// Maximum queue capacity
pub capacity : usize,
/// Number of pending messages
pub pending_messages : usize,
}
/// WebSocket chat stream for real-time conversation
#[ derive( Debug ) ]
pub struct WebSocketChatStream
{
/// Connection ID
pub connection_id : String,
/// Chat request
pub request : ChatRequest,
/// Stream state
pub state : Arc< RwLock< WebSocketState > >,
}