3.7 KiB · text History 0297141
use uuid::Uuid;

use crate::{ApiError, Error, MessageInfo, MessageReceipt, SendRequest, SyncReport, SyncTemplates};

/// Async client for one application's API key. Cheap to clone — the inner
/// `reqwest::Client` is reference-counted, so hold one and clone it around.
#[derive(Clone)]
pub struct Client {
    base_url: String,
    api_key: String,
    http: reqwest::Client,
}

impl std::fmt::Debug for Client {
    // Hand-written so the API key never lands in a log via `{:?}`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client").field("base_url", &self.base_url).finish_non_exhaustive()
    }
}

impl Client {
    pub fn new(base_url: impl Into<String>, api_key: impl Into<String>) -> Result<Self, Error> {
        let http = reqwest::Client::builder()
            .user_agent(concat!("mail-prism-client/", env!("CARGO_PKG_VERSION")))
            .timeout(std::time::Duration::from_secs(15))
            .build()?;
        Ok(Self::with_http(base_url, api_key, http))
    }

    /// Use a caller-built `reqwest::Client` (custom timeouts, proxies, …).
    pub fn with_http(base_url: impl Into<String>, api_key: impl Into<String>, http: reqwest::Client) -> Self {
        Self {
            base_url: base_url.into().trim_end_matches('/').to_string(),
            api_key: api_key.into(),
            http,
        }
    }

    /// Build from `MAIL_PRISM_URL` and `MAIL_PRISM_API_KEY`.
    pub fn from_env() -> Result<Self, Error> {
        let var = |k: &str| {
            std::env::var(k)
                .ok()
                .filter(|v| !v.trim().is_empty())
                .ok_or_else(|| Error::Config(format!("{k} is not set")))
        };
        Self::new(var("MAIL_PRISM_URL")?, var("MAIL_PRISM_API_KEY")?)
    }

    /// Queue a message. Returns once mail-prism has rendered and stored it;
    /// delivery happens asynchronously — poll [`Client::message`] if you care.
    pub async fn send(&self, request: &SendRequest) -> Result<MessageReceipt, Error> {
        let resp = self
            .http
            .post(format!("{}/api/v1/messages", self.base_url))
            .bearer_auth(&self.api_key)
            .json(request)
            .send()
            .await?;
        decode(resp).await
    }

    /// Current status of a message this application sent.
    pub async fn message(&self, id: Uuid) -> Result<MessageInfo, Error> {
        let resp = self
            .http
            .get(format!("{}/api/v1/messages/{id}", self.base_url))
            .bearer_auth(&self.api_key)
            .send()
            .await?;
        decode(resp).await
    }
}

impl Client {
    /// Replace this application's synced templates (see [`SyncTemplates`]).
    /// Run it at deploy or startup, before the first send that names one.
    pub async fn sync_templates(&self, request: &SyncTemplates) -> Result<SyncReport, Error> {
        let resp = self
            .http
            .put(format!("{}/api/v1/templates", self.base_url))
            .bearer_auth(&self.api_key)
            .json(request)
            .send()
            .await?;
        decode(resp).await
    }
}

async fn decode<T: serde::de::DeserializeOwned>(resp: reqwest::Response) -> Result<T, Error> {
    let status = resp.status();
    if status.is_success() {
        return Ok(resp.json().await?);
    }
    // A proxy in front of mail-prism may answer with HTML; keep the status
    // and say so rather than failing on the JSON decode.
    let body = resp.text().await.unwrap_or_default();
    let ApiError { error, detail } = serde_json::from_str(&body).unwrap_or(ApiError {
        error: "unexpected_response".into(),
        detail: Some(body.chars().take(200).collect()),
    });
    Err(Error::Api { status: status.as_u16(), error, detail })
}