From 50b436100e2a1e1a16f64727f82b85da54085d2d Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Fri, 1 Jul 2022 00:03:43 +1000 Subject: [PATCH] Reuse `Client` everywhere instead of recreate one which pools the connection to the same site (github.com). This commit also sets `USER_AGENT` so that quickinstall can reuse it. Signed-off-by: Jiahao XU --- src/fetchers/quickinstall.rs | 9 ++------- src/helpers.rs | 11 +++++++---- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/fetchers/quickinstall.rs b/src/fetchers/quickinstall.rs index 120dd6cb..50076394 100644 --- a/src/fetchers/quickinstall.rs +++ b/src/fetchers/quickinstall.rs @@ -7,13 +7,10 @@ use tokio::task::JoinHandle; use url::Url; use super::Data; -use crate::{ - download_and_extract, new_reqwest_client_builder, remote_exists, BinstallError, PkgFmt, -}; +use crate::{download_and_extract, new_reqwest_client, remote_exists, BinstallError, PkgFmt}; const BASE_URL: &str = "https://github.com/alsuren/cargo-quickinstall/releases/download"; const STATS_URL: &str = "https://warehouse-clerk-tmp.vercel.app/api/crate"; -const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); pub struct QuickInstall { package: String, @@ -91,9 +88,7 @@ impl QuickInstall { let url = Url::parse(&stats_url)?; debug!("Sending installation report to quickinstall ({url})"); - new_reqwest_client_builder() - .user_agent(USER_AGENT) - .build()? + new_reqwest_client()? .request(Method::HEAD, url.clone()) .send() .await diff --git a/src/helpers.rs b/src/helpers.rs index d48e97b6..04a8473b 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -59,8 +59,10 @@ pub fn load_manifest_path>( }) } -pub fn new_reqwest_client_builder() -> ClientBuilder { - let mut builder = ClientBuilder::new(); +fn new_reqwest_client_builder() -> ClientBuilder { + const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); + + let mut builder = ClientBuilder::new().user_agent(USER_AGENT); if let Some(ReqwestConfig { secure, min_tls }) = REQWESTGLOBALCONFIG.get() { if *secure { @@ -77,8 +79,9 @@ pub fn new_reqwest_client_builder() -> ClientBuilder { builder } -pub fn new_reqwest_client() -> reqwest::Result { - new_reqwest_client_builder().build() +pub fn new_reqwest_client() -> reqwest::Result<&'static Client> { + static CLIENT: OnceCell = OnceCell::new(); + CLIENT.get_or_try_init(|| new_reqwest_client_builder().build()) } pub async fn remote_exists(url: Url, method: Method) -> Result {