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};
use thiserror::Error;

#[derive(Debug, Clone, Serialize, Deserialize)]
/// ATP's stable JSON error envelope.
pub struct ApiErrorBody {
    /// Structured error detail returned by ATP.
    pub error: ApiErrorDetail,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Machine-readable ATP error detail.
pub struct ApiErrorDetail {
    /// Stable application error code.
    pub code: String,
    /// Human-readable diagnostic message; do not branch on this value.
    pub message: String,
    /// Request identifier used to correlate ATP logs and support cases.
    pub request_id: String,
}

#[derive(Debug, Error)]
/// Errors produced by client configuration, transport, or the ATP API.
pub enum SdkError {
    /// Client-side configuration or input is invalid.
    #[error("invalid ATP SDK configuration: {0}")]
    Config(String),
    /// An HTTP attempt exceeded its configured deadline.
    #[error("ATP request timed out")]
    Timeout,
    /// The request failed before a usable HTTP response was received.
    #[error("ATP transport failed: {0}")]
    Transport(String),
    /// ATP returned a response that did not match the public wire contract.
    #[error("ATP response could not be decoded: {0}")]
    Decode(String),
    /// The tenant API key was missing, disabled, or invalid.
    #[error("ATP rejected credentials")]
    Unauthorized,
    /// The requested ATP resource does not exist in this tenant.
    #[error("ATP resource was not found")]
    NotFound,
    /// Available credit buckets could not cover a debit.
    #[error("insufficient credits")]
    InsufficientCredits,
    /// Current state conflicts with the requested operation.
    #[error("ATP request conflicts with current state")]
    Conflict,
    /// ATP throttled the request.
    #[error("ATP rate limit exceeded")]
    RateLimited {
        /// Parsed `Retry-After` delay when supplied by ATP.
        retry_after_seconds: Option<u64>,
    },
    /// A structured API failure without a more specific SDK variant.
    #[error("ATP API error {code}: {message} (request {request_id})")]
    Api {
        /// HTTP status code.
        status: u16,
        /// Stable ATP application error code.
        code: String,
        /// Human-readable diagnostic message.
        message: String,
        /// Server request identifier for log correlation.
        request_id: String,
    },
}

impl SdkError {
    /// Returns whether replaying this request may succeed without changing its inputs.
    ///
    /// The SDK applies this only to GET operations; callers control write retries.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Self::Timeout
                | Self::Transport(_)
                | Self::RateLimited { .. }
                | Self::Api {
                    status: 502..=504,
                    ..
                }
        )
    }
}

/// Result alias used by all SDK operations.
pub type SdkResult<T> = std::result::Result<T, SdkError>;

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn cross_language_error_fixture_decodes() {
        let value: ApiErrorBody = serde_json::from_str(include_str!(
            "../../../sdk-conformance/error-insufficient-credits.json"
        ))
        .unwrap();
        assert_eq!(value.error.code, "insufficient_credits");
    }
}