1use crate::ssh::client::{SshClient, SshClientConfig};
6use crate::ssh::privatekey::PrivateKey;
7use fynx_platform::{FynxError, FynxResult};
8use std::collections::HashMap;
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11use tokio::sync::Mutex;
12use tracing::{debug, info, warn};
13
14#[derive(Debug, Clone)]
16pub struct ConnectionPoolConfig {
17 pub max_connections: usize,
19 pub idle_timeout: Duration,
21 pub enable_keepalive: bool,
23 pub keepalive_interval: Duration,
25}
26
27impl Default for ConnectionPoolConfig {
28 fn default() -> Self {
29 Self {
30 max_connections: 10,
31 idle_timeout: Duration::from_secs(300), enable_keepalive: true,
33 keepalive_interval: Duration::from_secs(60),
34 }
35 }
36}
37
38impl ConnectionPoolConfig {
39 pub fn new() -> Self {
41 Self::default()
42 }
43
44 pub fn with_max_connections(mut self, max: usize) -> Self {
46 self.max_connections = max;
47 self
48 }
49
50 pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
52 self.idle_timeout = timeout;
53 self
54 }
55
56 pub fn with_keepalive(mut self, enabled: bool) -> Self {
58 self.enable_keepalive = enabled;
59 self
60 }
61
62 pub fn with_keepalive_interval(mut self, interval: Duration) -> Self {
64 self.keepalive_interval = interval;
65 self
66 }
67}
68
69#[derive(Debug, Clone)]
71pub enum PoolAuth {
72 Password(String),
74 PrivateKey(PrivateKey),
76}
77
78struct PooledConnection {
80 client: SshClient,
82 last_used: Instant,
84 in_use: bool,
86 auth: PoolAuth,
88}
89
90pub struct SshConnectionPool {
121 config: ConnectionPoolConfig,
123 connections: Arc<Mutex<HashMap<String, PooledConnection>>>,
125}
126
127impl SshConnectionPool {
128 pub fn new(config: ConnectionPoolConfig) -> Self {
130 Self {
131 config,
132 connections: Arc::new(Mutex::new(HashMap::new())),
133 }
134 }
135
136 fn connection_key(addr: &str, username: &str) -> String {
138 format!("{}@{}", username, addr)
139 }
140
141 pub async fn get(
157 &self,
158 addr: &str,
159 username: &str,
160 password: &str,
161 ) -> FynxResult<Arc<Mutex<SshClient>>> {
162 let key = Self::connection_key(addr, username);
163 let mut connections = self.connections.lock().await;
164
165 if let Some(conn) = connections.get_mut(&key) {
167 if !conn.in_use {
168 debug!("Reusing connection: {}", key);
170 conn.in_use = true;
171 conn.last_used = Instant::now();
172
173 let client = Arc::new(Mutex::new(
175 self.create_connection(
179 addr,
180 username,
181 PoolAuth::Password(password.to_string()),
182 )
183 .await?,
184 ));
185
186 return Ok(client);
187 }
188 }
189
190 if connections.len() >= self.config.max_connections {
192 warn!("Connection pool full ({} connections)", connections.len());
193 return Err(FynxError::Protocol("Connection pool is full".to_string()));
194 }
195
196 debug!("Creating new connection: {}", key);
198 let client = self
199 .create_connection(addr, username, PoolAuth::Password(password.to_string()))
200 .await?;
201
202 let pooled = PooledConnection {
203 client,
204 last_used: Instant::now(),
205 in_use: true,
206 auth: PoolAuth::Password(password.to_string()),
207 };
208
209 connections.insert(key.clone(), pooled);
210
211 let client = self
216 .create_connection(addr, username, PoolAuth::Password(password.to_string()))
217 .await?;
218 Ok(Arc::new(Mutex::new(client)))
219 }
220
221 pub async fn get_with_key(
223 &self,
224 addr: &str,
225 username: &str,
226 private_key: &PrivateKey,
227 ) -> FynxResult<Arc<Mutex<SshClient>>> {
228 let key = Self::connection_key(addr, username);
229 let connections = self.connections.lock().await;
230
231 if connections.len() >= self.config.max_connections {
233 warn!("Connection pool full ({} connections)", connections.len());
234 return Err(FynxError::Protocol("Connection pool is full".to_string()));
235 }
236
237 debug!("Creating new connection with key: {}", key);
239 let client = self
240 .create_connection(addr, username, PoolAuth::PrivateKey(private_key.clone()))
241 .await?;
242
243 Ok(Arc::new(Mutex::new(client)))
244 }
245
246 async fn create_connection(
248 &self,
249 addr: &str,
250 username: &str,
251 auth: PoolAuth,
252 ) -> FynxResult<SshClient> {
253 let mut config = SshClientConfig::default();
255
256 if self.config.enable_keepalive {
257 config.keepalive_interval = Some(self.config.keepalive_interval);
258 }
259
260 let mut client = SshClient::connect_with_config(addr, config).await?;
262
263 match auth {
265 PoolAuth::Password(ref password) => {
266 client.authenticate_password(username, password).await?;
267 }
268 PoolAuth::PrivateKey(ref key) => {
269 client.authenticate_publickey(username, key).await?;
270 }
271 }
272
273 Ok(client)
274 }
275
276 pub async fn cleanup_idle(&self) -> FynxResult<usize> {
284 let mut connections = self.connections.lock().await;
285 let now = Instant::now();
286 let idle_timeout = self.config.idle_timeout;
287
288 let initial_count = connections.len();
289
290 connections.retain(|key, conn| {
291 let idle_time = now.duration_since(conn.last_used);
292 if !conn.in_use && idle_time > idle_timeout {
293 info!(
294 "Removing idle connection: {} (idle for {:?})",
295 key, idle_time
296 );
297 false
298 } else {
299 true
300 }
301 });
302
303 let removed = initial_count - connections.len();
304 if removed > 0 {
305 debug!("Cleaned up {} idle connections", removed);
306 }
307
308 Ok(removed)
309 }
310
311 pub async fn close_all(&self) -> FynxResult<()> {
313 let mut connections = self.connections.lock().await;
314 let count = connections.len();
315
316 connections.clear();
317
318 info!("Closed {} connections", count);
319 Ok(())
320 }
321
322 pub async fn connection_count(&self) -> usize {
324 self.connections.lock().await.len()
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn test_connection_pool_config_default() {
334 let config = ConnectionPoolConfig::default();
335 assert_eq!(config.max_connections, 10);
336 assert_eq!(config.idle_timeout, Duration::from_secs(300));
337 assert!(config.enable_keepalive);
338 assert_eq!(config.keepalive_interval, Duration::from_secs(60));
339 }
340
341 #[test]
342 fn test_connection_pool_config_builder() {
343 let config = ConnectionPoolConfig::new()
344 .with_max_connections(5)
345 .with_idle_timeout(Duration::from_secs(600))
346 .with_keepalive(false)
347 .with_keepalive_interval(Duration::from_secs(30));
348
349 assert_eq!(config.max_connections, 5);
350 assert_eq!(config.idle_timeout, Duration::from_secs(600));
351 assert!(!config.enable_keepalive);
352 assert_eq!(config.keepalive_interval, Duration::from_secs(30));
353 }
354
355 #[test]
356 fn test_connection_key_generation() {
357 let key = SshConnectionPool::connection_key("server:22", "user");
358 assert_eq!(key, "user@server:22");
359 }
360
361 #[tokio::test]
362 async fn test_connection_pool_creation() {
363 let config = ConnectionPoolConfig::default();
364 let pool = SshConnectionPool::new(config);
365
366 assert_eq!(pool.connection_count().await, 0);
367 }
368
369 #[tokio::test]
370 async fn test_cleanup_idle_empty_pool() {
371 let config = ConnectionPoolConfig::default();
372 let pool = SshConnectionPool::new(config);
373
374 let removed = pool.cleanup_idle().await.unwrap();
375 assert_eq!(removed, 0);
376 }
377
378 #[tokio::test]
379 async fn test_close_all_empty_pool() {
380 let config = ConnectionPoolConfig::default();
381 let pool = SshConnectionPool::new(config);
382
383 pool.close_all().await.unwrap();
384 assert_eq!(pool.connection_count().await, 0);
385 }
386}