atp-client 0.1.0

Framework-neutral ATP billing SDK with optional Axum routes, guards, caching, and JWT claims enrichment
Documentation
use crate::{AtpClient, SdkError, SdkResult};
use secrecy::{ExposeSecret, SecretString};
use std::time::Duration;
use url::Url;

#[derive(Clone)]
pub(crate) struct AtpClientConfig {
    pub(crate) base_url: Url,
    pub(crate) api_key: SecretString,
    pub(crate) request_timeout: Duration,
    pub(crate) connect_timeout: Duration,
    pub(crate) read_retries: u8,
    pub(crate) user_agent: String,
}

/// Builder for [`AtpClient`] transport and retry behavior.
pub struct AtpClientBuilder {
    base_url: String,
    api_key: SecretString,
    request_timeout: Duration,
    connect_timeout: Duration,
    read_retries: u8,
    user_agent: String,
    allow_insecure_http: bool,
}

impl AtpClientBuilder {
    /// Creates a builder for an ATP base URL and tenant API key.
    pub fn new(base_url: impl Into<String>, api_key: SecretString) -> Self {
        Self {
            base_url: base_url.into(),
            api_key,
            request_timeout: Duration::from_secs(3),
            connect_timeout: Duration::from_secs(1),
            read_retries: 1,
            user_agent: format!("atp-client/{}", env!("CARGO_PKG_VERSION")),
            allow_insecure_http: false,
        }
    }
    /// Sets the total timeout for one HTTP attempt. The default is three seconds.
    pub fn request_timeout(mut self, value: Duration) -> Self {
        self.request_timeout = value;
        self
    }
    /// Sets the TCP/TLS connection timeout. The default is one second.
    pub fn connect_timeout(mut self, value: Duration) -> Self {
        self.connect_timeout = value;
        self
    }
    /// Sets GET retries after the first attempt, capped at three. Writes are never retried.
    pub fn read_retries(mut self, value: u8) -> Self {
        self.read_retries = value.min(3);
        self
    }
    /// Overrides the SDK user-agent string.
    pub fn user_agent(mut self, value: impl Into<String>) -> Self {
        self.user_agent = value.into();
        self
    }
    /// Allows plain HTTP for local development and tests. Production should keep this false.
    pub fn allow_insecure_http(mut self, value: bool) -> Self {
        self.allow_insecure_http = value;
        self
    }
    /// Validates configuration and constructs the client.
    pub fn build(self) -> SdkResult<AtpClient> {
        if !self.api_key.expose_secret().starts_with("atp_")
            || self.api_key.expose_secret().len() < 36
        {
            return Err(SdkError::Config(
                "API key does not have the ATP key format".into(),
            ));
        }
        let mut base_url =
            Url::parse(&self.base_url).map_err(|error| SdkError::Config(error.to_string()))?;
        if base_url.scheme() != "https"
            && !(self.allow_insecure_http && base_url.scheme() == "http")
        {
            return Err(SdkError::Config("base URL must use HTTPS".into()));
        }
        base_url.set_query(None);
        base_url.set_fragment(None);
        if !base_url.path().ends_with('/') {
            base_url.set_path(&format!("{}/", base_url.path()));
        }
        AtpClient::from_config(AtpClientConfig {
            base_url,
            api_key: self.api_key,
            request_timeout: self.request_timeout,
            connect_timeout: self.connect_timeout,
            read_retries: self.read_retries,
            user_agent: self.user_agent,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn rejects_http_and_malformed_keys_by_default() {
        let result =
            AtpClientBuilder::new("http://localhost", SecretString::from("bad".to_owned())).build();
        assert!(matches!(result, Err(SdkError::Config(_))));
    }
}