amaters_sdk_rust/
connection.rs1use 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#[derive(Clone)]
15pub struct Connection {
16 channel: Channel,
17 created_at: Instant,
18 last_used: Arc<RwLock<Instant>>,
19}
20
21impl Connection {
22 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 pub fn channel(&self) -> &Channel {
34 *self.last_used.write() = Instant::now();
35 &self.channel
36 }
37
38 fn is_idle(&self, idle_timeout: std::time::Duration) -> bool {
40 self.last_used.read().elapsed() > idle_timeout
41 }
42
43 fn age(&self) -> std::time::Duration {
45 self.created_at.elapsed()
46 }
47}
48
49pub struct ConnectionPool {
51 config: Arc<ClientConfig>,
52 connections: DashMap<usize, Connection>,
53 next_id: Arc<parking_lot::Mutex<usize>>,
54}
55
56impl ConnectionPool {
57 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 pub async fn get(&self) -> Result<Connection> {
68 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 self.cleanup_idle();
79
80 if self.connections.len() >= self.config.max_connections {
82 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
84
85 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 self.create_connection().await
100 }
101
102 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 endpoint = endpoint
111 .timeout(self.config.request_timeout)
112 .connect_timeout(self.config.connect_timeout);
113
114 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 if self.config.tls_enabled {
123 if let Some(_tls_config) = &self.config.tls_config {
124 debug!("TLS configuration requested but not yet implemented");
127 }
128 }
129
130 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 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 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 pub fn close_all(&self) {
176 info!("Closing all connections ({})", self.connections.len());
177 self.connections.clear();
178 }
179
180 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#[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 let now = Instant::now();
219 let last_used = Arc::new(RwLock::new(now));
220
221 std::thread::sleep(Duration::from_millis(10));
223
224 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}