use crate::{
connectors::{create_source_with_options, Source, Target},
protocols::Protocol,
Result, TinyEtlError,
};
use async_trait::async_trait;
use std::collections::HashMap;
use std::io::Write;
use tempfile::NamedTempFile;
use tracing::info;
use url::Url;
pub const OPTIONS: &[&str] = &[
"header.*",
"auth.basic.username",
"auth.basic.password",
"auth.bearer",
];
pub struct HttpProtocol;
impl Default for HttpProtocol {
fn default() -> Self {
Self::new()
}
}
impl HttpProtocol {
pub fn new() -> Self {
Self
}
async fn download_to_temp_with_type_and_options(
&self,
url: &Url,
source_type: Option<&str>,
options: &HashMap<String, String>,
) -> Result<NamedTempFile> {
let client = reqwest::Client::new();
info!("Downloading from HTTP URL: {}", url);
let mut request = client.get(url.as_str());
for (key, value) in options {
if let Some(header_name) = key.strip_prefix("header.") {
info!("Adding custom header: {}", header_name);
request = request.header(header_name, value);
}
}
if let (Some(username), Some(password)) = (
options.get("auth.basic.username"),
options.get("auth.basic.password"),
) {
info!("Using basic authentication");
request = request.basic_auth(username, Some(password));
}
if let Some(token) = options.get("auth.bearer") {
info!("Using bearer token authentication");
request = request.bearer_auth(token);
}
let response = request
.send()
.await
.map_err(|e| TinyEtlError::Connection(format!("Failed to fetch URL {}: {}", url, e)))?;
if !response.status().is_success() {
return Err(TinyEtlError::Connection(format!(
"HTTP request failed with status {}: {}",
response.status(),
url
)));
}
if let Some(size) = response.content_length() {
info!("Downloading {} bytes", size);
} else {
info!("Downloading file (size unknown)");
}
let content = response.bytes().await.map_err(|e| {
TinyEtlError::Connection(format!("Failed to read response body: {}", e))
})?;
info!("Download completed, {} bytes received", content.len());
let extension = self.get_file_extension(url, source_type);
let mut temp_file = if let Some(ext) = extension {
tempfile::Builder::new()
.suffix(&format!(".{}", ext))
.tempfile()
.map_err(TinyEtlError::Io)?
} else {
tempfile::NamedTempFile::new().map_err(TinyEtlError::Io)?
};
temp_file.write_all(&content).map_err(TinyEtlError::Io)?;
temp_file.flush().map_err(TinyEtlError::Io)?;
Ok(temp_file)
}
fn extract_extension_from_url(&self, url: &Url) -> Option<String> {
crate::protocols::extension_from_path(url.path())
}
fn get_file_extension(&self, url: &Url, source_type: Option<&str>) -> Option<String> {
if let Some(forced_type) = source_type {
Some(forced_type.to_lowercase())
} else {
self.extract_extension_from_url(url)
}
}
}
#[async_trait]
impl Protocol for HttpProtocol {
async fn create_source(
&self,
url: &Url,
options: &HashMap<String, String>,
) -> Result<Box<dyn Source>> {
self.create_source_with_type(url, None, options).await
}
async fn create_source_with_type(
&self,
url: &Url,
source_type: Option<&str>,
options: &HashMap<String, String>,
) -> Result<Box<dyn Source>> {
let temp_file = self
.download_to_temp_with_type_and_options(url, source_type, options)
.await?;
let extension = self.get_file_extension(url, source_type);
let temp_dir = std::env::temp_dir();
let file_name = format!(
"tinyetl_download_{}.{}",
std::process::id(),
extension.unwrap_or_else(|| "tmp".to_string())
);
let persistent_path = temp_dir.join(file_name);
std::fs::copy(temp_file.path(), &persistent_path).map_err(TinyEtlError::Io)?;
let final_path = persistent_path.to_string_lossy().to_string();
create_source_with_options(&final_path, options)
}
async fn create_target(
&self,
_url: &Url,
_options: &HashMap<String, String>,
) -> Result<Box<dyn Target>> {
Err(TinyEtlError::Configuration(
"HTTP protocol does not support target/write operations. Use file:// protocol for local output.".to_string()
))
}
fn validate_url(&self, url: &Url) -> Result<()> {
match url.scheme() {
"http" | "https" => {}
_ => {
return Err(TinyEtlError::Configuration(format!(
"HTTP protocol requires http:// or https:// scheme, got: {}",
url.scheme()
)))
}
}
if url.host().is_none() {
return Err(TinyEtlError::Configuration(
"HTTP protocol requires a valid host".to_string(),
));
}
Ok(())
}
fn name(&self) -> &'static str {
"http"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_http_url() {
let protocol = HttpProtocol::new();
let url = Url::parse("http://example.com/data.csv").unwrap();
assert!(protocol.validate_url(&url).is_ok());
let url = Url::parse("https://example.com/data.json").unwrap();
assert!(protocol.validate_url(&url).is_ok());
let url = Url::parse("file:///path/to/file.csv").unwrap();
assert!(protocol.validate_url(&url).is_err());
let url = Url::parse("ftp://example.com/file.csv").unwrap();
assert!(protocol.validate_url(&url).is_err());
}
#[test]
fn test_extract_extension_from_url() {
let protocol = HttpProtocol::new();
let url = Url::parse("https://example.com/data.csv").unwrap();
assert_eq!(
protocol.extract_extension_from_url(&url),
Some("csv".to_string())
);
let url = Url::parse("https://example.com/path/to/file.json").unwrap();
assert_eq!(
protocol.extract_extension_from_url(&url),
Some("json".to_string())
);
let url = Url::parse("https://example.com/data.parquet").unwrap();
assert_eq!(
protocol.extract_extension_from_url(&url),
Some("parquet".to_string())
);
let url = Url::parse("https://example.com/api/data").unwrap();
assert_eq!(protocol.extract_extension_from_url(&url), None);
let url = Url::parse("https://example.com/data.csv?format=csv&limit=1000").unwrap();
assert_eq!(
protocol.extract_extension_from_url(&url),
Some("csv".to_string())
);
}
#[test]
fn test_target_not_supported() {
let protocol = HttpProtocol::new();
let url = Url::parse("https://example.com/upload").unwrap();
let options = std::collections::HashMap::new();
tokio_test::block_on(async {
let result = protocol.create_target(&url, &options).await;
assert!(result.is_err());
});
}
}