bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use crate::error::{ApiErrorBody, BachsError, BachsResult};
use reqwest::{header, Method, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::time::Duration;

/// Which Bachs deployment to talk to.
///
/// Per the docs: sandbox and production are entirely separate hosts and key
/// prefixes (`sk_sandbox_...` / `sk_live_...`) — going live is a key swap,
/// not a config flag on the same host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
    Sandbox,
    Production,
    /// Point the client at a custom base URL — useful for testing against a
    /// local mock server (e.g. with `wiremock`).
    Custom(String),
}

impl Environment {
    pub fn base_url(&self) -> &str {
        match self {
            Environment::Sandbox => "https://sandbox-api.bachs.io",
            Environment::Production => "https://api.bachs.io",
            Environment::Custom(url) => url,
        }
    }

    /// Guess the environment from an API key's prefix. Falls back to
    /// `Production` for keys that don't match a known sandbox prefix, since
    /// that's the safer default to surface auth errors against rather than
    /// silently pointing live-looking traffic elsewhere.
    fn from_api_key(api_key: &str) -> Self {
        if api_key.starts_with("sk_sandbox_") {
            Environment::Sandbox
        } else {
            Environment::Production
        }
    }
}

/// Per-request options: currently just the idempotency key.
///
/// ```no_run
/// # use bachs_sdk::RequestOptions;
/// let opts = RequestOptions::new().idempotency_key("retry-1234");
/// ```
#[derive(Debug, Clone, Default)]
pub struct RequestOptions {
    pub idempotency_key: Option<String>,
}

impl RequestOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }
}

/// Builder for [`Bachs`].
pub struct BachsBuilder {
    api_key: String,
    environment: Option<Environment>,
    timeout: Duration,
    user_agent: String,
}

impl BachsBuilder {
    fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            environment: None,
            timeout: Duration::from_secs(30),
            user_agent: format!("bachs-sdk-rust/{}", env!("CARGO_PKG_VERSION")),
        }
    }

    /// Explicitly set the environment instead of inferring it from the key prefix.
    pub fn environment(mut self, environment: Environment) -> Self {
        self.environment = Some(environment);
        self
    }

    /// Point requests at a custom base URL (e.g. a local mock server in tests).
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.environment = Some(Environment::Custom(base_url.into()));
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    pub fn build(self) -> BachsResult<Bachs> {
        let environment = self
            .environment
            .unwrap_or_else(|| Environment::from_api_key(&self.api_key));

        let mut headers = header::HeaderMap::new();
        let mut auth_value = header::HeaderValue::from_str(&format!("Bearer {}", self.api_key))
            .map_err(|e| BachsError::InvalidRequest(format!("invalid API key: {e}")))?;
        auth_value.set_sensitive(true);
        headers.insert(header::AUTHORIZATION, auth_value);
        headers.insert(
            header::ACCEPT,
            header::HeaderValue::from_static("application/json"),
        );

        let http = reqwest::Client::builder()
            .timeout(self.timeout)
            .user_agent(self.user_agent)
            .default_headers(headers)
            .build()?;

        Ok(Bachs {
            http,
            base_url: environment.base_url().to_string(),
        })
    }
}

/// The Bachs API client.
///
/// ```no_run
/// use bachs_sdk::Bachs;
///
/// # async fn run() -> Result<(), bachs_sdk::BachsError> {
/// let bachs = Bachs::new(std::env::var("BACHS_API_KEY").unwrap())?;
/// let customer = bachs
///     .customers()
///     .get("cust_1a2b3c4d5e6f")
///     .await?;
/// println!("{}", customer.email);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Bachs {
    pub(crate) http: reqwest::Client,
    pub(crate) base_url: String,
}

impl Bachs {
    /// Create a client, inferring sandbox vs. production from the key prefix.
    pub fn new(api_key: impl Into<String>) -> BachsResult<Self> {
        Self::builder(api_key).build()
    }

    /// Start building a client with custom options (environment, timeout, ...).
    pub fn builder(api_key: impl Into<String>) -> BachsBuilder {
        BachsBuilder::new(api_key)
    }

    pub(crate) async fn send<B: Serialize, R: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
        query: Option<&[(&str, String)]>,
        options: Option<&RequestOptions>,
    ) -> BachsResult<R> {
        let url = format!("{}{}", self.base_url, path);
        let mut req = self.http.request(method, url);

        if let Some(q) = query {
            req = req.query(q);
        }
        if let Some(b) = body {
            req = req.json(b);
        }
        if let Some(opts) = options {
            if let Some(key) = &opts.idempotency_key {
                req = req.header("Idempotency-Key", key);
            }
        }

        let resp = req.send().await?;
        Self::handle_response(resp).await
    }

    pub(crate) async fn send_multipart<R: DeserializeOwned>(
        &self,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> BachsResult<R> {
        let url = format!("{}{}", self.base_url, path);
        // multipart() sets its own Content-Type (with boundary), overriding
        // the client's default `application/json` header for this request.
        let resp = self.http.post(url).multipart(form).send().await?;
        Self::handle_response(resp).await
    }

    async fn handle_response<R: DeserializeOwned>(resp: reqwest::Response) -> BachsResult<R> {
        let status = resp.status();
        let rate_limit_reset = resp
            .headers()
            .get("X-RateLimit-Reset")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<i64>().ok());

        if status.is_success() {
            if status == StatusCode::NO_CONTENT {
                let empty = serde_json::from_value(serde_json::Value::Null)
                    .or_else(|_| serde_json::from_str::<R>("null"));
                return empty.map_err(BachsError::from);
            }
            let bytes = resp.bytes().await?;
            if bytes.is_empty() {
                return serde_json::from_str::<R>("null").map_err(BachsError::from);
            }
            serde_json::from_slice(&bytes).map_err(BachsError::from)
        } else {
            let raw_body = resp.text().await.unwrap_or_default();
            match serde_json::from_str::<ApiErrorBody>(&raw_body) {
                Ok(body) => Err(BachsError::Api {
                    status: status.as_u16(),
                    body,
                    rate_limit_reset,
                }),
                Err(_) => Err(BachsError::ApiUnparsed {
                    status: status.as_u16(),
                    raw_body,
                }),
            }
        }
    }
}

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

    #[test]
    fn sandbox_key_infers_sandbox() {
        assert_eq!(
            Environment::from_api_key("sk_sandbox_test123"),
            Environment::Sandbox
        );
    }

    #[test]
    fn live_key_infers_production() {
        assert_eq!(
            Environment::from_api_key("sk_live_test123"),
            Environment::Production
        );
    }

    #[test]
    fn unknown_key_falls_back_to_production() {
        assert_eq!(
            Environment::from_api_key("sk_other_test123"),
            Environment::Production
        );
    }

    #[test]
    fn custom_environment_base_url() {
        let env = Environment::Custom("http://localhost:8080".to_string());
        assert_eq!(env.base_url(), "http://localhost:8080");
    }

    #[test]
    fn sandbox_base_url() {
        assert_eq!(Environment::Sandbox.base_url(), "https://sandbox-api.bachs.io");
    }

    #[test]
    fn production_base_url() {
        assert_eq!(Environment::Production.base_url(), "https://api.bachs.io");
    }

    #[test]
    fn request_options_default() {
        let opts = RequestOptions::new();
        assert!(opts.idempotency_key.is_none());
    }

    #[test]
    fn request_options_with_idempotency_key() {
        let opts = RequestOptions::new().idempotency_key("key-123");
        assert_eq!(opts.idempotency_key.as_deref(), Some("key-123"));
    }

    #[test]
    fn builder_defaults() {
        let client = BachsBuilder::new("sk_sandbox_test").build().unwrap();
        assert_eq!(client.base_url, "https://sandbox-api.bachs.io");
    }

    #[test]
    fn builder_explicit_environment() {
        let client = BachsBuilder::new("sk_sandbox_test")
            .environment(Environment::Production)
            .build()
            .unwrap();
        assert_eq!(client.base_url, "https://api.bachs.io");
    }

    #[test]
    fn builder_custom_base_url() {
        let client = BachsBuilder::new("sk_sandbox_test")
            .base_url("http://localhost:3000")
            .build()
            .unwrap();
        assert_eq!(client.base_url, "http://localhost:3000");
    }

    #[test]
    fn builder_rejects_invalid_api_key_header() {
        let err = BachsBuilder::new("\x00invalid").build().unwrap_err();
        match err {
            BachsError::InvalidRequest(_) => {}
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}