mod operations;
mod session;
mod stats;
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use crate::ftp::connection::FtpMode;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ConnectionKey {
pub host: String,
pub port: u16,
pub username: String,
pub password: String,
pub base_working_dir: String,
}
impl std::fmt::Debug for ConnectionKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConnectionKey")
.field("host", &self.host)
.field("port", &self.port)
.field("username", &self.username)
.field("password", &"<redacted>")
.field("base_working_dir", &self.base_working_dir)
.finish()
}
}
impl ConnectionKey {
pub fn new(
host: &str,
port: u16,
username: &str,
password: &str,
base_working_dir: &str,
) -> Self {
Self {
host: host.to_string(),
port,
username: username.to_string(),
password: password.to_string(),
base_working_dir: base_working_dir.to_string(),
}
}
pub fn new_simple(host: &str, port: u16, username: &str, password: &str) -> Self {
Self::new(host, port, username, password, "/")
}
pub fn to_pool_key_string(&self) -> String {
if self.username.is_empty() {
format!("{}({})", self.host, self.port)
} else {
format!("{}@{}({})", self.username, self.host, self.port)
}
}
}
#[derive(Debug)]
pub struct RawControlStream {
pub reader: BufReader<TcpStream>,
pub created_at: std::time::Instant,
pub last_used: std::time::Instant,
pub reuse_count: u64,
}
impl RawControlStream {
pub fn new(stream: TcpStream, _read_timeout: Duration) -> Self {
let now = std::time::Instant::now();
Self {
reader: BufReader::new(stream),
created_at: now,
last_used: now,
reuse_count: 0,
}
}
pub fn mark_used(&mut self) {
self.last_used = std::time::Instant::now();
self.reuse_count += 1;
}
pub fn age(&self) -> Duration {
self.created_at.elapsed()
}
pub fn idle_time(&self) -> Duration {
self.last_used.elapsed()
}
pub fn is_healthy(&self, max_idle_time: Duration) -> bool {
self.last_used.elapsed() < max_idle_time
}
pub fn into_inner(self) -> TcpStream {
self.reader.into_inner()
}
pub fn into_buf_reader(self) -> BufReader<TcpStream> {
self.reader
}
}
pub struct PooledConnection {
pub control: RawControlStream,
pub key: ConnectionKey,
pub mode: FtpMode,
pub read_timeout: Duration,
}
impl std::fmt::Debug for PooledConnection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PooledConnection")
.field("key", &self.key)
.field("mode", &self.mode)
.field("read_timeout", &self.read_timeout)
.field("age", &self.control.age())
.field("idle_time", &self.control.idle_time())
.field("reuse_count", &self.control.reuse_count)
.finish_non_exhaustive()
}
}
impl PooledConnection {
pub fn new(
stream: TcpStream,
key: ConnectionKey,
mode: FtpMode,
read_timeout: Duration,
) -> Self {
Self {
control: RawControlStream::new(stream, read_timeout),
key,
mode,
read_timeout,
}
}
pub fn is_healthy(&self, max_idle_time: Duration) -> bool {
self.control.is_healthy(max_idle_time)
}
pub(crate) fn is_reusable(
&self,
max_idle_time: Duration,
max_connection_age: Duration,
) -> bool {
self.is_healthy(max_idle_time) && self.age() <= max_connection_age
}
pub fn age(&self) -> Duration {
self.control.age()
}
pub fn idle_time(&self) -> Duration {
self.control.idle_time()
}
pub fn mark_used(&mut self) {
self.control.mark_used();
}
pub fn base_working_dir(&self) -> &str {
&self.key.base_working_dir
}
}
#[derive(Debug, Clone)]
pub(crate) struct LruEntry {
pub(crate) key: PoolKey,
pub(crate) last_access: std::time::Instant,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum PoolKey {
Raw(ConnectionKey),
Control(ControlSessionKey),
}
#[derive(Debug, Clone)]
pub struct PoolConfig {
pub max_connections: usize,
pub max_idle_time: Duration,
pub max_connection_age: Duration,
pub connect_timeout: Duration,
pub read_timeout: Duration,
}
impl Default for PoolConfig {
fn default() -> Self {
Self {
max_connections: crate::constants::FTP_POOL_DEFAULT_MAX_CONNECTIONS,
max_idle_time: Duration::from_secs(
crate::constants::FTP_POOL_DEFAULT_MAX_IDLE_TIME_SECS,
),
max_connection_age: Duration::from_secs(
crate::constants::FTP_POOL_DEFAULT_MAX_CONNECTION_AGE_SECS,
),
connect_timeout: Duration::from_secs(
crate::constants::FTP_POOL_DEFAULT_CONNECT_TIMEOUT_SECS,
),
read_timeout: Duration::from_secs(crate::constants::FTP_POOL_DEFAULT_READ_TIMEOUT_SECS),
}
}
}
pub struct FtpConnectionPool {
pub(crate) state: Mutex<PoolState>,
pub(crate) config: PoolConfig,
pub(crate) stats: Mutex<PoolStats>,
}
pub(crate) struct PoolState {
pub(crate) connections: HashMap<ConnectionKey, PooledConnection>,
pub(crate) control_sessions: HashMap<ControlSessionKey, PooledControlSession>,
pub(crate) lru_order: Vec<LruEntry>,
}
impl FtpConnectionPool {
pub async fn cleanup_stale_count(&self) -> usize {
let before = self.size().await;
self.cleanup_stale().await;
before.saturating_sub(self.size().await)
}
pub fn new(max_connections: usize) -> Self {
let config = PoolConfig {
max_connections,
..Default::default()
};
Self::with_config(config)
}
pub fn with_config(config: PoolConfig) -> Self {
Self {
state: Mutex::new(PoolState {
connections: HashMap::new(),
control_sessions: HashMap::new(),
lru_order: Vec::new(),
}),
config,
stats: Mutex::new(PoolStats::default()),
}
}
}
pub fn create_pool(max_connections: usize) -> Arc<FtpConnectionPool> {
Arc::new(FtpConnectionPool::new(max_connections))
}
pub fn create_custom_pool(config: PoolConfig) -> Arc<FtpConnectionPool> {
Arc::new(FtpConnectionPool::with_config(config))
}
pub use stats::PoolStats;
pub(crate) use session::{ControlSessionIdentity, ControlSessionKey, PooledControlSession};