use async_trait::async_trait;
use url::Url;
use tempfile::NamedTempFile;
use std::process::Command;
use std::io::Write;
use tracing::info;
use crate::{
Result, TinyEtlError,
connectors::{Source, Target, create_source, create_target},
protocols::Protocol,
};
pub struct SshProtocol;
impl SshProtocol {
pub fn new() -> Self {
Self
}
async fn download_via_scp(&self, url: &Url) -> Result<NamedTempFile> {
let host = url.host_str()
.ok_or_else(|| TinyEtlError::Configuration("SSH URL must specify a host".to_string()))?;
let username = if !url.username().is_empty() {
url.username()
} else {
return Err(TinyEtlError::Configuration(
"SSH URL must specify a username (ssh://user@host/path)".to_string()
));
};
let port = url.port().unwrap_or(22);
let remote_path = url.path();
if remote_path.is_empty() || remote_path == "/" {
return Err(TinyEtlError::Configuration(
"SSH URL must specify a file path".to_string()
));
}
let extension = self.extract_extension_from_path(remote_path);
let temp_file = if let Some(ext) = extension {
tempfile::Builder::new()
.suffix(&format!(".{}", ext))
.tempfile()
.map_err(|e| TinyEtlError::Io(e))?
} else {
tempfile::NamedTempFile::new()
.map_err(|e| TinyEtlError::Io(e))?
};
let temp_path = temp_file.path().to_string_lossy().to_string();
let scp_source = format!("{}@{}:{}", username, host, remote_path);
info!("Downloading via SSH: {}", scp_source);
let output = Command::new("scp")
.arg("-P")
.arg(port.to_string())
.arg("-o")
.arg("StrictHostKeyChecking=no") .arg("-o")
.arg("UserKnownHostsFile=/dev/null") .arg("-q") .arg(&scp_source)
.arg(&temp_path)
.output()
.map_err(|e| TinyEtlError::Connection(format!("Failed to execute scp command: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(TinyEtlError::Connection(format!(
"SCP failed to download file from {}: {}",
scp_source,
stderr
)));
}
info!("SSH download completed");
Ok(temp_file)
}
async fn upload_via_scp(&self, url: &Url, local_path: &str) -> Result<()> {
let host = url.host_str()
.ok_or_else(|| TinyEtlError::Configuration("SSH URL must specify a host".to_string()))?;
let username = if !url.username().is_empty() {
url.username()
} else {
return Err(TinyEtlError::Configuration(
"SSH URL must specify a username (ssh://user@host/path)".to_string()
));
};
let port = url.port().unwrap_or(22);
let remote_path = url.path();
if remote_path.is_empty() || remote_path == "/" {
return Err(TinyEtlError::Configuration(
"SSH URL must specify a file path".to_string()
));
}
let scp_dest = format!("{}@{}:{}", username, host, remote_path);
info!("Uploading via SSH to: {}", scp_dest);
let output = Command::new("scp")
.arg("-P")
.arg(port.to_string())
.arg("-o")
.arg("StrictHostKeyChecking=no")
.arg("-o")
.arg("UserKnownHostsFile=/dev/null")
.arg("-q")
.arg(local_path)
.arg(&scp_dest)
.output()
.map_err(|e| TinyEtlError::Connection(format!("Failed to execute scp command: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(TinyEtlError::Connection(format!(
"SCP failed to upload file to {}: {}",
scp_dest,
stderr
)));
}
info!("SSH upload completed");
Ok(())
}
fn extract_extension_from_path(&self, path: &str) -> Option<String> {
if let Some(filename) = path.split('/').last() {
if let Some(extension) = filename.split('.').last() {
if extension.len() > 0 && extension.len() <= 10 && extension != filename {
return Some(extension.to_lowercase());
}
}
}
None
}
}
#[async_trait]
impl Protocol for SshProtocol {
async fn create_source(&self, url: &Url) -> Result<Box<dyn Source>> {
let temp_file = self.download_via_scp(url).await?;
let temp_path = temp_file.path().to_string_lossy().to_string();
create_source(&temp_path)
}
async fn create_target(&self, url: &Url) -> Result<Box<dyn Target>> {
Err(TinyEtlError::Configuration(
"SSH target implementation requires additional coordination with the ETL pipeline. Use file:// for local output and manually upload via SSH.".to_string()
))
}
fn validate_url(&self, url: &Url) -> Result<()> {
if url.scheme() != "ssh" {
return Err(TinyEtlError::Configuration(
format!("SSH protocol requires ssh:// scheme, got: {}", url.scheme())
));
}
if url.host().is_none() {
return Err(TinyEtlError::Configuration(
"SSH protocol requires a valid host".to_string()
));
}
if url.username().is_empty() {
return Err(TinyEtlError::Configuration(
"SSH protocol requires a username in the URL (ssh://user@host/path)".to_string()
));
}
let path = url.path();
if path.is_empty() || path == "/" {
return Err(TinyEtlError::Configuration(
"SSH protocol requires a file path".to_string()
));
}
Ok(())
}
fn name(&self) -> &'static str {
"ssh"
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_validate_ssh_url() {
let protocol = SshProtocol::new();
let url = Url::parse("ssh://user@example.com/path/to/file.csv").unwrap();
assert!(protocol.validate_url(&url).is_ok());
let url = Url::parse("ssh://user@example.com:2222/data/file.json").unwrap();
assert!(protocol.validate_url(&url).is_ok());
let url = Url::parse("ssh://example.com/path/to/file.csv").unwrap();
assert!(protocol.validate_url(&url).is_err());
let url = Url::parse("ssh://user@example.com/").unwrap();
assert!(protocol.validate_url(&url).is_err());
let url = Url::parse("http://example.com/file.csv").unwrap();
assert!(protocol.validate_url(&url).is_err());
}
#[test]
fn test_extract_extension_from_path() {
let protocol = SshProtocol::new();
assert_eq!(protocol.extract_extension_from_path("/path/to/data.csv"), Some("csv".to_string()));
assert_eq!(protocol.extract_extension_from_path("/data/file.json"), Some("json".to_string()));
assert_eq!(protocol.extract_extension_from_path("file.parquet"), Some("parquet".to_string()));
assert_eq!(protocol.extract_extension_from_path("/path/to/data"), None);
assert_eq!(protocol.extract_extension_from_path("/api/endpoint"), None);
}
#[test]
fn test_target_not_fully_supported() {
let protocol = SshProtocol::new();
let url = Url::parse("ssh://user@example.com/upload/file.csv").unwrap();
tokio_test::block_on(async {
let result = protocol.create_target(&url).await;
assert!(result.is_err());
});
}
#[test]
fn test_ssh_protocol_name() {
let protocol = SshProtocol::new();
assert_eq!(protocol.name(), "ssh");
}
#[test]
fn test_url_validation_error_messages() {
let protocol = SshProtocol::new();
let url = Url::parse("ftp://user@example.com/file.csv").unwrap();
let result = protocol.validate_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("SSH protocol requires ssh:// scheme"));
assert!(msg.contains("ftp"));
} else {
panic!("Expected Configuration error");
}
let url = Url::parse("ssh://example.com/file.csv").unwrap();
let result = protocol.validate_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("requires a username"));
} else {
panic!("Expected Configuration error");
}
let url = Url::parse("ssh://user@example.com").unwrap();
let result = protocol.validate_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("requires a file path"));
} else {
panic!("Expected Configuration error");
}
let url = Url::parse("ssh://user@example.com/").unwrap();
let result = protocol.validate_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("requires a file path"));
} else {
panic!("Expected Configuration error");
}
}
#[test]
fn test_extract_extension_edge_cases() {
let protocol = SshProtocol::new();
assert_eq!(protocol.extract_extension_from_path(""), None);
assert_eq!(protocol.extract_extension_from_path("/"), None);
assert_eq!(protocol.extract_extension_from_path("/.hidden"), Some("hidden".to_string())); assert_eq!(protocol.extract_extension_from_path("/path/to/."), None);
assert_eq!(protocol.extract_extension_from_path("/path/to/.."), None);
assert_eq!(protocol.extract_extension_from_path("/path/to/file."), None);
assert_eq!(protocol.extract_extension_from_path("/path/file.toolongextension"), None);
assert_eq!(protocol.extract_extension_from_path("/data.CSV"), Some("csv".to_string()));
assert_eq!(protocol.extract_extension_from_path("/file.JSON"), Some("json".to_string()));
assert_eq!(protocol.extract_extension_from_path("/archive.tar.gz"), Some("gz".to_string()));
assert_eq!(protocol.extract_extension_from_path("/home/user/documents/data.xlsx"), Some("xlsx".to_string()));
assert_eq!(protocol.extract_extension_from_path("./relative/path/file.txt"), Some("txt".to_string()));
assert_eq!(protocol.extract_extension_from_path("C:\\data\\file.csv"), Some("csv".to_string()));
}
#[test]
fn test_url_parsing_components() {
let url = Url::parse("ssh://user@example.com/path/to/file.csv").unwrap();
assert_eq!(url.host_str(), Some("example.com"));
assert_eq!(url.username(), "user");
assert_eq!(url.port(), None); assert_eq!(url.path(), "/path/to/file.csv");
let url = Url::parse("ssh://admin@server.local:2222/data/export.json").unwrap();
assert_eq!(url.host_str(), Some("server.local"));
assert_eq!(url.username(), "admin");
assert_eq!(url.port(), Some(2222));
assert_eq!(url.path(), "/data/export.json");
let url = Url::parse("ssh://user%2Bname@example.com/file.csv").unwrap();
assert_eq!(url.username(), "user%2Bname");
let url = Url::parse("ssh://root@192.168.1.100:22/tmp/data.parquet").unwrap();
assert_eq!(url.host_str(), Some("192.168.1.100"));
assert_eq!(url.port(), Some(22));
}
#[test]
fn test_scp_command_building() {
let url = Url::parse("ssh://user@example.com:2222/path/to/file.csv").unwrap();
let host = url.host_str().unwrap();
let username = url.username();
let port = url.port().unwrap_or(22);
let remote_path = url.path();
let scp_source = format!("{}@{}:{}", username, host, remote_path);
assert_eq!(scp_source, "user@example.com:/path/to/file.csv");
assert_eq!(port, 2222);
let scp_dest = format!("{}@{}:{}", username, host, "/upload/target.csv");
assert_eq!(scp_dest, "user@example.com:/upload/target.csv");
}
#[test]
fn test_default_port_handling() {
let url = Url::parse("ssh://user@example.com/file.csv").unwrap();
let port = url.port().unwrap_or(22);
assert_eq!(port, 22);
let url_with_port = Url::parse("ssh://user@example.com:443/file.csv").unwrap();
let port_explicit = url_with_port.port().unwrap_or(22);
assert_eq!(port_explicit, 443);
}
#[test]
fn test_path_validation_edge_cases() {
let protocol = SshProtocol::new();
let invalid_paths = vec![
"ssh://user@host", "ssh://user@host/", ];
for url_str in invalid_paths {
let url = Url::parse(url_str).unwrap();
assert!(protocol.validate_url(&url).is_err(), "Should reject URL: {}", url_str);
}
let valid_paths = vec![
"ssh://user@host/file",
"ssh://user@host/path/to/file.csv",
"ssh://user@host/data/export.json",
"ssh://user@host/home/user/.bashrc",
];
for url_str in valid_paths {
let url = Url::parse(url_str).unwrap();
assert!(protocol.validate_url(&url).is_ok(), "Should accept URL: {}", url_str);
}
}
#[tokio::test]
async fn test_create_source_url_validation() {
let protocol = SshProtocol::new();
let invalid_url = Url::parse("ssh://example.com/file.csv").unwrap(); let result = protocol.create_source(&invalid_url).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_create_target_error_handling() {
let protocol = SshProtocol::new();
let url = Url::parse("ssh://user@example.com/upload/file.csv").unwrap();
let result = protocol.create_target(&url).await;
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("SSH target implementation requires additional coordination"));
} else {
panic!("Expected specific Configuration error message");
}
}
#[test]
fn test_error_types_and_messages() {
let protocol = SshProtocol::new();
let url = Url::parse("http://example.com/file.csv").unwrap();
match protocol.validate_url(&url) {
Err(TinyEtlError::Configuration(_)) => {}, _ => panic!("Expected Configuration error"),
}
let url = Url::parse("ssh://host/file.csv").unwrap(); if let Err(TinyEtlError::Configuration(msg)) = protocol.validate_url(&url) {
assert!(msg.contains("username"));
assert!(msg.contains("ssh://user@host/path"));
} else {
panic!("Expected Configuration error with helpful message");
}
}
#[test]
fn test_temp_file_extension_preservation() {
let protocol = SshProtocol::new();
let paths_and_extensions = vec![
("/data/file.csv", Some("csv".to_string())),
("/exports/data.json", Some("json".to_string())),
("/files/archive.parquet", Some("parquet".to_string())),
("/backup/dump.sql", Some("sql".to_string())),
("/logs/access.log", Some("log".to_string())),
("/data/noextension", None),
];
for (path, expected_ext) in paths_and_extensions {
let actual_ext = protocol.extract_extension_from_path(path);
assert_eq!(actual_ext, expected_ext, "Failed for path: {}", path);
}
}
#[test]
fn test_ssh_protocol_instantiation() {
let protocol = SshProtocol::new();
assert_eq!(protocol.name(), "ssh");
let _: &dyn Protocol = &protocol;
}
}