make BaseClientBuild accept custom proxies (#12232)

close #12230 

implement `BaseClientBuilder::proxy(self, Proxy)` and apply it to the
underlying reqwest::Client.
This commit is contained in:
James Z.M. Gao 2025-03-18 03:18:55 +08:00 committed by GitHub
parent ba73231164
commit 05352882ea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 23 additions and 2 deletions

View file

@ -1,5 +1,5 @@
use itertools::Itertools;
use reqwest::{Client, ClientBuilder, Response};
use reqwest::{Client, ClientBuilder, Proxy, Response};
use reqwest_middleware::{ClientWithMiddleware, Middleware};
use reqwest_retry::policies::ExponentialBackoff;
use reqwest_retry::{
@ -56,6 +56,7 @@ pub struct BaseClientBuilder<'a> {
url_auth_policies: Option<UrlAuthPolicies>,
default_timeout: Duration,
extra_middleware: Option<ExtraMiddleware>,
proxies: Vec<Proxy>,
}
/// A list of user-defined middlewares to be applied to the client.
@ -90,6 +91,7 @@ impl BaseClientBuilder<'_> {
url_auth_policies: None,
default_timeout: Duration::from_secs(30),
extra_middleware: None,
proxies: vec![],
}
}
}
@ -161,6 +163,12 @@ impl<'a> BaseClientBuilder<'a> {
self
}
#[must_use]
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.proxies.push(proxy);
self
}
pub fn is_offline(&self) -> bool {
matches!(self.connectivity, Connectivity::Offline)
}
@ -301,6 +309,13 @@ impl<'a> BaseClientBuilder<'a> {
client_builder
};
// apply proxies
let mut client_builder = client_builder;
for p in &self.proxies {
client_builder = client_builder.proxy(p.clone());
}
let client_builder = client_builder;
client_builder
.build()
.expect("Failed to build HTTP client.")

View file

@ -8,7 +8,7 @@ use async_http_range_reader::AsyncHttpRangeReader;
use futures::{FutureExt, StreamExt, TryStreamExt};
use http::HeaderMap;
use itertools::Either;
use reqwest::{Response, StatusCode};
use reqwest::{Proxy, Response, StatusCode};
use reqwest_middleware::ClientWithMiddleware;
use tokio::sync::Semaphore;
use tracing::{info_span, instrument, trace, warn, Instrument};
@ -133,6 +133,12 @@ impl<'a> RegistryClientBuilder<'a> {
self
}
#[must_use]
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.base_client_builder = self.base_client_builder.proxy(proxy);
self
}
pub fn build(self) -> RegistryClient {
// Build a base client
let builder = self.base_client_builder;