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

feat(api_client): add api client trait (#1919)

harsh-sharma-juspay97b2747458fb
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a2644878ba..18191545ae 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -258,6 +258,10 @@ pub enum ApiClientError {
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
+ #[error("Request body serialization failed")]
+ BodySerializationFailed,
+ #[error("Unexpected state reached/Invariants conflicted")]
+ UnexpectedState,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index d37f22f750..b65487cc61 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -1,10 +1,16 @@
+use std::time::Duration;
+
use error_stack::{IntoReport, ResultExt};
+use http::{HeaderValue, Method};
+use masking::PeekInterface;
use once_cell::sync::OnceCell;
+use reqwest::{multipart::Form, IntoUrl};
+use super::request::Maskable;
use crate::{
configs::settings::{Locker, Proxy},
core::{
- errors::{self, CustomResult},
+ errors::{ApiClientError, CustomResult},
payments,
},
};
@@ -15,7 +21,7 @@ static PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
fn get_client_builder(
proxy_config: &Proxy,
should_bypass_proxy: bool,
-) -> CustomResult<reqwest::ClientBuilder, errors::ApiClientError> {
+) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let mut client_builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
if should_bypass_proxy {
@@ -27,7 +33,7 @@ fn get_client_builder(
client_builder = client_builder.proxy(
reqwest::Proxy::https(url)
.into_report()
- .change_context(errors::ApiClientError::InvalidProxyConfiguration)
+ .change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTPS proxy configuration error")?,
);
}
@@ -37,7 +43,7 @@ fn get_client_builder(
client_builder = client_builder.proxy(
reqwest::Proxy::http(url)
.into_report()
- .change_context(errors::ApiClientError::InvalidProxyConfiguration)
+ .change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTP proxy configuration error")?,
);
}
@@ -48,7 +54,7 @@ fn get_client_builder(
fn get_base_client(
proxy_config: &Proxy,
should_bypass_proxy: bool,
-) -> CustomResult<reqwest::Client, errors::ApiClientError> {
+) -> CustomResult<reqwest::Client, ApiClientError> {
Ok(if should_bypass_proxy
|| (proxy_config.http_url.is_none() && proxy_config.https_url.is_none())
{
@@ -60,7 +66,7 @@ fn get_base_client(
get_client_builder(proxy_config, should_bypass_proxy)?
.build()
.into_report()
- .change_context(errors::ApiClientError::ClientConstructionFailed)
+ .change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct base client")
})?
.clone())
@@ -73,7 +79,7 @@ pub(super) fn create_client(
should_bypass_proxy: bool,
client_certificate: Option<String>,
client_certificate_key: Option<String>,
-) -> CustomResult<reqwest::Client, errors::ApiClientError> {
+) -> CustomResult<reqwest::Client, ApiClientError> {
match (client_certificate, client_certificate_key) {
(Some(encoded_certificate), Some(encoded_certificate_key)) => {
let client_builder = get_client_builder(proxy_config, should_bypass_proxy)?;
@@ -87,7 +93,7 @@ pub(super) fn create_client(
.identity(identity)
.build()
.into_report()
- .change_context(errors::ApiClientError::ClientConstructionFailed)
+ .change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct client with certificate and certificate key")
}
_ => get_base_client(proxy_config, should_bypass_proxy),
@@ -110,3 +116,206 @@ pub(super) fn proxy_bypass_urls(locker: &Locker) -> Vec<String> {
format!("{basilisk_host}/tokenize/delete/token"),
]
}
+
+pub trait RequestBuilder: Send + Sync {
+ fn json(&mut self, body: serde_json::Value);
+ fn url_encoded_form(&mut self, body: serde_json::Value);
+ fn timeout(&mut self, timeout: Duration);
+ fn multipart(&mut self, form: Form);
+ fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>;
+ fn send(
+ self,
+ ) -> CustomResult<
+ Box<
+ (dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>>
+ + 'static),
+ >,
+ ApiClientError,
+ >;
+}
+
+pub trait ApiClient
+where
+ Self: Sized + Send + Sync,
+{
+ fn new(
+ proxy_config: Proxy,
+ whitelisted_urls: Vec<String>,
+ ) -> CustomResult<Self, ApiClientError>;
+ fn request<U: IntoUrl>(
+ &self,
+ method: Method,
+ url: String,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
+ fn request_with_certificate(
+ &self,
+ method: Method,
+ url: String,
+ certificate: Option<String>,
+ certificate_key: Option<String>,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
+}
+
+#[derive(Clone)]
+pub struct ProxyClient {
+ proxy_client: reqwest::Client,
+ non_proxy_client: reqwest::Client,
+ whitelisted_urls: Vec<String>,
+}
+
+impl ProxyClient {
+ fn get_reqwest_client(
+ &self,
+ base_url: String,
+ client_certificate: Option<String>,
+ client_certificate_key: Option<String>,
+ ) -> CustomResult<reqwest::Client, ApiClientError> {
+ match (client_certificate, client_certificate_key) {
+ (Some(certificate), Some(certificate_key)) => {
+ let client_builder =
+ reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
+ let identity = payments::helpers::create_identity_from_certificate_and_key(
+ certificate,
+ certificate_key,
+ )?;
+ Ok(client_builder
+ .identity(identity)
+ .build()
+ .into_report()
+ .change_context(ApiClientError::ClientConstructionFailed)
+ .attach_printable(
+ "Failed to construct client with certificate and certificate key",
+ )?)
+ }
+ (_, _) => {
+ if self.whitelisted_urls.contains(&base_url) {
+ Ok(self.non_proxy_client.clone())
+ } else {
+ Ok(self.proxy_client.clone())
+ }
+ }
+ }
+ }
+}
+
+pub struct RouterRequestBuilder {
+ // Using option here to get around the reinitialization problem
+ // request builder follows a chain pattern where the value is consumed and a newer requestbuilder is returned
+ // Since for this brief period of time between the value being consumed & newer request builder
+ // since requestbuilder does not allow moving the value
+ // leaves our struct in an inconsistent state, we are using option to get around rust semantics
+ inner: Option<reqwest::RequestBuilder>,
+}
+
+impl RequestBuilder for RouterRequestBuilder {
+ fn json(&mut self, body: serde_json::Value) {
+ self.inner = self.inner.take().map(|r| r.json(&body));
+ }
+ fn url_encoded_form(&mut self, body: serde_json::Value) {
+ self.inner = self.inner.take().map(|r| r.form(&body));
+ }
+
+ fn timeout(&mut self, timeout: Duration) {
+ self.inner = self.inner.take().map(|r| r.timeout(timeout));
+ }
+
+ fn multipart(&mut self, form: Form) {
+ self.inner = self.inner.take().map(|r| r.multipart(form));
+ }
+
+ fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError> {
+ let header_value = match value {
+ Maskable::Masked(hvalue) => HeaderValue::from_str(hvalue.peek()).map(|mut h| {
+ h.set_sensitive(true);
+ h
+ }),
+ Maskable::Normal(hvalue) => HeaderValue::from_str(&hvalue),
+ }
+ .into_report()
+ .change_context(ApiClientError::HeaderMapConstructionFailed)?;
+
+ self.inner = self.inner.take().map(|r| r.header(key, header_value));
+ Ok(())
+ }
+
+ fn send(
+ self,
+ ) -> CustomResult<
+ Box<
+ (dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>>
+ + 'static),
+ >,
+ ApiClientError,
+ > {
+ Ok(Box::new(
+ self.inner.ok_or(ApiClientError::UnexpectedState)?.send(),
+ ))
+ }
+}
+
+// TODO: remove this when integrating this trait
+#[allow(dead_code)]
+impl ApiClient for ProxyClient {
+ fn new(
+ proxy_config: Proxy,
+ whitelisted_urls: Vec<String>,
+ ) -> CustomResult<Self, ApiClientError> {
+ let non_proxy_client = reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .into_report()
+ .change_context(ApiClientError::ClientConstructionFailed)?;
+
+ let mut proxy_builder =
+ reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
+
+ if let Some(url) = proxy_config.https_url.as_ref() {
+ proxy_builder = proxy_builder.proxy(
+ reqwest::Proxy::https(url)
+ .into_report()
+ .change_context(ApiClientError::InvalidProxyConfiguration)?,
+ );
+ }
+
+ if let Some(url) = proxy_config.http_url.as_ref() {
+ proxy_builder = proxy_builder.proxy(
+ reqwest::Proxy::http(url)
+ .into_report()
+ .change_context(ApiClientError::InvalidProxyConfiguration)?,
+ );
+ }
+
+ let proxy_client = proxy_builder
+ .build()
+ .into_report()
+ .change_context(ApiClientError::InvalidProxyConfiguration)?;
+ Ok(Self {
+ proxy_client,
+ non_proxy_client,
+ whitelisted_urls,
+ })
+ }
+
+ fn request<U: IntoUrl>(
+ &self,
+ method: Method,
+ url: String,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
+ self.request_with_certificate(method, url, None, None)
+ }
+
+ fn request_with_certificate(
+ &self,
+ method: Method,
+ url: String,
+ certificate: Option<String>,
+ certificate_key: Option<String>,
+ ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
+ let client_builder = self
+ .get_reqwest_client(url.clone(), certificate, certificate_key)
+ .change_context(ApiClientError::ClientConstructionFailed)?;
+ Ok(Box::new(RouterRequestBuilder {
+ inner: Some(client_builder.request(method, url)),
+ }))
+ }
+}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 7a7bc9d891..bf95efe64f 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -10163,6 +10163,11 @@
"format": "int64",
"description": "The total number of refunds in the list"
},
+ "total_count": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The total number of refunds in the list"
+ },
"data": {
"type": "array",
"items": {