mailman 0.2.0

SDK for mailman, a microservice that sends emails on your behalf over SMTP.
Documentation
use std::env;
use std::sync::OnceLock;

use reqwest::{IntoUrl, Url};

use crate::{Error, SendEmailRequest, SendEmailResponse};

/// HTTP client for a mailman server.
///
/// Carries the bearer token mailman requires on `POST /send`, so a single
/// client can be cloned and shared across your application.
#[derive(Debug, Clone)]
pub struct Client {
    http: reqwest::Client,
    base_url: Url,
    token: String,
}

impl Client {
    /// Construct a client pointed at `base_url` (e.g. `https://mailman.example.com`)
    /// using `token` as the `Authorization: Bearer` secret.
    pub fn new<U: IntoUrl>(base_url: U, token: impl Into<String>) -> Result<Self, Error> {
        Self::with_http(reqwest::Client::new(), base_url, token)
    }

    /// Construct a client using a caller-supplied `reqwest::Client` (so you can
    /// share connection pools, set timeouts, install middleware, etc.).
    pub fn with_http<U: IntoUrl>(
        http: reqwest::Client,
        base_url: U,
        token: impl Into<String>,
    ) -> Result<Self, Error> {
        let base_url = base_url
            .into_url()
            .map_err(|e| Error::InvalidUrl(e.to_string()))?;
        Ok(Self {
            http,
            base_url,
            token: token.into(),
        })
    }

    /// Base URL the client points at.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Send an email by calling `POST {base}/send`.
    pub async fn send(&self, req: &SendEmailRequest) -> Result<SendEmailResponse, Error> {
        let url = format!("{}/send", self.base_url.as_str().trim_end_matches('/'));
        let resp = self
            .http
            .post(url)
            .bearer_auth(&self.token)
            .json(req)
            .send()
            .await
            .map_err(Error::Http)?;

        let status = resp.status();
        if status.is_success() {
            resp.json::<SendEmailResponse>().await.map_err(Error::Http)
        } else {
            let body = resp.text().await.unwrap_or_default();
            Err(Error::Status {
                status: status.as_u16(),
                message: extract_error_message(&body),
            })
        }
    }
}

/// The mailman server's error responses look like `{"error":"..."}`. Pull the
/// inner string out when present; otherwise return the body verbatim.
fn extract_error_message(body: &str) -> String {
    serde_json::from_str::<crate::ErrorResponse>(body)
        .map(|b| b.error)
        .unwrap_or_else(|_| body.to_string())
}

static GLOBAL: OnceLock<Client> = OnceLock::new();

/// Configure the process-global client with an explicit URL and token. The
/// first successful call wins; subsequent calls are no-ops.
pub fn setup<U: IntoUrl>(base_url: U, token: impl Into<String>) -> Result<(), Error> {
    let client = Client::new(base_url, token)?;
    let _ = GLOBAL.set(client);
    Ok(())
}

/// Configure the process-global client by reading `MAILMAN_URL` and
/// `MAILMAN_API_TOKEN`.
pub fn from_env() -> Result<(), Error> {
    let url = env::var("MAILMAN_URL").map_err(|_| Error::NotConfigured)?;
    let token = env::var("MAILMAN_API_TOKEN").map_err(|_| Error::NotConfigured)?;
    setup(url, token)
}

/// The configured base URL, if [`setup`] or [`from_env`] has run.
pub fn configured_url() -> Option<&'static Url> {
    GLOBAL.get().map(|c| c.base_url())
}

/// Send an email via the process-global client. Lazily initializes from
/// `MAILMAN_URL` / `MAILMAN_API_TOKEN` on first call if not already
/// configured.
pub async fn send(req: &SendEmailRequest) -> Result<SendEmailResponse, Error> {
    let client = match GLOBAL.get() {
        Some(c) => c,
        None => {
            from_env()?;
            GLOBAL.get().expect("from_env set global client")
        }
    };
    client.send(req).await
}