use std::sync::Arc;
use std::time::Duration;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::time::timeout;
use tracing::{debug, info, warn};
use crate::error::Result;
use crate::ftp::connection::FtpMode;
use crate::ftp::connection::negotiation::RawFtpControl;
use crate::ftp::connection_pool::FtpConnectionPool;
#[derive(Debug, Clone)]
pub struct FtpFinishConfig {
pub reuse_connection: bool,
pub finish_timeout: Duration,
pub username: String,
pub host: String,
pub port: u16,
pub mode: FtpMode,
pub base_working_dir: String,
}
impl Default for FtpFinishConfig {
fn default() -> Self {
Self {
reuse_connection: true,
finish_timeout: Duration::from_secs(60),
username: String::new(),
host: String::new(),
port: 21,
mode: FtpMode::Passive,
base_working_dir: "/".to_string(),
}
}
}
#[derive(Debug)]
pub struct FtpFinishResult {
pub transfer_complete: bool,
pub connection_pooled: bool,
}
pub struct FtpFinishHandler;
impl FtpFinishHandler {
pub async fn finish(
mut control: RawFtpControl,
config: &FtpFinishConfig,
pool: Option<Arc<FtpConnectionPool>>,
) -> FtpFinishResult {
let mut transfer_complete = false;
let mut connection_pooled = false;
match timeout(config.finish_timeout, control.read_transfer_complete()).await {
Ok(Ok(true)) => {
transfer_complete = true;
info!(
"FTP transfer complete (226) for {}:{}",
config.host, config.port
);
}
Ok(Ok(false)) => {
warn!(
"FTP transfer finished with non-226 status for {}:{}",
config.host, config.port
);
}
Ok(Err(e)) => {
debug!(
"FTP finish response error (ignorable, download complete): {}",
e
);
}
Err(_) => {
debug!(
"FTP timeout waiting for 226 response from {}:{}",
config.host, config.port
);
}
}
let should_pool = transfer_complete && config.reuse_connection && pool.is_some();
if should_pool {
let pool_ref = pool.as_ref().unwrap();
match Self::pool_connection(control, config, pool_ref.clone()).await {
Ok(()) => {
connection_pooled = true;
debug!(
"FTP connection to {}:{} returned to pool (baseWorkingDir={})",
config.host, config.port, config.base_working_dir
);
}
Err(e) => {
debug!(
"Failed to pool FTP connection to {}:{}: {} (connection will be dropped)",
config.host, config.port, e
);
}
}
} else {
if let Err(e) = control.quit().await {
debug!(
"FTP QUIT failed for {}:{} (may already be closed): {}",
config.host, config.port, e
);
}
}
FtpFinishResult {
transfer_complete,
connection_pooled,
}
}
async fn pool_connection(
control: RawFtpControl,
config: &FtpFinishConfig,
pool: Arc<FtpConnectionPool>,
) -> Result<()> {
let buf_reader = control.into_inner();
let stream = buf_reader.into_inner();
pool.return_raw_connection(
stream,
&config.host,
config.port,
&config.username,
config.mode,
&config.base_working_dir,
)
.await
}
}
#[derive(Debug)]
pub struct PooledFtpControl {
pub reader: BufReader<TcpStream>,
pub host: String,
pub port: u16,
pub username: String,
pub base_working_dir: String,
pub read_timeout: Duration,
}
impl PooledFtpControl {
pub fn new(
stream: TcpStream,
host: String,
port: u16,
username: String,
base_working_dir: String,
read_timeout: Duration,
) -> Self {
Self {
reader: BufReader::new(stream),
host,
port,
username,
base_working_dir,
read_timeout,
}
}
pub fn into_raw_control(self) -> RawFtpControl {
RawFtpControl::new(self.reader, self.host, self.read_timeout)
}
pub fn base_working_dir(&self) -> &str {
&self.base_working_dir
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_finish_config_default() {
let config = FtpFinishConfig::default();
assert!(config.reuse_connection);
assert_eq!(config.finish_timeout, Duration::from_secs(60));
assert_eq!(config.port, 21);
assert_eq!(config.base_working_dir, "/");
assert!(config.username.is_empty());
assert!(config.host.is_empty());
}
#[test]
fn test_finish_result_default() {
let result = FtpFinishResult {
transfer_complete: false,
connection_pooled: false,
};
assert!(!result.transfer_complete);
assert!(!result.connection_pooled);
}
#[tokio::test]
async fn test_finish_without_pool() {
let config = FtpFinishConfig {
reuse_connection: true,
finish_timeout: Duration::from_millis(100),
username: "test".to_string(),
host: "ftp.example.com".to_string(),
port: 21,
mode: FtpMode::Passive,
base_working_dir: "/pub".to_string(),
};
assert!(config.reuse_connection);
assert_eq!(config.base_working_dir, "/pub");
}
#[test]
fn test_pooled_ftp_control_creation() {
let config = FtpFinishConfig {
base_working_dir: "/var/ftp".to_string(),
..Default::default()
};
assert_eq!(config.base_working_dir, "/var/ftp");
}
#[test]
fn test_pool_key_construction() {
let username = "admin";
let host = "ftp.example.com";
let port: u16 = 21;
let key_with_user = format!("{}@{}({})", username, host, port);
assert_eq!(key_with_user, "admin@ftp.example.com(21)");
let key_no_user = format!("{}({})", host, port);
assert_eq!(key_no_user, "ftp.example.com(21)");
}
}