use std::sync::Arc;
use std::time::{Duration, Instant};
use reqwest::Client as HttpClient;
use serde::Deserialize;
use tokio::sync::RwLock;
use tracing::{debug, info, instrument};
use super::config::UspsConfig;
use super::error::{Result, UspsError};
const EXPIRATION_BUFFER_SECS: u64 = 60;
#[derive(Debug, Deserialize)]
pub struct OAuthTokenResponse {
pub access_token: String,
pub token_type: Option<String>,
pub expires_in: Option<i64>,
pub status: Option<String>,
}
#[derive(Debug, Clone)]
struct CachedToken {
access_token: String,
expires_at: Instant,
}
impl CachedToken {
fn is_valid(&self) -> bool {
Instant::now() < self.expires_at
}
}
#[derive(Debug, Clone)]
pub struct TokenManager {
config: UspsConfig,
http_client: HttpClient,
cached_token: Arc<RwLock<Option<CachedToken>>>,
}
impl TokenManager {
#[must_use]
pub fn new(config: UspsConfig, http_client: HttpClient) -> Self {
Self {
config,
http_client,
cached_token: Arc::new(RwLock::new(None)),
}
}
#[instrument(skip(self), name = "usps_get_token")]
pub async fn get_token(&self) -> Result<String> {
{
let read_guard = self.cached_token.read().await;
if let Some(ref cached) = *read_guard {
if cached.is_valid() {
debug!("Reutilizando token OAuth 2.0 en caché");
return Ok(cached.access_token.clone());
}
}
}
let mut write_guard = self.cached_token.write().await;
if let Some(ref cached) = *write_guard {
if cached.is_valid() {
debug!("Token ya renovado concurrentemente por otra tarea");
return Ok(cached.access_token.clone());
}
}
info!("Renovando token OAuth 2.0 con USPS");
let token_resp = self.fetch_new_token().await?;
let expires_in = token_resp.expires_in.unwrap_or(3600).max(0) as u64;
let usable_duration = if expires_in > EXPIRATION_BUFFER_SECS {
Duration::from_secs(expires_in - EXPIRATION_BUFFER_SECS)
} else {
Duration::from_secs(expires_in)
};
let cached = CachedToken {
access_token: token_resp.access_token.clone(),
expires_at: Instant::now() + usable_duration,
};
*write_guard = Some(cached);
Ok(token_resp.access_token)
}
async fn fetch_new_token(&self) -> Result<OAuthTokenResponse> {
let token_url = format!("{}/oauth2/v3/token", self.config.environment.base_url());
let form_params = [
("grant_type", "client_credentials"),
("client_id", &self.config.client_id),
("client_secret", &self.config.client_secret),
];
let response = self
.http_client
.post(&token_url)
.form(&form_params)
.send()
.await?;
let status = response.status();
let body = response.text().await?;
if !status.is_success() {
return Err(UspsError::from_response(status, &body));
}
let token_response: OAuthTokenResponse = serde_json::from_str(&body).map_err(|err| {
UspsError::Auth(format!("Error al deserializar respuesta OAuth: {err}"))
})?;
Ok(token_response)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cached_token_validity_check() {
let token = CachedToken {
access_token: "test_token".to_string(),
expires_at: Instant::now() + Duration::from_secs(10),
};
assert!(token.is_valid());
let expired = CachedToken {
access_token: "test_token".to_string(),
expires_at: Instant::now() - Duration::from_secs(1),
};
assert!(!expired.is_valid());
}
}