sentinel_proxy/agents/
pool.rs

1//! Agent connection pooling.
2
3use std::sync::atomic::{AtomicU32, AtomicU64};
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use sentinel_agent_protocol::AgentClient;
8use tokio::sync::RwLock;
9use tracing::{debug, trace};
10
11/// Agent connection pool for efficient connection reuse.
12pub struct AgentConnectionPool {
13    /// Pool configuration
14    pub(super) max_connections: usize,
15    pub(super) min_idle: usize,
16    pub(super) max_idle: usize,
17    pub(super) idle_timeout: Duration,
18    /// Available connections
19    pub(super) connections: Arc<RwLock<Vec<AgentConnection>>>,
20    /// Active connections count
21    pub(super) active_count: AtomicU32,
22    /// Total connections created
23    pub(super) total_created: AtomicU64,
24}
25
26/// Pooled agent connection.
27pub(super) struct AgentConnection {
28    /// The actual client
29    pub client: AgentClient,
30    /// Creation time
31    pub created_at: Instant,
32    /// Last used time
33    pub last_used: Instant,
34    /// Is healthy
35    pub healthy: bool,
36}
37
38impl AgentConnectionPool {
39    /// Create a new connection pool.
40    pub fn new(
41        max_connections: usize,
42        min_idle: usize,
43        max_idle: usize,
44        idle_timeout: Duration,
45    ) -> Self {
46        trace!(
47            max_connections = max_connections,
48            min_idle = min_idle,
49            max_idle = max_idle,
50            idle_timeout_secs = idle_timeout.as_secs(),
51            "Creating agent connection pool"
52        );
53
54        debug!(
55            max_connections = max_connections,
56            "Agent connection pool initialized"
57        );
58
59        Self {
60            max_connections,
61            min_idle,
62            max_idle,
63            idle_timeout,
64            connections: Arc::new(RwLock::new(Vec::new())),
65            active_count: AtomicU32::new(0),
66            total_created: AtomicU64::new(0),
67        }
68    }
69
70    /// Get active connection count.
71    pub fn active_count(&self) -> u32 {
72        let count = self.active_count.load(std::sync::atomic::Ordering::Relaxed);
73        trace!(active_connections = count, "Retrieved active connection count");
74        count
75    }
76
77    /// Get total connections created.
78    pub fn total_created(&self) -> u64 {
79        let total = self.total_created.load(std::sync::atomic::Ordering::Relaxed);
80        trace!(total_created = total, "Retrieved total connections created");
81        total
82    }
83}