Skip to main content

netget/server/
connection.rs

1//! Connection management
2
3use std::net::SocketAddr;
4use tokio::net::TcpStream;
5
6/// Unique identifier for a connection
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub struct ConnectionId(u32);
9
10impl ConnectionId {
11    /// Create a new connection ID from a u32 value
12    /// NOTE: Callers should use AppState::get_next_unified_id() to ensure uniqueness
13    pub fn new(id: u32) -> Self {
14        Self(id)
15    }
16
17    /// Get the raw ID value
18    pub fn as_u32(&self) -> u32 {
19        self.0
20    }
21
22    /// Get the raw ID value as u64 (for backwards compatibility)
23    #[deprecated(note = "Use as_u32() instead - IDs are now u32")]
24    pub fn as_u64(&self) -> u64 {
25        self.0 as u64
26    }
27
28    /// Parse from string (expects format "conn-123" or just "123")
29    pub fn from_string(s: &str) -> Option<Self> {
30        let s = s.trim();
31        let id_str = s.strip_prefix("conn-").unwrap_or(s);
32        id_str.parse::<u32>().ok().map(Self)
33    }
34}
35
36impl std::fmt::Display for ConnectionId {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "conn-{}", self.0)
39    }
40}
41
42/// Represents an active network connection
43pub struct Connection {
44    /// Unique identifier for this connection
45    pub id: ConnectionId,
46    /// Remote address
47    pub remote_addr: SocketAddr,
48    /// Local address
49    pub local_addr: SocketAddr,
50    /// TCP stream
51    pub stream: TcpStream,
52    /// Number of bytes sent
53    pub bytes_sent: u64,
54    /// Number of bytes received
55    pub bytes_received: u64,
56}
57
58impl Connection {
59    /// Create a new connection with a specific ID
60    /// NOTE: Callers should use AppState::get_next_unified_id() to get the ID
61    pub fn new_with_id(
62        id: ConnectionId,
63        stream: TcpStream,
64        remote_addr: SocketAddr,
65        local_addr: SocketAddr,
66    ) -> Self {
67        Self {
68            id,
69            remote_addr,
70            local_addr,
71            stream,
72            bytes_sent: 0,
73            bytes_received: 0,
74        }
75    }
76
77    /// Record bytes sent
78    pub fn add_bytes_sent(&mut self, count: u64) {
79        self.bytes_sent += count;
80    }
81
82    /// Record bytes received
83    pub fn add_bytes_received(&mut self, count: u64) {
84        self.bytes_received += count;
85    }
86}