amaters_sdk_rust/
connection.rs

1//! Connection management and pooling
2
3use crate::config::ClientConfig;
4use crate::error::{Result, SdkError};
5use dashmap::DashMap;
6use parking_lot::RwLock;
7use std::sync::Arc;
8use std::time::Instant;
9use tokio::time::timeout;
10use tonic::transport::{Channel, Endpoint};
11use tracing::{debug, info, warn};
12
13/// Connection wrapper with metadata
14#[derive(Clone)]
15pub struct Connection {
16    channel: Channel,
17    created_at: Instant,
18    last_used: Arc<RwLock<Instant>>,
19}
20
21impl Connection {
22    /// Create a new connection
23    fn new(channel: Channel) -> Self {
24        let now = Instant::now();
25        Self {
26            channel,
27            created_at: now,
28            last_used: Arc::new(RwLock::new(now)),
29        }
30    }
31
32    /// Get the underlying channel
33    pub fn channel(&self) -> &Channel {
34        *self.last_used.write() = Instant::now();
35        &self.channel
36    }
37
38    /// Check if connection is idle for too long
39    fn is_idle(&self, idle_timeout: std::time::Duration) -> bool {
40        self.last_used.read().elapsed() > idle_timeout
41    }
42
43    /// Get age of connection
44    fn age(&self) -> std::time::Duration {
45        self.created_at.elapsed()
46    }
47}
48
49/// Connection pool for managing multiple connections
50pub struct ConnectionPool {
51    config: Arc<ClientConfig>,
52    connections: DashMap<usize, Connection>,
53    next_id: Arc<parking_lot::Mutex<usize>>,
54}
55
56impl ConnectionPool {
57    /// Create a new connection pool
58    pub fn new(config: ClientConfig) -> Self {
59        Self {
60            config: Arc::new(config),
61            connections: DashMap::new(),
62            next_id: Arc::new(parking_lot::Mutex::new(0)),
63        }
64    }
65
66    /// Get a connection from the pool or create a new one
67    pub async fn get(&self) -> Result<Connection> {
68        // Try to find a healthy connection
69        for entry in self.connections.iter() {
70            let conn = entry.value();
71            if !conn.is_idle(self.config.idle_timeout) {
72                debug!("Reusing connection {}", entry.key());
73                return Ok(conn.clone());
74            }
75        }
76
77        // Clean up idle connections
78        self.cleanup_idle();
79
80        // Check if we can create a new connection
81        if self.connections.len() >= self.config.max_connections {
82            // Wait and retry
83            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
84
85            // Try again
86            for entry in self.connections.iter() {
87                let conn = entry.value();
88                if !conn.is_idle(self.config.idle_timeout) {
89                    return Ok(conn.clone());
90                }
91            }
92
93            return Err(SdkError::Connection(
94                "connection pool exhausted".to_string(),
95            ));
96        }
97
98        // Create new connection
99        self.create_connection().await
100    }
101
102    /// Create a new connection
103    async fn create_connection(&self) -> Result<Connection> {
104        info!("Creating new connection to {}", self.config.server_addr);
105
106        let mut endpoint = Endpoint::from_shared(self.config.server_addr.clone())
107            .map_err(|e| SdkError::Configuration(format!("invalid server address: {}", e)))?;
108
109        // Configure timeouts
110        endpoint = endpoint
111            .timeout(self.config.request_timeout)
112            .connect_timeout(self.config.connect_timeout);
113
114        // Configure keep-alive
115        if self.config.keep_alive {
116            endpoint = endpoint
117                .keep_alive_timeout(self.config.keep_alive_timeout)
118                .http2_keep_alive_interval(self.config.keep_alive_interval);
119        }
120
121        // Configure TLS if enabled
122        if self.config.tls_enabled {
123            if let Some(_tls_config) = &self.config.tls_config {
124                // TODO: Configure TLS when needed
125                // For now, just use the endpoint as-is
126                debug!("TLS configuration requested but not yet implemented");
127            }
128        }
129
130        // Connect with timeout
131        let channel = timeout(self.config.connect_timeout, endpoint.connect())
132            .await
133            .map_err(|_| {
134                SdkError::Timeout(format!(
135                    "connection timeout after {:?}",
136                    self.config.connect_timeout
137                ))
138            })?
139            .map_err(SdkError::Transport)?;
140
141        let conn = Connection::new(channel);
142
143        // Store in pool
144        let id = {
145            let mut next = self.next_id.lock();
146            let id = *next;
147            *next += 1;
148            id
149        };
150
151        self.connections.insert(id, conn.clone());
152        info!("Connection {} created successfully", id);
153
154        Ok(conn)
155    }
156
157    /// Clean up idle connections
158    fn cleanup_idle(&self) {
159        let mut to_remove = Vec::new();
160
161        for entry in self.connections.iter() {
162            if entry.value().is_idle(self.config.idle_timeout) {
163                to_remove.push(*entry.key());
164            }
165        }
166
167        for id in to_remove {
168            if let Some((_, conn)) = self.connections.remove(&id) {
169                warn!("Removing idle connection {} (age: {:?})", id, conn.age());
170            }
171        }
172    }
173
174    /// Close all connections
175    pub fn close_all(&self) {
176        info!("Closing all connections ({})", self.connections.len());
177        self.connections.clear();
178    }
179
180    /// Get pool statistics
181    pub fn stats(&self) -> PoolStats {
182        let total = self.connections.len();
183        let mut idle = 0;
184
185        for entry in self.connections.iter() {
186            if entry.value().is_idle(self.config.idle_timeout) {
187                idle += 1;
188            }
189        }
190
191        PoolStats {
192            total_connections: total,
193            active_connections: total - idle,
194            idle_connections: idle,
195            max_connections: self.config.max_connections,
196        }
197    }
198}
199
200/// Connection pool statistics
201#[derive(Debug, Clone)]
202pub struct PoolStats {
203    pub total_connections: usize,
204    pub active_connections: usize,
205    pub idle_connections: usize,
206    pub max_connections: usize,
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use std::time::Duration;
213
214    #[test]
215    fn test_connection_idle() {
216        // Create a mock channel (we can't easily test this without a real server)
217        // Just test the idle logic with timing
218        let now = Instant::now();
219        let last_used = Arc::new(RwLock::new(now));
220
221        // Sleep a bit
222        std::thread::sleep(Duration::from_millis(10));
223
224        // Check if idle
225        let elapsed = last_used.read().elapsed();
226        assert!(elapsed >= Duration::from_millis(10));
227    }
228
229    #[test]
230    fn test_pool_stats() {
231        let config = ClientConfig::default();
232        let pool = ConnectionPool::new(config);
233
234        let stats = pool.stats();
235        assert_eq!(stats.total_connections, 0);
236        assert_eq!(stats.active_connections, 0);
237        assert_eq!(stats.max_connections, 10);
238    }
239}