atp-client 0.1.0

Framework-neutral ATP billing SDK with optional Axum routes, guards, caching, and JWT claims enrichment
Documentation
use crate::config::AtpClientConfig;
use crate::{
    ApiErrorBody, AtpClientBuilder, Balance, BillingSnapshot, BillingStatus, CheckoutRequest,
    CheckoutResponse, DebitRequest, DebitResult, LedgerEntry, PortalResponse, RefundRequest,
    SdkError, SdkResult, SnapshotSource,
};
use async_trait::async_trait;
use reqwest::{Method, StatusCode};
use secrecy::{ExposeSecret, SecretString};
use serde::{Serialize, de::DeserializeOwned};
use std::{sync::Arc, time::Duration};
use tokio::time::sleep;
use url::Url;

#[async_trait]
/// Framework-neutral source of a per-user billing snapshot.
///
/// Implement this trait to supply test doubles or an application-specific cache.
pub trait BillingProvider: Send + Sync {
    /// Loads the current billing snapshot for a tenant-scoped user identifier.
    async fn billing_snapshot(&self, user_id: &str) -> SdkResult<BillingSnapshot>;
}

#[derive(Clone)]
/// Cloneable, async client for ATP's tenant-facing HTTP API.
///
/// The API key remains server-side and is redacted by [`SecretString`]. Only GET
/// requests are retried automatically; writes require caller-controlled retries
/// with a stable idempotency key.
pub struct AtpClient {
    http: reqwest::Client,
    base_url: Url,
    api_key: Arc<SecretString>,
    read_retries: u8,
}

impl AtpClient {
    /// Starts a configurable client builder.
    pub fn builder(base_url: impl Into<String>, api_key: SecretString) -> AtpClientBuilder {
        AtpClientBuilder::new(base_url, api_key)
    }

    /// Creates a client with production-safe timeouts, HTTPS, and one GET retry.
    pub fn new(base_url: impl Into<String>, api_key: SecretString) -> SdkResult<Self> {
        Self::builder(base_url, api_key).build()
    }

    pub(crate) fn from_config(config: AtpClientConfig) -> SdkResult<Self> {
        let http = reqwest::Client::builder()
            .connect_timeout(config.connect_timeout)
            .timeout(config.request_timeout)
            .user_agent(config.user_agent)
            .build()
            .map_err(|error| SdkError::Config(error.to_string()))?;
        Ok(Self {
            http,
            base_url: config.base_url,
            api_key: Arc::new(config.api_key),
            read_retries: config.read_retries,
        })
    }

    /// Loads the user's three credit buckets and optimistic-concurrency version.
    pub async fn balance(&self, user_id: &str) -> SdkResult<Balance> {
        self.get(self.user_url(user_id, "balance")?).await
    }
    /// Loads tier, subscription status, and balance in one request.
    pub async fn status(&self, user_id: &str) -> SdkResult<BillingStatus> {
        self.get(self.user_url(user_id, "status")?).await
    }
    /// Lists the user's most recent ledger entries using ATP's default page size.
    pub async fn ledger(&self, user_id: &str) -> SdkResult<Vec<LedgerEntry>> {
        #[derive(serde::Deserialize)]
        struct Page {
            items: Vec<LedgerEntry>,
        }
        Ok(self
            .get::<Page>(self.user_url(user_id, "ledger")?)
            .await?
            .items)
    }
    /// Atomically consumes credits in subscription → purchased → team-pool order.
    ///
    /// Reuse the same `idempotency_key` when retrying the same business operation.
    pub async fn debit(
        &self,
        request: &DebitRequest,
        idempotency_key: &str,
    ) -> SdkResult<DebitResult> {
        validate_idempotency_key(idempotency_key)?;
        self.post(
            self.endpoint(&["api", "v1", "credits", "debit"])?,
            request,
            Some(idempotency_key),
        )
        .await
    }
    /// Refunds a completed debit back to its original credit buckets.
    ///
    /// `request.debit_tx_id` identifies the debit; the refund also needs its own
    /// stable idempotency key.
    pub async fn refund(
        &self,
        request: &RefundRequest,
        idempotency_key: &str,
    ) -> SdkResult<DebitResult> {
        validate_idempotency_key(idempotency_key)?;
        self.post(
            self.endpoint(&["api", "v1", "credits", "refund"])?,
            request,
            Some(idempotency_key),
        )
        .await
    }
    /// Creates a Stripe Checkout session for a subscription or credit pack.
    pub async fn checkout(
        &self,
        request: &CheckoutRequest,
        idempotency_key: &str,
    ) -> SdkResult<CheckoutResponse> {
        validate_idempotency_key(idempotency_key)?;
        self.post(
            self.endpoint(&["api", "v1", "checkout", "sessions"])?,
            request,
            Some(idempotency_key),
        )
        .await
    }
    /// Creates a Stripe Customer Portal session and returns its redirect URL.
    pub async fn portal(&self, email: &str, return_url: &str) -> SdkResult<String> {
        #[derive(Serialize)]
        struct Body<'a> {
            email: &'a str,
            return_url: &'a str,
        }
        Ok(self
            .post::<_, PortalResponse>(
                self.endpoint(&["api", "v1", "portal", "sessions"])?,
                &Body { email, return_url },
                None,
            )
            .await?
            .portal_url)
    }

    fn user_url(&self, user_id: &str, resource: &str) -> SdkResult<Url> {
        if user_id.is_empty() || user_id.len() > 200 {
            return Err(SdkError::Config(
                "user_id must contain 1..=200 characters".into(),
            ));
        }
        self.endpoint(&["api", "v1", "users", user_id, resource])
    }
    fn endpoint(&self, segments: &[&str]) -> SdkResult<Url> {
        let mut url = self.base_url.clone();
        url.path_segments_mut()
            .map_err(|_| SdkError::Config("base URL cannot be a base".into()))?
            .pop_if_empty()
            .extend(segments);
        Ok(url)
    }
    async fn get<T: DeserializeOwned>(&self, url: Url) -> SdkResult<T> {
        self.request::<(), T>(Method::GET, url, None, None, self.read_retries)
            .await
    }
    async fn post<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        url: Url,
        body: &B,
        idempotency: Option<&str>,
    ) -> SdkResult<T> {
        self.request(Method::POST, url, Some(body), idempotency, 0)
            .await
    }
    async fn request<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        method: Method,
        url: Url,
        body: Option<&B>,
        idempotency: Option<&str>,
        retries: u8,
    ) -> SdkResult<T> {
        let mut attempt = 0_u8;
        loop {
            let mut request = self
                .http
                .request(method.clone(), url.clone())
                .bearer_auth(self.api_key.expose_secret())
                .header("Accept", "application/json")
                .header("X-Request-ID", ulid::Ulid::new().to_string());
            if let Some(value) = body {
                request = request.json(value);
            }
            if let Some(key) = idempotency {
                request = request.header("Idempotency-Key", key);
            }
            let response = request.send().await;
            let result = match response {
                Ok(response) => self.decode(response).await,
                Err(error) if error.is_timeout() => Err(SdkError::Timeout),
                Err(error) => Err(SdkError::Transport(error.to_string())),
            };
            if attempt >= retries || !result.as_ref().err().is_some_and(SdkError::is_retryable) {
                return result;
            }
            attempt += 1;
            sleep(Duration::from_millis(25 * 4_u64.pow((attempt - 1) as u32))).await;
        }
    }
    async fn decode<T: DeserializeOwned>(&self, response: reqwest::Response) -> SdkResult<T> {
        let status = response.status();
        if status.is_success() {
            return response
                .json()
                .await
                .map_err(|error| SdkError::Decode(error.to_string()));
        }
        let retry_after_seconds = response
            .headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok());
        let body = response.json::<ApiErrorBody>().await.ok();
        let code = body
            .as_ref()
            .map(|v| v.error.code.clone())
            .unwrap_or_else(|| "unknown_error".into());
        match (status, code.as_str()) {
            (StatusCode::UNAUTHORIZED, _) | (StatusCode::FORBIDDEN, _) => {
                Err(SdkError::Unauthorized)
            }
            (StatusCode::NOT_FOUND, _) => Err(SdkError::NotFound),
            (StatusCode::CONFLICT, "insufficient_credits") => Err(SdkError::InsufficientCredits),
            (StatusCode::CONFLICT, _) => Err(SdkError::Conflict),
            (StatusCode::TOO_MANY_REQUESTS, _) => Err(SdkError::RateLimited {
                retry_after_seconds,
            }),
            _ => {
                let detail = body.map(|v| v.error);
                Err(SdkError::Api {
                    status: status.as_u16(),
                    code: detail.as_ref().map(|v| v.code.clone()).unwrap_or(code),
                    message: detail
                        .as_ref()
                        .map(|v| v.message.clone())
                        .unwrap_or_else(|| status.to_string()),
                    request_id: detail.map(|v| v.request_id).unwrap_or_default(),
                })
            }
        }
    }
}

fn validate_idempotency_key(value: &str) -> SdkResult<()> {
    if value.len() < 8 || value.len() > 128 || !value.is_ascii() {
        return Err(SdkError::Config(
            "Idempotency-Key must contain 8..=128 ASCII characters".into(),
        ));
    }
    Ok(())
}

#[cfg(all(test, feature = "axum"))]
mod tests {
    use super::*;
    use axum::{
        Json, Router,
        http::StatusCode,
        routing::{get, post},
    };

    async fn test_client() -> AtpClient {
        let app = Router::new()
            .route("/api/v1/users/{user}/status", get(|| async {
                Json(serde_json::from_str::<serde_json::Value>(include_str!("../../../sdk-conformance/billing-status.json")).unwrap())
            }))
            .route("/api/v1/credits/debit", post(|| async {
                (StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"insufficient_credits","message":"no credits","request_id":"req-1"}})))
            }));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        AtpClient::builder(
            format!("http://{address}"),
            SecretString::from(format!("atp_{}", "a".repeat(64))),
        )
        .allow_insecure_http(true)
        .build()
        .unwrap()
    }

    #[tokio::test]
    async fn decodes_forward_compatible_status() {
        let status = test_client().await.status("usr_1").await.unwrap();
        assert_eq!(status.tier, "pro");
    }

    #[tokio::test]
    async fn maps_stable_error_codes() {
        let request = DebitRequest {
            user_id: "usr_1".into(),
            amount: 1,
            related_id: "job_1".into(),
            description: None,
        };
        let error = test_client()
            .await
            .debit(&request, "job-0001")
            .await
            .unwrap_err();
        assert!(matches!(error, SdkError::InsufficientCredits));
    }
}

#[async_trait]
impl BillingProvider for AtpClient {
    async fn billing_snapshot(&self, user_id: &str) -> SdkResult<BillingSnapshot> {
        Ok(BillingSnapshot {
            status: self.status(user_id).await?,
            source: SnapshotSource::Fresh,
            degraded: false,
        })
    }
}