use std::sync::Arc;
use http::HeaderMap;
use crate::{
IntoUri,
blocking::{
BlockingClientBuilder,
download::Download,
imp::{blocking_token_bucket::BlockingTokenBucket, ureq_client::UreqClient},
},
shared::DownloadConfig,
};
#[derive(Clone)]
pub struct Client {
client: UreqClient,
headers: HeaderMap,
default_max_retries: Option<u64>,
limiter: Arc<BlockingTokenBucket>,
}
impl Client {
pub fn new() -> Self {
BlockingClientBuilder::default().build().unwrap()
}
pub(crate) fn new_inner(
agent: ureq::Agent,
headers: HeaderMap,
default_max_retries: Option<u64>,
max_bytes_per_second: Option<u64>,
) -> Self {
let limiter = Arc::new(BlockingTokenBucket::new(max_bytes_per_second));
Self {
client: UreqClient::new(agent),
headers,
default_max_retries,
limiter,
}
}
pub fn builder() -> BlockingClientBuilder {
BlockingClientBuilder::default()
}
pub fn get(&self, uri: impl IntoUri) -> Download {
let mut config = DownloadConfig::new(uri, &self.headers);
config.max_retries(self.default_max_retries);
Download::new(self.client.clone(), self.limiter.clone(), config)
}
pub fn max_bytes_per_second(&self, max_bytes_per_second: Option<u64>) {
self.limiter.set_max_bytes_per_second(max_bytes_per_second);
}
}
impl Default for Client {
fn default() -> Self {
Self::new()
}
}