Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

chore(router): adding cache for client creation based on proxy (#10158)

Shivansh Mathur7445ec7c0a60
diff --git a/crates/external_services/src/http_client/client.rs b/crates/external_services/src/http_client/client.rs
index 1f88f59507..34bf22c9a9 100644
--- a/crates/external_services/src/http_client/client.rs
+++ b/crates/external_services/src/http_client/client.rs
@@ -1,4 +1,4 @@
-use std::time::Duration;
+use std::{collections::HashMap, sync::RwLock, time::Duration};
use base64::Engine;
use common_utils::consts::BASE64_ENGINE;
@@ -9,8 +9,17 @@ use masking::ExposeInterface;
use once_cell::sync::OnceCell;
static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
+
+static PROXY_CLIENT_CACHE: OnceCell<RwLock<HashMap<Proxy, reqwest::Client>>> = OnceCell::new();
+
use router_env::logger;
+use super::metrics;
+
+trait ProxyClientCacheKey {
+ fn cache_key(&self) -> Option<Proxy>;
+}
+
// We may need to use outbound proxy to connect to external world.
// Precedence will be the environment variables, followed by the config.
#[allow(missing_docs)]
@@ -87,6 +96,12 @@ pub fn get_client_builder(
let proxy_exclusion_config =
reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default());
+ logger::debug!(
+ "Proxy HTTP Proxy -> {:?} and HTTPS Proxy -> {:?}",
+ proxy_config.http_url.clone(),
+ proxy_config.https_url.clone()
+ );
+
// Proxy all HTTPS traffic through the configured HTTPS proxy
if let Some(url) = proxy_config.https_url.as_ref() {
client_builder = client_builder.proxy(
@@ -170,13 +185,114 @@ fn apply_mitm_certificate(
client_builder
}
+impl ProxyClientCacheKey for Proxy {
+ fn cache_key(&self) -> Option<Proxy> {
+ if self.has_proxy_config() {
+ logger::debug!("Using proxy config as cache key: {:?}", self);
+
+ // Return a clone of the proxy config for caching
+ // Exclude timeout from cache key by creating a normalized version
+ Some(Self {
+ http_url: self.http_url.clone(),
+ https_url: self.https_url.clone(),
+ bypass_proxy_hosts: self.bypass_proxy_hosts.clone(),
+ mitm_ca_certificate: self.mitm_ca_certificate.clone(),
+ idle_pool_connection_timeout: None, // Exclude timeout from cache key
+ mitm_enabled: self.mitm_enabled,
+ })
+ } else {
+ None
+ }
+ }
+}
+
+fn get_or_create_proxy_client(
+ cache: &RwLock<HashMap<Proxy, reqwest::Client>>,
+ cache_key: Proxy,
+ proxy_config: &Proxy,
+ metrics_tag: &[router_env::opentelemetry::KeyValue],
+) -> CustomResult<reqwest::Client, HttpClientError> {
+ let read_result = cache
+ .read()
+ .ok()
+ .and_then(|read_lock| read_lock.get(&cache_key).cloned());
+
+ let client = match read_result {
+ Some(cached_client) => {
+ logger::debug!("Retrieved cached proxy client for config: {:?}", cache_key);
+ metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
+ cached_client
+ }
+ None => {
+ let mut write_lock = cache.try_write().map_err(|_| {
+ error_stack::Report::new(HttpClientError::ClientConstructionFailed)
+ .attach_printable("Failed to acquire proxy client cache write lock")
+ })?;
+
+ match write_lock.get(&cache_key) {
+ Some(cached_client) => {
+ logger::debug!(
+ "Retrieved cached proxy client after write lock for config: {:?}",
+ cache_key
+ );
+ metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
+ cached_client.clone()
+ }
+ None => {
+ logger::info!("Creating new proxy client for config: {:?}", cache_key);
+ metrics::HTTP_CLIENT_CACHE_MISS.add(1, metrics_tag);
+
+ let new_client =
+ apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
+ .build()
+ .change_context(HttpClientError::ClientConstructionFailed)
+ .attach_printable("Failed to construct proxy client")?;
+
+ metrics::HTTP_CLIENT_CREATED.add(1, metrics_tag);
+ write_lock.insert(cache_key.clone(), new_client.clone());
+ logger::debug!("Cached new proxy client for config: {:?}", cache_key);
+ new_client
+ }
+ }
+ }
+ };
+
+ Ok(client)
+}
+
fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, HttpClientError> {
- Ok(DEFAULT_CLIENT
- .get_or_try_init(|| {
- apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
- .build()
- .change_context(HttpClientError::ClientConstructionFailed)
- .attach_printable("Failed to construct base client")
- })?
- .clone())
+ // Check if proxy configuration is provided using trait method
+ if let Some(cache_key) = proxy_config.cache_key() {
+ logger::debug!(
+ "Using proxy-specific client cache with key: {:?}",
+ cache_key
+ );
+
+ let metrics_tag = router_env::metric_attributes!(("client_type", "proxy"));
+
+ let cache = PROXY_CLIENT_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
+
+ let client = get_or_create_proxy_client(cache, cache_key, proxy_config, metrics_tag)?;
+
+ Ok(client)
+ } else {
+ logger::debug!("No proxy configuration detected, using DEFAULT_CLIENT");
+
+ let metrics_tag = router_env::metric_attributes!(("client_type", "default"));
+
+ // Use DEFAULT_CLIENT for non-proxy scenarios
+ let client = DEFAULT_CLIENT
+ .get_or_try_init(|| {
+ logger::info!("Initializing DEFAULT_CLIENT (no proxy configuration)");
+ metrics::HTTP_CLIENT_CREATED.add(1, metrics_tag);
+ apply_mitm_certificate(get_client_builder(proxy_config)?, proxy_config)
+ .build()
+ .change_context(HttpClientError::ClientConstructionFailed)
+ .attach_printable("Failed to construct default client")
+ })?
+ .clone();
+
+ metrics::HTTP_CLIENT_CACHE_HIT.add(1, metrics_tag);
+ Ok(client)
+ }
}
diff --git a/crates/external_services/src/http_client/metrics.rs b/crates/external_services/src/http_client/metrics.rs
index 5b6f48334f..78582421f9 100644
--- a/crates/external_services/src/http_client/metrics.rs
+++ b/crates/external_services/src/http_client/metrics.rs
@@ -7,3 +7,8 @@ counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER);
counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER);
+
+// HTTP Client creation metrics
+counter_metric!(HTTP_CLIENT_CREATED, GLOBAL_METER);
+counter_metric!(HTTP_CLIENT_CACHE_HIT, GLOBAL_METER);
+counter_metric!(HTTP_CLIENT_CACHE_MISS, GLOBAL_METER);
diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs
index b91fdaabc9..1a0ea2d6db 100644
--- a/crates/hyperswitch_interfaces/src/types.rs
+++ b/crates/hyperswitch_interfaces/src/types.rs
@@ -416,7 +416,7 @@ pub type ExternalVaultCreateType =
dyn ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>;
/// Proxy configuration structure
-#[derive(Debug, serde::Deserialize, Clone)]
+#[derive(Debug, serde::Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(default)]
pub struct Proxy {
/// The URL of the HTTP proxy server.
@@ -451,6 +451,12 @@ impl Default for Proxy {
}
}
+impl Proxy {
+ /// Check if any proxy configuration is present
+ pub fn has_proxy_config(&self) -> bool {
+ self.http_url.is_some() || self.https_url.is_some()
+ }
+}
/// Proxy override configuration for rollout-based proxy switching
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProxyOverride {
diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs
index 0650dfe7ee..0dcf77a4ce 100644
--- a/crates/masking/src/secret.rs
+++ b/crates/masking/src/secret.rs
@@ -150,6 +150,17 @@ where
{
}
+impl<SecretValue, MaskingStrategy> std::hash::Hash for Secret<SecretValue, MaskingStrategy>
+where
+ Self: PeekInterface<SecretValue>,
+ SecretValue: std::hash::Hash,
+ MaskingStrategy: Strategy<SecretValue>,
+{
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.peek().hash(state);
+ }
+}
+
impl<SecretValue, MaskingStrategy> fmt::Debug for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
@@ -280,6 +291,32 @@ where
}
}
+#[cfg(test)]
+mod hash_tests {
+ use std::hash::{DefaultHasher, Hash, Hasher};
+
+ use super::*;
+
+ #[test]
+ fn test_secret_hash_implementation() {
+ let secret1: Secret<String> = Secret::new("test_string".to_string());
+ let secret2: Secret<String> = Secret::new("test_string".to_string());
+ let secret3: Secret<String> = Secret::new("different_string".to_string());
+
+ // Test that equal secrets hash to the same value
+ let mut hasher1 = DefaultHasher::new();
+ let mut hasher2 = DefaultHasher::new();
+ secret1.hash(&mut hasher1);
+ secret2.hash(&mut hasher2);
+ assert_eq!(hasher1.finish(), hasher2.finish());
+
+ // Test that different secrets hash to different values (usually)
+ let mut hasher3 = DefaultHasher::new();
+ secret3.hash(&mut hasher3);
+ assert_ne!(hasher1.finish(), hasher3.finish());
+ }
+}
+
#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {