use std::collections::HashSet;
use std::sync::Arc;
use tracing::{debug, warn};
use super::stats::WebSeedStats;
pub struct WebSeedClient {
base_url: String,
client: reqwest::Client,
active_requests: Arc<std::sync::Mutex<HashSet<u32>>>,
stats: Arc<WebSeedStats>,
}
impl WebSeedClient {
pub fn new(base_url: &str) -> Self {
debug!(url = base_url, "Creating WebSeedClient");
crate::http::client_pool::ensure_rustls_provider();
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.connect_timeout(std::time::Duration::from_secs(10))
.pool_max_idle_per_host(4)
.build()
.unwrap_or_else(|_| reqwest::Client::new());
Self {
base_url: base_url.to_string(),
client,
active_requests: Arc::new(std::sync::Mutex::new(HashSet::new())),
stats: Arc::new(WebSeedStats::new()),
}
}
pub fn with_shared_stats(base_url: &str, stats: Arc<WebSeedStats>) -> Self {
debug!(url = base_url, "Creating WebSeedClient with shared stats");
crate::http::client_pool::ensure_rustls_provider();
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.connect_timeout(std::time::Duration::from_secs(10))
.pool_max_idle_per_host(4)
.build()
.unwrap_or_else(|_| reqwest::Client::new());
Self {
base_url: base_url.to_string(),
client,
active_requests: Arc::new(std::sync::Mutex::new(HashSet::new())),
stats,
}
}
pub fn can_request(&self, piece_index: u32) -> bool {
let active = self
.active_requests
.lock()
.unwrap_or_else(|e| e.into_inner());
!active.contains(&piece_index)
}
pub fn mark_requesting(&self, piece_index: u32) {
let mut active = self
.active_requests
.lock()
.unwrap_or_else(|e| e.into_inner());
active.insert(piece_index);
}
pub fn clear_request(&self, piece_index: u32) {
let mut active = self
.active_requests
.lock()
.unwrap_or_else(|e| e.into_inner());
active.remove(&piece_index);
}
pub fn active_request_count(&self) -> usize {
let active = self
.active_requests
.lock()
.unwrap_or_else(|e| e.into_inner());
active.len()
}
pub fn stats(&self) -> &WebSeedStats {
&self.stats
}
pub async fn download_piece(
&self,
piece_index: u32,
_piece_length: u64,
piece_offset: u64,
length: u64,
) -> Result<Vec<u8>, String> {
let range_end = piece_offset + length.saturating_sub(1);
let range_header = format!("bytes={}-{}", piece_offset, range_end);
debug!(
piece_index,
offset = piece_offset,
length,
url = self.base_url,
range = %range_header,
"Web-seed HTTP Range request"
);
let response = self
.client
.get(&self.base_url)
.header("Range", &range_header)
.header("User-Agent", crate::constants::USER_AGENT)
.send()
.await
.map_err(|e| format!("HTTP request failed: {}", e))?;
let status = response.status().as_u16();
if status != 200 && status != 206 {
return Err(format!("Unexpected HTTP status {} from web-seed", status));
}
let data = response
.bytes()
.await
.map_err(|e| format!("Failed to read response body: {}", e))?
.to_vec();
self.stats.record_bytes(data.len() as u64);
if data.len() != length as usize {
warn!(
expected = length,
actual = data.len(),
piece_index,
"Web-seed response size mismatch"
);
}
Ok(data)
}
pub async fn request_piece(
&self,
piece_index: u32,
piece_length: u32,
total_length: u64,
) -> Result<Vec<u8>, String> {
if !self.can_request(piece_index) {
return Err(format!("Piece {} already being requested", piece_index));
}
self.mark_requesting(piece_index);
let piece_offset = piece_index as u64 * piece_length as u64;
let remaining = total_length.saturating_sub(piece_offset);
let actual_length = std::cmp::min(piece_length as u64, remaining);
let result = self
.download_piece(
piece_index,
piece_length as u64,
piece_offset,
actual_length,
)
.await;
self.clear_request(piece_index);
result
}
pub fn is_available(&self) -> bool {
true
}
pub fn url(&self) -> &str {
&self.base_url
}
}