10.3 KiB · text History de2cabc
//! Client for the mail-prism send API.
//!
//! An application holds one API key, scoped to one sender address
//! (`app@domain`). It never sees SMTP credentials: it asks mail-prism to send
//! either a stored template rendered with a context, or a raw message, and
//! mail-prism renders, queues, and delivers it.
//!
//! ```no_run
//! # async fn demo() -> Result<(), mail_prism_client::Error> {
//! use mail_prism_client::{Client, SendRequest};
//! use serde_json::json;
//!
//! let client = Client::from_env()?; // MAIL_PRISM_URL + MAIL_PRISM_API_KEY
//! let receipt = client
//!     .send(
//!         &SendRequest::template("magic-link")
//!             .to("someone@example.com")
//!             .context(json!({ "url": "https://example.com/login/abc" })),
//!     )
//!     .await?;
//! println!("queued {}", receipt.id);
//! # Ok(()) }
//! ```
//!
//! With default features off this crate is only the wire types, which is how
//! the server itself uses it — so the two sides cannot drift apart.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[cfg(feature = "http")]
mod client;
#[cfg(feature = "http")]
pub use client::Client;

/// Body of `POST /api/v1/messages`.
///
/// Exactly one of `template` or `subject` must be set. A template send
/// renders the stored subject/HTML/text with `context`; a raw send carries its
/// own `subject` plus at least one of `html` / `text`. Either way, a missing
/// plain-text part is generated from the HTML.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SendRequest {
    /// Recipients, as `addr@example.com` or `Name <addr@example.com>`.
    pub to: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cc: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bcc: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<String>,
    /// Sender address. Optional, and only accepted when it equals the
    /// application's own address — it exists so a client that always sets a
    /// From (Swoosh does) gets a clear error rather than silent rewriting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Display name override for the From header.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_name: Option<String>,

    /// Stored template slug.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
    /// Template context. Rendering is strict: a variable the template uses
    /// but the context lacks is a 422, not an empty string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<serde_json::Value>,

    /// Raw-send fields.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    /// Retrying with the same key returns the original message instead of
    /// sending twice. Scoped to the application.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

impl SendRequest {
    /// Start a template send.
    pub fn template(slug: impl Into<String>) -> Self {
        Self { template: Some(slug.into()), ..Default::default() }
    }

    /// Start a raw send.
    pub fn raw(subject: impl Into<String>) -> Self {
        Self { subject: Some(subject.into()), ..Default::default() }
    }

    pub fn to(mut self, addr: impl Into<String>) -> Self {
        self.to.push(addr.into());
        self
    }
    pub fn cc(mut self, addr: impl Into<String>) -> Self {
        self.cc.push(addr.into());
        self
    }
    pub fn bcc(mut self, addr: impl Into<String>) -> Self {
        self.bcc.push(addr.into());
        self
    }
    pub fn reply_to(mut self, addr: impl Into<String>) -> Self {
        self.reply_to = Some(addr.into());
        self
    }
    pub fn from_name(mut self, name: impl Into<String>) -> Self {
        self.from_name = Some(name.into());
        self
    }
    pub fn context(mut self, ctx: serde_json::Value) -> Self {
        self.context = Some(ctx);
        self
    }
    pub fn html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }
}

/// Lifecycle of a message. `Sent` means the relay accepted it, which is not
/// the same claim as "delivered to an inbox".
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MessageStatus {
    Queued,
    Sending,
    Sent,
    Failed,
}

impl MessageStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Sending => "sending",
            Self::Sent => "sent",
            Self::Failed => "failed",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "queued" => Self::Queued,
            "sending" => Self::Sending,
            "sent" => Self::Sent,
            "failed" => Self::Failed,
            _ => return None,
        })
    }
}

/// `202` response to a send.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MessageReceipt {
    pub id: Uuid,
    pub status: MessageStatus,
    /// True when this response is a replay of an earlier send with the same
    /// idempotency key.
    #[serde(default)]
    pub duplicate: bool,
}

/// `GET /api/v1/messages/{id}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MessageInfo {
    pub id: Uuid,
    pub status: MessageStatus,
    pub attempts: i32,
    pub last_error: Option<String>,
    pub created_at: DateTime<Utc>,
    pub sent_at: Option<DateTime<Utc>>,
}

/// One template as an application ships it, for `PUT /api/v1/templates`.
///
/// Parts are minijinja: the HTML auto-escapes, subject and text don't. An
/// empty `text` means "generate it from the rendered HTML".
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct TemplateSpec {
    pub slug: String,
    /// Shown in the admin UI; defaults to the slug.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    pub subject: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub html: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub text: String,
    /// Rendered against at sync time, so it must define every variable the
    /// template uses (rendering is strict). Also the admin UI's preview.
    #[serde(default = "empty_object")]
    pub sample_context: serde_json::Value,
}

fn empty_object() -> serde_json::Value {
    serde_json::json!({})
}

/// `PUT /api/v1/templates`: make the application's synced templates exactly
/// these. All or nothing: every template is rendered against its sample
/// context first, and one failure rejects the whole set.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SyncTemplates {
    pub templates: Vec<TemplateSpec>,
    /// Delete synced templates that aren't in `templates`. Templates made in
    /// the admin UI are never deleted by a sync.
    #[serde(default)]
    pub prune: bool,
}

/// Slugs by what the sync did to them.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SyncReport {
    pub created: Vec<String>,
    pub updated: Vec<String>,
    pub unchanged: Vec<String>,
    pub deleted: Vec<String>,
}

/// Every non-2xx API response carries this body.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ApiError {
    /// Short machine-ish code, e.g. `unknown_template`, `render_failed`.
    pub error: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("mail-prism configuration: {0}")]
    Config(String),
    #[cfg(feature = "http")]
    #[error("mail-prism transport: {0}")]
    Http(#[from] reqwest::Error),
    #[error("mail-prism rejected the request ({status}): {error}{}", detail.as_deref().map(|d| format!(" — {d}")).unwrap_or_default())]
    Api { status: u16, error: String, detail: Option<String> },
}

impl Error {
    /// Whether a retry could plausibly succeed: transport failures and 5xx,
    /// but never a 4xx — those are the caller's request being wrong.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Config(_) => false,
            #[cfg(feature = "http")]
            Self::Http(_) => true,
            Self::Api { status, .. } => *status >= 500 || *status == 429,
        }
    }
}

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

    #[test]
    fn template_request_omits_unset_fields() {
        let req = SendRequest::template("welcome").to("a@example.com").context(json!({"n": 1}));
        assert_eq!(
            serde_json::to_value(&req).unwrap(),
            json!({ "to": ["a@example.com"], "template": "welcome", "context": {"n": 1} })
        );
    }

    #[test]
    fn raw_request_round_trips() {
        let req = SendRequest::raw("Hi").to("a@example.com").text("hello").idempotency_key("k1");
        let back: SendRequest = serde_json::from_value(serde_json::to_value(&req).unwrap()).unwrap();
        assert_eq!(back, req);
    }

    #[test]
    fn status_strings_match_serde() {
        for s in [MessageStatus::Queued, MessageStatus::Sending, MessageStatus::Sent, MessageStatus::Failed] {
            assert_eq!(serde_json::to_value(s).unwrap(), json!(s.as_str()));
            assert_eq!(MessageStatus::parse(s.as_str()), Some(s));
        }
    }

    #[test]
    fn only_server_side_errors_retry() {
        let api = |status| Error::Api { status, error: "x".into(), detail: None };
        assert!(!api(422).is_retryable());
        assert!(api(503).is_retryable());
        assert!(api(429).is_retryable());
    }
}