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 crate::services::addresses::AddressesService;
use crate::services::labels::LabelsService;
use crate::services::locations::LocationsService;
use crate::services::pickup::PickupService;
use crate::services::prices::PricesService;
use crate::services::tracking::TrackingService;
#[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 token_manager(&self) -> &TokenManager {
&self.inner.token_manager
}
#[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,
{
let url = format!("{}{endpoint}", self.inner.config.environment.base_url());
let token = self.inner.token_manager.get_token().await?;
debug!("Enviando GET autenticado a {}", url);
let response = self
.inner
.http_client
.get(&url)
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/json")
.query(query)
.send()
.await?;
let status = response.status();
let body = response.text().await?;
if !status.is_success() {
return Err(UspsError::from_response(status, &body));
}
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,
{
let url = format!("{}{endpoint}", self.inner.config.environment.base_url());
let token = self.inner.token_manager.get_token().await?;
debug!("Enviando POST JSON autenticado a {}", url);
let response = self
.inner
.http_client
.post(&url)
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/json")
.json(body)
.send()
.await?;
let status = response.status();
let body = response.text().await?;
if !status.is_success() {
return Err(UspsError::from_response(status, &body));
}
serde_json::from_str::<T>(&body).map_err(UspsError::Serialization)
}
}
#[derive(Debug, Default)]
pub struct UspsClientBuilder {
client_id: Option<String>,
client_secret: Option<String>,
environment: UspsEnvironment,
timeout: Option<Duration>,
}
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
}
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);
}
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(_)));
}
}