use crate::error::{ApiErrorBody, BachsError, BachsResult};
use reqwest::{header, Method, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
Sandbox,
Production,
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,
}
}
fn from_api_key(api_key: &str) -> Self {
if api_key.starts_with("sk_sandbox_") {
Environment::Sandbox
} else {
Environment::Production
}
}
}
#[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
}
}
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")),
}
}
pub fn environment(mut self, environment: Environment) -> Self {
self.environment = Some(environment);
self
}
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(),
})
}
}
#[derive(Clone)]
pub struct Bachs {
pub(crate) http: reqwest::Client,
pub(crate) base_url: String,
}
impl Bachs {
pub fn new(api_key: impl Into<String>) -> BachsResult<Self> {
Self::builder(api_key).build()
}
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);
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:?}"),
}
}
}