use std::sync::Arc;
use std::time::Duration;
use reqwest::Client as HttpClient;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tracing::{debug, instrument};
use super::auth::TokenManager;
use super::config::{UspsConfig, UspsEnvironment};
use super::error::{Result, UspsError};
use super::retry::RetryPolicy;
use crate::services::addresses::AddressesService;
use crate::services::labels::LabelsService;
use crate::services::locations::LocationsService;
use crate::services::manifests::ManifestsService;
use crate::services::payments::PaymentsService;
use crate::services::pickup::PickupService;
use crate::services::prices::PricesService;
use crate::services::standards::ServiceStandardsService;
use crate::services::tracking::TrackingService;
use crate::services::webhooks::WebhooksService;
#[derive(Debug, Clone)]
pub struct UspsClient {
inner: Arc<UspsClientInner>,
}
#[derive(Debug)]
struct UspsClientInner {
config: UspsConfig,
http_client: HttpClient,
token_manager: TokenManager,
}
impl UspsClient {
#[must_use]
pub fn builder() -> UspsClientBuilder {
UspsClientBuilder::new()
}
pub fn new(config: UspsConfig) -> Result<Self> {
let http_client = HttpClient::builder()
.timeout(config.timeout)
.build()
.map_err(UspsError::Http)?;
let token_manager = TokenManager::new(config.clone(), http_client.clone());
Ok(Self {
inner: Arc::new(UspsClientInner {
config,
http_client,
token_manager,
}),
})
}
#[must_use]
pub fn config(&self) -> &UspsConfig {
&self.inner.config
}
#[must_use]
pub fn addresses(&self) -> AddressesService {
AddressesService::new(self.clone())
}
#[must_use]
pub fn tracking(&self) -> TrackingService {
TrackingService::new(self.clone())
}
#[must_use]
pub fn prices(&self) -> PricesService {
PricesService::new(self.clone())
}
#[must_use]
pub fn labels(&self) -> LabelsService {
LabelsService::new(self.clone())
}
#[must_use]
pub fn pickup(&self) -> PickupService {
PickupService::new(self.clone())
}
#[must_use]
pub fn locations(&self) -> LocationsService {
LocationsService::new(self.clone())
}
#[must_use]
pub fn manifests(&self) -> ManifestsService {
ManifestsService::new(self.clone())
}
#[must_use]
pub fn webhooks(&self) -> WebhooksService {
WebhooksService::new(self.clone())
}
#[must_use]
pub fn service_standards(&self) -> ServiceStandardsService {
ServiceStandardsService::new(self.clone())
}
#[must_use]
pub fn payments(&self) -> PaymentsService {
PaymentsService::new(self.clone())
}
#[must_use]
pub fn token_manager(&self) -> &TokenManager {
&self.inner.token_manager
}
async fn execute_with_retry<F>(&self, endpoint: &str, build_req: F) -> Result<String>
where
F: Fn(&HttpClient, &str, &str) -> reqwest::RequestBuilder,
{
let url = format!("{}{endpoint}", self.inner.config.environment.base_url());
let mut attempt = 0;
loop {
let token = self.inner.token_manager.get_token().await?;
let request = build_req(&self.inner.http_client, &url, &token)
.header("Accept", "application/json");
let response = request.send().await.map_err(UspsError::Http)?;
let status = response.status();
let body = response.text().await.map_err(UspsError::Http)?;
if status.is_success() {
return Ok(body);
}
if RetryPolicy::is_retryable_status(status)
&& attempt < self.inner.config.retry_policy.max_retries
{
attempt += 1;
let backoff = self.inner.config.retry_policy.calculate_backoff(attempt);
tracing::warn!(
attempt = attempt,
max_retries = self.inner.config.retry_policy.max_retries,
status = %status,
endpoint = endpoint,
backoff_ms = backoff.as_millis(),
"Error reintentable HTTP de USPS. Reintentando tras pausa"
);
tokio::time::sleep(backoff).await;
continue;
}
return Err(UspsError::from_response(status, &body));
}
}
#[instrument(skip(self, query), name = "usps_get_with_query")]
pub async fn get_with_query<Q, T>(&self, endpoint: &str, query: &Q) -> Result<T>
where
Q: Serialize + ?Sized,
T: DeserializeOwned,
{
debug!("Enviando GET autenticado a {}", endpoint);
let body = self
.execute_with_retry(endpoint, |http, url, token| {
http.get(url)
.header("Authorization", format!("Bearer {token}"))
.query(query)
})
.await?;
serde_json::from_str::<T>(&body).map_err(UspsError::Serialization)
}
#[instrument(skip(self, body), name = "usps_post_json")]
pub async fn post_json<B, T>(&self, endpoint: &str, body: &B) -> Result<T>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
debug!("Enviando POST JSON autenticado a {}", endpoint);
let res_body = self
.execute_with_retry(endpoint, |http, url, token| {
http.post(url)
.header("Authorization", format!("Bearer {token}"))
.json(body)
})
.await?;
serde_json::from_str::<T>(&res_body).map_err(UspsError::Serialization)
}
#[instrument(skip(self), name = "usps_delete")]
pub async fn delete(&self, endpoint: &str) -> Result<String> {
debug!("Enviando DELETE autenticado a {}", endpoint);
self.execute_with_retry(endpoint, |http, url, token| {
http.delete(url)
.header("Authorization", format!("Bearer {token}"))
})
.await
}
}
#[derive(Debug, Default)]
pub struct UspsClientBuilder {
client_id: Option<String>,
client_secret: Option<String>,
environment: UspsEnvironment,
timeout: Option<Duration>,
retry_policy: Option<RetryPolicy>,
}
impl UspsClientBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn credentials(
mut self,
client_id: impl Into<String>,
client_secret: impl Into<String>,
) -> Self {
self.client_id = Some(client_id.into());
self.client_secret = Some(client_secret.into());
self
}
#[must_use]
pub fn environment(mut self, env: UspsEnvironment) -> Self {
self.environment = env;
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
#[must_use]
pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
self.retry_policy = Some(policy);
self
}
pub fn build(self) -> Result<UspsClient> {
let client_id = self.client_id.ok_or_else(|| {
UspsError::InvalidInput("Se requiere client_id para construir el cliente".to_string())
})?;
let client_secret = self.client_secret.ok_or_else(|| {
UspsError::InvalidInput(
"Se requiere client_secret para construir el cliente".to_string(),
)
})?;
let mut config = UspsConfig::new(client_id, client_secret, self.environment)?;
if let Some(timeout) = self.timeout {
config = config.with_timeout(timeout);
}
if let Some(retry_policy) = self.retry_policy {
config = config.with_retry_policy(retry_policy);
}
UspsClient::new(config)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_should_create_client_with_valid_config() {
let client = UspsClientBuilder::new()
.credentials("test_id", "test_secret")
.environment(UspsEnvironment::Sandbox)
.timeout(Duration::from_secs(15))
.build()
.unwrap();
assert_eq!(client.config().client_id, "test_id");
assert_eq!(client.config().timeout, Duration::from_secs(15));
assert_eq!(client.config().environment, UspsEnvironment::Sandbox);
}
#[test]
fn builder_should_fail_when_credentials_missing() {
let err = UspsClientBuilder::new().build().unwrap_err();
assert!(matches!(err, UspsError::InvalidInput(_)));
}
}