use std::collections::HashSet;
use std::sync::Arc;
use futures::StreamExt;
use tracing::{debug, warn};
use super::stats::WebSeedStats;
use crate::http::client_identity::ClientTlsConfig;
use crate::request::request_group::AtomicProgress;
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 {
Self::new_with_tls(base_url, &ClientTlsConfig::default())
.expect("web-seed HTTP client configuration must be valid")
}
pub(crate) fn new_with_tls(base_url: &str, tls: &ClientTlsConfig) -> Result<Self, String> {
debug!(url = base_url, "Creating WebSeedClient");
crate::http::client_pool::ensure_rustls_provider();
let client = build_client(tls)?;
Ok(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 {
Self::with_shared_stats_and_tls(base_url, stats, &ClientTlsConfig::default())
.expect("web-seed HTTP client configuration must be valid")
}
pub(crate) fn with_shared_stats_and_tls(
base_url: &str,
stats: Arc<WebSeedStats>,
tls: &ClientTlsConfig,
) -> Result<Self, String> {
debug!(url = base_url, "Creating WebSeedClient with shared stats");
crate::http::client_pool::ensure_rustls_provider();
let client = build_client(tls)?;
Ok(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> {
self.download_piece_with_activity(piece_index, piece_length, piece_offset, length, None)
.await
}
pub(crate) async fn download_piece_with_activity(
&self,
piece_index: u32,
_piece_length: u64,
piece_offset: u64,
length: u64,
network_activity: Option<&AtomicProgress>,
) -> 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 mut data = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| format!("Failed to read response body: {}", e))?;
if !chunk.is_empty()
&& let Some(progress) = network_activity
{
progress.record_network_activity();
}
data.extend_from_slice(&chunk);
}
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> {
self.request_piece_with_activity(piece_index, piece_length, total_length, None)
.await
}
pub(crate) async fn request_piece_with_activity(
&self,
piece_index: u32,
piece_length: u32,
total_length: u64,
network_activity: Option<&AtomicProgress>,
) -> 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_with_activity(
piece_index,
piece_length as u64,
piece_offset,
actual_length,
network_activity,
)
.await;
self.clear_request(piece_index);
result
}
pub fn is_available(&self) -> bool {
true
}
pub fn url(&self) -> &str {
&self.base_url
}
}
fn build_client(tls: &ClientTlsConfig) -> Result<reqwest::Client, String> {
let builder = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
.pool_max_idle_per_host(4)
.gzip(false);
crate::http::client_identity::apply(builder, tls)
.map_err(|error| error.to_string())?
.build()
.map_err(|error| format!("web-seed HTTP client build failed: {error}"))
}