use crate::tcp::Tcp;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct PoolConfig {
pub max_size: usize,
pub max_idle: u64,
pub max_lifetime: u64,
pub health_check_timeout: u64,
}
impl Default for PoolConfig {
fn default() -> Self {
Self {
max_size: 3,
max_idle: 600, max_lifetime: 3600, health_check_timeout: 5,
}
}
}
#[derive(Debug)]
struct IdleConn {
tcp: Tcp,
created_at: Instant,
last_used: Instant,
}
impl IdleConn {
fn is_healthy(&self, config: &PoolConfig) -> bool {
!lifetime_expired(self.created_at, config)
&& self.last_used.elapsed() <= Duration::from_secs(config.max_idle)
}
}
fn lifetime_expired(created_at: Instant, config: &PoolConfig) -> bool {
created_at.elapsed() > Duration::from_secs(config.max_lifetime)
}
#[derive(Debug, Default)]
struct PoolState {
idle: Vec<IdleConn>,
active: usize,
generation: u64,
}
#[derive(Debug, Clone)]
pub struct ConnectionPool {
state: Arc<Mutex<PoolState>>,
config: PoolConfig,
}
impl ConnectionPool {
pub fn new(max_size: usize) -> Result<Self, std::io::Error> {
Self::with_config(PoolConfig {
max_size,
..Default::default()
})
}
pub fn with_config(config: PoolConfig) -> Result<Self, std::io::Error> {
Ok(Self {
state: Arc::new(Mutex::new(PoolState::default())),
config,
})
}
fn lock(&self) -> MutexGuard<'_, PoolState> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn get_connection(&self) -> Result<PooledConn, std::io::Error> {
self.get_connection_with(Tcp::new)
}
fn get_connection_with(
&self,
connect: impl FnOnce() -> Result<Tcp, std::io::Error>,
) -> Result<PooledConn, std::io::Error> {
let generation = {
let mut state = self.lock();
state.idle.retain(|conn| conn.is_healthy(&self.config));
if let Some(conn) = state.idle.pop() {
state.active += 1;
return Ok(PooledConn {
pool: self.clone(),
tcp: Some(conn.tcp),
created_at: conn.created_at,
generation: state.generation,
});
}
if state.idle.len() + state.active >= self.config.max_size {
return Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
"Connection pool exhausted",
));
}
state.active += 1;
state.generation
};
match connect() {
Ok(tcp) => Ok(PooledConn {
pool: self.clone(),
tcp: Some(tcp),
created_at: Instant::now(),
generation,
}),
Err(e) => {
self.release(generation);
Err(e)
}
}
}
fn release(&self, generation: u64) -> bool {
let mut state = self.lock();
if state.generation != generation {
return false;
}
state.active -= 1;
true
}
pub fn stats(&self) -> PoolStats {
let state = self.lock();
PoolStats {
total: state.idle.len() + state.active,
active: state.active,
idle: state.idle.len(),
max_size: self.config.max_size,
}
}
pub fn close(&self) {
let mut state = self.lock();
state.idle.clear();
state.active = 0;
state.generation += 1;
}
}
pub struct PooledConn {
pool: ConnectionPool,
tcp: Option<Tcp>,
created_at: Instant,
generation: u64,
}
impl PooledConn {
pub fn get_mut(&mut self) -> &mut Tcp {
self.tcp.as_mut().expect("连接仅在 Drop 时被取走")
}
pub fn execute<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Tcp) -> R,
{
f(self.get_mut())
}
}
impl Drop for PooledConn {
fn drop(&mut self) {
let tcp = self.tcp.take();
let mut state = self.pool.lock();
if state.generation != self.generation {
return;
}
state.active -= 1;
if let Some(tcp) = tcp
&& !lifetime_expired(self.created_at, &self.pool.config)
{
state.idle.push(IdleConn {
tcp,
created_at: self.created_at,
last_used: Instant::now(),
});
}
}
}
#[derive(Debug, Clone)]
pub struct PoolStats {
pub total: usize,
pub active: usize,
pub idle: usize,
pub max_size: usize,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tcp::{HANDSHAKE, TcpConfig};
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener};
use std::sync::atomic::{AtomicUsize, Ordering};
fn skip_network() -> bool {
if std::env::var("RUSTDX_SKIP_INTEGRATION_TESTS").is_ok() {
println!("⚠️ 跳过集成测试 (RUSTDX_SKIP_INTEGRATION_TESTS 已设置)");
return true;
}
false
}
fn fake_server() -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
let mut alive = Vec::new();
for stream in listener.incoming() {
let mut stream = stream.unwrap();
for &pack in HANDSHAKE {
let mut request = vec![0; pack.len()];
stream.read_exact(&mut request).unwrap();
stream.write_all(&[0; 16]).unwrap();
}
alive.push(stream);
}
});
addr
}
fn connect_fake(addr: SocketAddr) -> Result<Tcp, std::io::Error> {
let config = TcpConfig {
timeout: Duration::from_secs(2),
..Default::default()
};
Tcp::with_servers(&config, &[addr])
}
fn local_port(conn: &mut PooledConn) -> u16 {
conn.get_mut().get_ref().0.local_addr().unwrap().port()
}
fn assert_stats(pool: &ConnectionPool, total: usize, active: usize, idle: usize) {
let stats = pool.stats();
assert_eq!(
(stats.total, stats.active, stats.idle),
(total, active, idle)
);
}
#[test]
fn test_pool_creation() {
let pool = ConnectionPool::new(3).unwrap();
let stats = pool.stats();
assert_eq!(stats.total, 0);
assert_eq!(stats.active, 0);
assert_eq!(stats.max_size, 3);
}
#[test]
fn test_pool_get_connection() {
if skip_network() {
return;
}
let pool = ConnectionPool::new(3).unwrap();
let conn1 = pool.get_connection();
assert!(conn1.is_ok());
let stats = pool.stats();
assert_eq!(stats.total, 1);
assert_eq!(stats.active, 1);
assert_eq!(stats.idle, 0);
}
#[test]
fn test_pool_connection_return() {
if skip_network() {
return;
}
let pool = ConnectionPool::new(3).unwrap();
{
let _conn = pool.get_connection().unwrap();
let stats = pool.stats();
assert_eq!(stats.active, 1);
}
let stats = pool.stats();
assert_eq!(stats.active, 0);
assert_eq!(stats.idle, 1);
}
#[test]
fn test_pool_max_size() {
if skip_network() {
return;
}
let pool = ConnectionPool::new(2).unwrap();
let _conn1 = pool.get_connection().unwrap();
let stats = pool.stats();
assert_eq!(stats.total, 1);
let _conn2 = pool.get_connection().unwrap();
let stats = pool.stats();
assert_eq!(stats.total, 2);
let result = pool.get_connection();
assert!(result.is_err());
}
#[test]
fn test_pool_connection_reuse() {
if skip_network() {
return;
}
let pool = ConnectionPool::new(2).unwrap();
{
let _conn = pool.get_connection().unwrap();
}
let stats = pool.stats();
assert_eq!(stats.total, 1);
let _conn2 = pool.get_connection().unwrap();
let stats = pool.stats();
assert_eq!(stats.total, 1); assert_eq!(stats.active, 1);
}
#[test]
fn test_pool_close() {
if skip_network() {
return;
}
let pool = ConnectionPool::new(3).unwrap();
let _conn1 = pool.get_connection().unwrap();
let _conn2 = pool.get_connection().unwrap();
let stats = pool.stats();
assert_eq!(stats.total, 2);
pool.close();
let stats = pool.stats();
assert_eq!(stats.total, 0);
}
#[test]
fn test_pool_config() {
let config = PoolConfig {
max_size: 5,
max_idle: 300,
max_lifetime: 1800,
health_check_timeout: 10,
};
let pool = ConnectionPool::with_config(config).unwrap();
let stats = pool.stats();
assert_eq!(stats.max_size, 5);
}
#[test]
fn test_return_after_idle_cleanup_keeps_accounting() {
let addr = fake_server();
let pool = ConnectionPool::with_config(PoolConfig {
max_size: 2,
max_idle: 0, ..Default::default()
})
.unwrap();
let connect = || connect_fake(addr);
let a = pool.get_connection_with(connect).unwrap();
let mut b = pool.get_connection_with(connect).unwrap();
let b_port = local_port(&mut b);
drop(a);
assert_stats(&pool, 2, 1, 1);
std::thread::sleep(Duration::from_millis(5));
let mut c = pool.get_connection_with(connect).unwrap();
let c_port = local_port(&mut c);
assert_ne!(b_port, c_port);
assert_stats(&pool, 2, 2, 0);
drop(b);
assert_stats(&pool, 2, 1, 1);
assert_eq!(local_port(&mut c), c_port);
drop(c);
assert_stats(&pool, 2, 0, 2);
std::thread::sleep(Duration::from_millis(5));
let _d = pool.get_connection_with(connect).unwrap();
let _e = pool.get_connection_with(connect).unwrap();
assert_stats(&pool, 2, 2, 0);
let err = pool.get_connection_with(connect).err().unwrap();
assert_eq!(err.kind(), std::io::ErrorKind::WouldBlock);
}
#[test]
fn test_idle_connection_is_reused_without_connecting() {
let addr = fake_server();
let pool = ConnectionPool::new(2).unwrap();
let connects = AtomicUsize::new(0);
let connect = || {
connects.fetch_add(1, Ordering::SeqCst);
connect_fake(addr)
};
let mut first = pool.get_connection_with(connect).unwrap();
let port = local_port(&mut first);
drop(first);
assert_stats(&pool, 1, 0, 1);
let mut second = pool.get_connection_with(connect).unwrap();
assert_eq!(local_port(&mut second), port);
assert_eq!(connects.load(Ordering::SeqCst), 1);
assert_stats(&pool, 1, 1, 0);
assert_eq!(second.execute(|_tcp| 42), 42);
}
#[test]
fn test_connect_runs_without_pool_lock() {
let addr = fake_server();
let pool = ConnectionPool::new(1).unwrap();
let conn = pool
.get_connection_with(|| {
assert_stats(&pool, 1, 1, 0);
let err = pool
.get_connection_with(|| unreachable!("池已满时不应建连"))
.err()
.unwrap();
assert_eq!(err.kind(), std::io::ErrorKind::WouldBlock);
connect_fake(addr)
})
.unwrap();
assert_stats(&pool, 1, 1, 0);
drop(conn);
assert_stats(&pool, 1, 0, 1);
}
#[test]
fn test_connect_failure_releases_reservation() {
let addr = fake_server();
let pool = ConnectionPool::new(1).unwrap();
let err = pool
.get_connection_with(|| Err(std::io::ErrorKind::ConnectionRefused.into()))
.err()
.unwrap();
assert_eq!(err.kind(), std::io::ErrorKind::ConnectionRefused);
assert_stats(&pool, 0, 0, 0);
let _conn = pool.get_connection_with(|| connect_fake(addr)).unwrap();
assert_stats(&pool, 1, 1, 0);
}
#[test]
fn test_close_discards_borrowed_connections() {
let addr = fake_server();
let pool = ConnectionPool::new(2).unwrap();
let connect = || connect_fake(addr);
let borrowed = pool.get_connection_with(connect).unwrap();
drop(pool.get_connection_with(connect).unwrap());
assert_stats(&pool, 2, 1, 1);
pool.close();
assert_stats(&pool, 0, 0, 0);
drop(borrowed);
assert_stats(&pool, 0, 0, 0);
let _conn = pool.get_connection_with(connect).unwrap();
assert_stats(&pool, 1, 1, 0);
}
#[test]
fn test_expired_lifetime_connection_is_dropped_on_return() {
let addr = fake_server();
let pool = ConnectionPool::with_config(PoolConfig {
max_size: 1,
max_lifetime: 0,
..Default::default()
})
.unwrap();
let conn = pool.get_connection_with(|| connect_fake(addr)).unwrap();
std::thread::sleep(Duration::from_millis(5));
drop(conn);
assert_stats(&pool, 0, 0, 0);
}
}