From 305bf8123dee2dd7e7c95b87c486aa067caa2058 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Fri, 6 Jan 2023 14:02:14 +1100 Subject: [PATCH] Optimize `Client`: Reduce size from 16 to 8 (#655) Signed-off-by: Jiahao XU --- crates/binstalk-downloader/src/remote.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/binstalk-downloader/src/remote.rs b/crates/binstalk-downloader/src/remote.rs index 876cd998..5632c19f 100644 --- a/crates/binstalk-downloader/src/remote.rs +++ b/crates/binstalk-downloader/src/remote.rs @@ -41,12 +41,15 @@ pub struct HttpError { err: reqwest::Error, } -#[derive(Clone, Debug)] -pub struct Client { +#[derive(Debug)] +struct Inner { client: reqwest::Client, - rate_limit: Arc>>, + rate_limit: Mutex>, } +#[derive(Clone, Debug)] +pub struct Client(Arc); + impl Client { /// * `per` - must not be 0. /// * `num_request` - maximum number of requests to be processed for @@ -76,14 +79,14 @@ impl Client { .tcp_nodelay(false) .build()?; - Ok(Client { + Ok(Client(Arc::new(Inner { client: client.clone(), - rate_limit: Arc::new(Mutex::new( + rate_limit: Mutex::new( ServiceBuilder::new() .rate_limit(num_request.get(), per) .service(client), - )), - }) + ), + }))) } inner(user_agent.as_ref(), min_tls, per, num_request) @@ -91,7 +94,7 @@ impl Client { /// Return inner reqwest client. pub fn get_inner(&self) -> &reqwest::Client { - &self.client + &self.0.client } async fn send_request_inner( @@ -110,7 +113,7 @@ impl Client { // the future, then release the lock before // polling the future, which performs network I/O that could // take really long. - let future = self.rate_limit.lock().await.ready().await?.call(request); + let future = self.0.rate_limit.lock().await.ready().await?.call(request); let response = future.await?;