msgtrans 1.0.8

Support for a variety of communication protocols such as TCP / QUIC / WebSocket, easy to create server and client network library.
Documentation
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::command::ConnectionInfo;
use crate::packet::Packet;
use crate::protocol::{
    QuicClientConfig, QuicServerConfig, TcpClientConfig, TcpServerConfig, WebSocketClientConfig,
    WebSocketServerConfig,
};
use crate::{error::TransportError, SessionId};
use async_trait::async_trait;

/// Adapter statistics information
#[derive(Debug, Clone)]
pub struct AdapterStats {
    /// Number of packets sent
    pub packets_sent: u64,
    /// Number of packets received
    pub packets_received: u64,
    /// Number of bytes sent
    pub bytes_sent: u64,
    /// Number of bytes received
    pub bytes_received: u64,
    /// Error count
    pub errors: u64,
    /// Last activity time
    pub last_activity: std::time::SystemTime,
}

impl Default for AdapterStats {
    fn default() -> Self {
        Self {
            packets_sent: 0,
            packets_received: 0,
            bytes_sent: 0,
            bytes_received: 0,
            errors: 0,
            last_activity: std::time::SystemTime::now(),
        }
    }
}

impl AdapterStats {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn record_packet_sent(&mut self, size: usize) {
        self.packets_sent += 1;
        self.bytes_sent += size as u64;
        self.last_activity = std::time::SystemTime::now();
    }

    pub fn record_packet_received(&mut self, size: usize) {
        self.packets_received += 1;
        self.bytes_received += size as u64;
        self.last_activity = std::time::SystemTime::now();
    }

    pub fn record_error(&mut self) {
        self.errors += 1;
        self.last_activity = std::time::SystemTime::now();
    }
}

/// Protocol adapter trait
///
/// Defines the basic interface that all protocol adapters must implement
/// This is the core abstraction of the event-driven architecture
#[async_trait]
pub trait ProtocolAdapter: Send + 'static {
    type Config: ProtocolConfig;
    type Error: Into<TransportError> + Send + std::fmt::Debug + 'static;

    /// Send packet
    async fn send(&mut self, packet: Packet) -> Result<(), Self::Error>;

    /// Close connection
    async fn close(&mut self) -> Result<(), Self::Error>;

    /// Gracefully close connection
    ///
    /// Send protocol-specific close signal and wait for peer confirmation
    async fn graceful_close(&mut self) -> Result<(), Self::Error> {
        // Default implementation: directly call close()
        self.close().await
    }

    /// Force close connection
    ///
    /// Immediately close connection without waiting for peer confirmation
    async fn force_close(&mut self) -> Result<(), Self::Error> {
        // Default implementation: directly call close()
        self.close().await
    }

    /// Get connection information
    fn connection_info(&self) -> ConnectionInfo;

    /// Check connection status
    fn is_connected(&self) -> bool;

    /// Get adapter statistics information
    fn stats(&self) -> AdapterStats;

    /// Get session ID
    fn session_id(&self) -> SessionId;

    /// Set session ID
    fn set_session_id(&mut self, session_id: SessionId);

    /// Flush send buffer
    async fn flush(&mut self) -> Result<(), Self::Error> {
        // Default implementation: handled by internal event loop in event-driven mode
        Ok(())
    }
}

/// Protocol configuration trait
pub trait ProtocolConfig: Send + Sync + Clone + std::fmt::Debug + 'static {
    /// Validate if configuration is valid
    fn validate(&self) -> Result<(), ConfigError>;

    /// Get default configuration
    fn default_config() -> Self;

    /// Merge configurations
    fn merge(self, other: Self) -> Self;
}

/// Object-safe protocol configuration trait for unified Builder interface
pub trait DynProtocolConfig: Send + Sync + 'static {
    /// Get protocol name
    fn protocol_name(&self) -> &'static str;

    /// Validate configuration
    fn validate_dyn(&self) -> Result<(), ConfigError>;

    /// Convert to Any to support downcasting
    fn as_any(&self) -> &dyn std::any::Any;

    /// Clone as Box<dyn DynProtocolConfig>
    fn clone_dyn(&self) -> Box<dyn DynProtocolConfig>;
}

/// 🔧 Server-specific dynamic configuration
pub trait DynServerConfig: DynProtocolConfig {
    /// Dynamically build server (object-safe)
    fn build_server_dyn(
        &self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<Box<dyn crate::Server>, crate::error::TransportError>,
                > + Send
                + '_,
        >,
    >;

    /// Get bind address
    fn get_bind_address(&self) -> std::net::SocketAddr;

    /// Clone as Box<dyn DynServerConfig>
    fn clone_server_dyn(&self) -> Box<dyn DynServerConfig>;
}

/// 🔧 Client-specific dynamic configuration  
pub trait DynClientConfig: DynProtocolConfig {
    /// Dynamically build connection (object-safe)
    fn build_connection_dyn(
        &self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<Box<dyn crate::Connection>, crate::error::TransportError>,
                > + Send
                + '_,
        >,
    >;

    /// Get target information (could be SocketAddr or URL)
    fn get_target_info(&self) -> String;

    /// Clone as Box<dyn DynClientConfig>
    fn clone_client_dyn(&self) -> Box<dyn DynClientConfig>;
}

/// Protocol configuration error
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Invalid address '{address}': {reason}")]
    InvalidAddress {
        address: String,
        reason: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    #[error("Invalid port {port}: {reason}\nSuggestion: Use a port between 1 and 65535")]
    InvalidPort { port: u32, reason: String },

    #[error("Missing required field '{field}'\nSuggestion: {suggestion}")]
    MissingRequiredField { field: String, suggestion: String },

    #[error("Invalid value for '{field}': {value}\nReason: {reason}\nSuggestion: {suggestion}")]
    InvalidValue {
        field: String,
        value: String,
        reason: String,
        suggestion: String,
    },

    #[error("File not found: '{path}'\nSuggestion: {suggestion}")]
    FileNotFound { path: String, suggestion: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

impl ServerConfig for TcpServerConfig {
    type Server = crate::adapters::factories::TcpServerWrapper;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("TCP config validation failed: {:?}", e),
            )
        })
    }

    async fn build_server(&self) -> Result<Self::Server, TransportError> {
        use crate::adapters::tcp::TcpServerBuilder;

        let server = TcpServerBuilder::new()
            .bind_address(self.bind_address)
            .config(self.clone())
            .build()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build TCP server: {:?}", e),
                    true,
                )
            })?;

        Ok(crate::adapters::factories::TcpServerWrapper::new(server))
    }

    fn protocol_name(&self) -> &'static str {
        "tcp"
    }
}

impl ClientConfig for TcpClientConfig {
    type Connection = crate::adapters::tcp::TcpAdapter<TcpClientConfig>;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("TCP config validation failed: {:?}", e),
            )
        })
    }

    async fn build_connection(&self) -> Result<Self::Connection, TransportError> {
        use crate::adapters::tcp::TcpClientBuilder;

        TcpClientBuilder::new()
            .target_address(self.target_address)
            .config(self.clone())
            .connect()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build TCP connection: {:?}", e),
                    true,
                )
            })
    }

    fn protocol_name(&self) -> &'static str {
        "tcp"
    }
}

impl ServerConfig for WebSocketServerConfig {
    type Server = crate::adapters::factories::WebSocketServerWrapper;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("WebSocket config validation failed: {:?}", e),
            )
        })
    }

    async fn build_server(&self) -> Result<Self::Server, TransportError> {
        use crate::adapters::websocket::WebSocketServerBuilder;

        let server = WebSocketServerBuilder::new()
            .bind_address(self.bind_address)
            .config(self.clone())
            .build()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build WebSocket server: {:?}", e),
                    true,
                )
            })?;

        Ok(crate::adapters::factories::WebSocketServerWrapper::new(
            server,
        ))
    }

    fn protocol_name(&self) -> &'static str {
        "websocket"
    }
}

impl ClientConfig for WebSocketClientConfig {
    type Connection = crate::adapters::websocket::WebSocketAdapter<WebSocketClientConfig>;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("WebSocket config validation failed: {:?}", e),
            )
        })
    }

    async fn build_connection(&self) -> Result<Self::Connection, TransportError> {
        use crate::adapters::websocket::WebSocketClientBuilder;

        WebSocketClientBuilder::new()
            .target_url(&self.target_url)
            .config(self.clone())
            .connect()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build WebSocket connection: {:?}", e),
                    true,
                )
            })
    }

    fn protocol_name(&self) -> &'static str {
        "websocket"
    }
}

impl ServerConfig for QuicServerConfig {
    type Server = crate::adapters::factories::QuicServerWrapper;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("QUIC config validation failed: {:?}", e),
            )
        })
    }

    async fn build_server(&self) -> Result<Self::Server, TransportError> {
        use crate::adapters::quic::QuicServerBuilder;

        let server = QuicServerBuilder::new()
            .bind_address(self.bind_address)
            .config(self.clone())
            .build()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build QUIC server: {:?}", e),
                    true,
                )
            })?;

        Ok(crate::adapters::factories::QuicServerWrapper::new(server))
    }

    fn protocol_name(&self) -> &'static str {
        "quic"
    }
}

impl ClientConfig for QuicClientConfig {
    type Connection = crate::adapters::quic::QuicAdapter<QuicClientConfig>;

    fn validate(&self) -> Result<(), TransportError> {
        ProtocolConfig::validate(self).map_err(|e| {
            TransportError::config_error(
                "protocol",
                format!("QUIC config validation failed: {:?}", e),
            )
        })
    }

    async fn build_connection(&self) -> Result<Self::Connection, TransportError> {
        use crate::adapters::quic::QuicClientBuilder;

        QuicClientBuilder::new()
            .target_address(self.target_address)
            .config(self.clone())
            .connect()
            .await
            .map_err(|e| {
                TransportError::connection_error(
                    format!("Failed to build QUIC connection: {:?}", e),
                    true,
                )
            })
    }

    fn protocol_name(&self) -> &'static str {
        "quic"
    }
}

/// Server configuration trait - for type-safe server startup
pub trait ServerConfig: Send + Sync + 'static {
    type Server: crate::Server;

    /// Validate configuration correctness
    fn validate(&self) -> Result<(), TransportError>;

    /// Build server instance
    fn build_server(
        &self,
    ) -> impl std::future::Future<Output = Result<Self::Server, TransportError>> + Send;

    /// Get protocol name
    fn protocol_name(&self) -> &'static str;
}

/// Client configuration trait - for type-safe client connections
pub trait ClientConfig: Send + Sync + 'static {
    type Connection: crate::Connection;

    /// Validate configuration correctness
    fn validate(&self) -> Result<(), TransportError>;

    /// Build connection instance
    fn build_connection(
        &self,
    ) -> impl std::future::Future<Output = Result<Self::Connection, TransportError>> + Send;

    /// Get protocol name
    fn protocol_name(&self) -> &'static str;
}

// ConnectableConfig implementation has been moved to client_config.rs