mailcycle 0.8.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
Documentation
//! Every error this crate returns.
//!
//! One enum, so a caller matches once and is done. An API failure carries the
//! API's own stable `code` (`plan_required`, `rate_limited`) rather than a
//! message to match on.

use std::fmt;

/// Where an account changes plan. A plan refusal ends with this link, so the
/// error says what to do next and not only what was refused.
pub const UPGRADE_URL: &str = "https://app.mailcycle.email/operator/billing";

/// The result type every fallible call in this crate returns.
pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// A request the API refused, or one that never reached it.
    Api {
        /// The HTTP status, or 0 when the request never got an answer.
        status: u16,
        /// The API's stable, machine-readable code.
        code: String,
        /// The message as the API wrote it, without the upgrade link.
        message: String,
        /// For a plan refusal, the lowest plan that allows the call, such as
        /// `"plan_operator"`. `None` otherwise.
        required_plan_id: Option<String>,
    },
    /// Data that would not open with the key provided.
    ///
    /// Every way an open can fail arrives as this one, including a box that is
    /// not a box at all. The fields come from a server, so "malformed" is a
    /// state the server can choose, and a reader that panicked on it would let
    /// the server decide that a program crashes instead of showing one record
    /// as unreadable.
    Decryption,
    /// Text that is not canonical base64url.
    Base64Url(&'static str),
    /// A recovery phrase that is not one.
    Phrase(PhraseProblem),
    /// A challenge the server offered that cannot be answered safely.
    AuthProof(&'static str),
    /// Something the caller asked for that this client cannot do.
    Unsupported(String),
}

impl Error {
    pub(crate) fn api(status: u16, code: impl Into<String>, message: impl Into<String>) -> Self {
        Error::Api { status, code: code.into(), message: message.into(), required_plan_id: None }
    }

    /// For a plan refusal, the lowest plan that allows the call.
    pub fn required_plan_id(&self) -> Option<&str> {
        match self {
            Error::Api { required_plan_id, .. } => required_plan_id.as_deref(),
            _ => None,
        }
    }

    /// For a plan refusal (`plan_required`, `plan_capability_required`), the
    /// page that changes the plan, with the plan the call needs already
    /// picked. `None` for every other error.
    pub fn upgrade_url(&self) -> Option<String> {
        let Error::Api { code, required_plan_id, .. } = self else { return None };
        if code != "plan_required" && code != "plan_capability_required" {
            return None;
        }
        match required_plan_id.as_deref() {
            Some(plan) if is_plan_id(plan) => Some(format!("{UPGRADE_URL}?upgrade={plan}")),
            _ => Some(UPGRADE_URL.to_string()),
        }
    }

    /// The API's code, for the failures that have one.
    pub fn code(&self) -> Option<&str> {
        match self {
            Error::Api { code, .. } => Some(code),
            _ => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Api { code, message, .. } => match self.upgrade_url() {
                Some(url) => write!(f, "{code}: {message} Upgrade at {url}"),
                None => write!(f, "{code}: {message}"),
            },
            Error::Decryption => f.write_str("This data could not be decrypted with the key provided."),
            Error::Base64Url(why) => write!(f, "Not canonical base64url: {why}"),
            Error::Phrase(problem) => write!(f, "{problem}"),
            Error::AuthProof(why) => f.write_str(why),
            Error::Unsupported(what) => f.write_str(what),
        }
    }
}

impl std::error::Error for Error {}

/// `plan_` and lowercase letters, the shape of every plan id the API names.
fn is_plan_id(plan: &str) -> bool {
    plan.strip_prefix("plan_")
        .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_lowercase()))
}

/// Why a recovery phrase was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PhraseProblem {
    /// Not twelve words. Carries how many there were.
    Length(usize),
    /// A word that is not in the list, and where it was.
    UnknownWord { word: String, index: usize },
    /// Twelve known words that do not agree with their checksum.
    Checksum,
}

impl fmt::Display for PhraseProblem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PhraseProblem::Length(count) => {
                write!(f, "A recovery phrase is twelve words; this one has {count}.")
            }
            PhraseProblem::UnknownWord { word, index } => {
                write!(f, "Word {} is not in the list: {word:?}.", index + 1)
            }
            PhraseProblem::Checksum => {
                f.write_str("Those twelve words do not check out; one of them is wrong.")
            }
        }
    }
}