atp-client 0.1.0

Framework-neutral ATP billing SDK with optional Axum routes, guards, caching, and JWT claims enrichment
Documentation
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
/// Current balances for a user, including an optional team contribution.
pub struct Balance {
    /// ATP tenant/application identifier.
    pub app_id: String,
    /// Tenant-scoped external user identifier.
    pub user_id: String,
    /// Credits granted by the current subscription period.
    pub subscription: u32,
    /// Non-expiring credits purchased separately.
    pub purchased: u32,
    /// Active team whose shared pool is available to the user.
    pub team_id: Option<String>,
    #[serde(default)]
    /// Credits currently available from the active team pool.
    pub team_pool: u32,
    /// Optimistic-concurrency version of the balance snapshot.
    pub version: u64,
}

impl Balance {
    /// Returns all immediately spendable credit buckets as a widened integer.
    pub fn total(&self) -> u64 {
        self.subscription as u64 + self.purchased as u64 + self.team_pool as u64
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
/// Entitlement and balance facts returned by the consolidated status endpoint.
pub struct BillingStatus {
    /// ATP tenant/application identifier.
    pub app_id: String,
    /// Tenant-scoped external user identifier.
    pub user_id: String,
    /// Product tier configured by the ATP tenant.
    pub tier: String,
    /// Subscription lifecycle state, such as `active` or `canceled`.
    pub subscription_status: String,
    /// Current credit-bucket snapshot.
    pub balance: Balance,
}

impl BillingStatus {
    /// Builds a zero-credit Free status for an explicitly configured login fallback.
    pub fn free_fallback(user_id: impl Into<String>) -> Self {
        let user_id = user_id.into();
        Self {
            app_id: String::new(),
            user_id: user_id.clone(),
            tier: "free".into(),
            subscription_status: "degraded".into(),
            balance: Balance {
                user_id,
                ..Balance::default()
            },
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Immutable ledger fact describing one balance change.
pub struct LedgerEntry {
    /// Stable ATP transaction identifier.
    pub tx_id: String,
    /// ATP tenant/application identifier.
    pub app_id: String,
    /// User or team whose ledger owns this entry.
    pub owner_id: String,
    /// Transaction kind, such as debit, refund, grant, or adjustment.
    pub tx_type: String,
    /// Signed total change represented by this entry.
    pub amount: i32,
    /// Signed portion applied to subscription credits.
    pub from_subscription: i32,
    /// Signed portion applied to purchased credits.
    pub from_purchased: i32,
    /// Signed portion applied to the team pool.
    pub from_team_pool: i32,
    /// Tenant-supplied business operation identifier, when present.
    pub related_id: Option<String>,
    /// Human-readable audit description.
    pub description: String,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Request to atomically consume credits for a business operation.
pub struct DebitRequest {
    /// Tenant-scoped user that owns or can access the credit buckets.
    pub user_id: String,
    /// Positive integer number of credits to consume.
    pub amount: u32,
    /// Stable business identifier used for tracing the charged work.
    pub related_id: String,
    /// Optional audit-safe description; do not include sensitive payloads.
    pub description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
/// Result of a debit or refund, broken down by original credit source.
pub struct DebitResult {
    /// Stable ATP transaction identifier.
    pub tx_id: String,
    /// Total number of credits affected.
    pub amount: u32,
    /// Portion taken from or restored to subscription credits.
    pub from_subscription: u32,
    /// Portion taken from or restored to purchased credits.
    pub from_purchased: u32,
    /// Portion taken from or restored to the team pool.
    pub from_team_pool: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Request to reverse one previously completed debit.
pub struct RefundRequest {
    /// Tenant-scoped user associated with the original debit.
    pub user_id: String,
    /// ATP transaction identifier returned by the original debit.
    pub debit_tx_id: String,
    /// Audit reason for the compensation.
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
/// Product a user intends to buy through Stripe Checkout.
pub enum Purchase {
    /// Recurring subscription for a configured tier.
    Subscription {
        /// Tenant-defined tier identifier.
        tier: String,
    },
    /// One-time purchase of a configured credit pack.
    CreditPack {
        /// Tenant-defined credit-pack identifier.
        pack_id: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Server-to-server Checkout request including authenticated user identity.
pub struct CheckoutRequest {
    /// Tenant-scoped user purchasing the product.
    pub user_id: String,
    /// Customer email used for Stripe customer lookup or creation.
    pub email: String,
    /// Subscription tier or credit pack to purchase.
    pub purchase: Purchase,
    /// Allowlisted URL used after successful Checkout.
    pub success_url: String,
    /// Allowlisted URL used when Checkout is canceled.
    pub cancel_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Browser-safe Checkout input for [`crate::BillingRouter`].
///
/// Identity is intentionally absent and is derived from the authenticated Principal.
pub struct CheckoutInput {
    /// Subscription tier or credit pack to purchase.
    pub purchase: Purchase,
    /// Allowlisted URL used after successful Checkout.
    pub success_url: String,
    /// Allowlisted URL used when Checkout is canceled.
    pub cancel_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Newly created Stripe Checkout session.
pub struct CheckoutResponse {
    /// Stripe Checkout Session identifier.
    pub session_id: String,
    /// Short-lived URL to which the browser should be redirected.
    pub checkout_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Browser-safe Customer Portal input for [`crate::BillingRouter`].
pub struct PortalInput {
    /// Allowlisted URL to which Stripe returns the customer.
    pub return_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Newly created Stripe Customer Portal session.
pub struct PortalResponse {
    /// Short-lived URL to which the browser should be redirected.
    pub portal_url: String,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
/// Provenance of the status held by a [`BillingSnapshot`].
pub enum SnapshotSource {
    /// Loaded from ATP during this request.
    Fresh,
    /// Served within the configured fresh TTL.
    Cache,
    /// Served after fresh expiry because ATP was unavailable.
    Stale,
    /// Synthetic zero-credit Free state used for login continuity.
    FreeFallback,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Billing status plus cache/fallback provenance needed for safe decisions.
pub struct BillingSnapshot {
    /// Entitlement and credit facts.
    pub status: BillingStatus,
    /// Where this snapshot came from.
    pub source: SnapshotSource,
    /// True when the snapshot was returned under an outage fallback policy.
    pub degraded: bool,
}

#[derive(Debug, Clone)]
/// Ordered tier hierarchy used by Axum's minimum-tier guard.
pub struct TierPolicy {
    order: Vec<String>,
}

impl TierPolicy {
    /// Creates a policy ordered from least to most privileged.
    pub fn new(order: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            order: order.into_iter().map(Into::into).collect(),
        }
    }

    /// Returns whether `actual` is at least as privileged as `required`.
    ///
    /// Unknown tiers fail closed.
    pub fn allows(&self, actual: &str, required: &str) -> bool {
        let rank = |tier: &str| self.order.iter().position(|value| value == tier);
        matches!((rank(actual), rank(required)), (Some(actual), Some(required)) if actual >= required)
    }
}

impl Default for TierPolicy {
    fn default() -> Self {
        Self::new(["free", "pro", "team"])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_tier_policy_is_monotonic() {
        let policy = TierPolicy::default();
        assert!(policy.allows("team", "pro"));
        assert!(policy.allows("pro", "pro"));
        assert!(!policy.allows("free", "pro"));
        assert!(!policy.allows("unknown", "free"));
    }

    #[test]
    fn cross_language_status_fixture_is_forward_compatible() {
        let status: BillingStatus =
            serde_json::from_str(include_str!("../../../sdk-conformance/billing-status.json"))
                .unwrap();
        assert_eq!(status.tier, "pro");
        assert_eq!(status.balance.total(), 160);
    }
}