use std::sync::Arc;
use http::HeaderMap;
use crate::{
ClientBuilder, Error, IntoUri,
nonblocking::{
download::Download,
imp::{reqwest_client::ReqwestClient, tokio_token_bucket::TokioTokenBucket},
},
shared::DownloadConfig,
};
#[derive(Clone)]
pub struct Client {
client: ReqwestClient,
headers: HeaderMap,
default_max_retries: Option<u64>,
limiter: Arc<TokioTokenBucket>,
}
impl ClientBuilder {
pub fn build(self) -> Result<Client, Error> {
if let Some(e) = self.err {
return Err(e);
}
let client = self.reqwest_client.unwrap_or_default();
Ok(Client::new_inner(
ReqwestClient::new(client),
self.headers,
self.default_max_retries,
self.max_bytes_per_second,
))
}
}
impl Client {
pub fn new() -> Self {
ClientBuilder::default().build().unwrap()
}
fn new_inner(
client: ReqwestClient,
headers: HeaderMap,
default_max_retries: Option<u64>,
max_bytes_per_second: Option<u64>,
) -> Self {
let limiter = Arc::new(TokioTokenBucket::new(max_bytes_per_second));
Self {
client,
headers,
default_max_retries,
limiter,
}
}
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub fn get(&self, url: impl IntoUri) -> Download {
let mut config = DownloadConfig::new(url, &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()
}
}