mailcycle 0.1.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! One HTTP wrapper. Every failure comes out as [`Error::Api`] with the API's
//! own code, so a caller matches on the code rather than on a message.

use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::error::{Error, Result};

pub const DEFAULT_API_URL: &str = "https://api.mailcycle.email";
pub const DEFAULT_TIMEOUT_SECONDS: u64 = 30;
const USER_AGENT: &str = concat!("mailcycle-rust/", env!("CARGO_PKG_VERSION"));

pub struct Http {
    base_url: String,
    token: Option<String>,
    agent: ureq::Agent,
}

impl Http {
    pub fn new(base_url: &str, token: Option<String>, timeout_seconds: u64) -> Self {
        let agent = ureq::AgentBuilder::new()
            .timeout(std::time::Duration::from_secs(timeout_seconds))
            // Redirects are not followed, so the bearer can never be replayed
            // to another host.
            .redirects(0)
            .user_agent(USER_AGENT)
            .build();
        Http { base_url: base_url.trim_end_matches('/').to_string(), token, agent }
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    pub fn token(&self) -> Option<&str> {
        self.token.as_deref()
    }

    pub fn set_token(&mut self, token: Option<String>) {
        self.token = token;
    }

    fn build(&self, method: &str, path: &str, query: &[(&str, String)]) -> ureq::Request {
        let mut request = self.agent.request(method, &format!("{}{path}", self.base_url));
        request = request.set("Accept", "application/json");
        if let Some(token) = &self.token {
            request = request.set("Authorization", &format!("Bearer {token}"));
        }
        for (key, value) in query {
            request = request.query(key, value);
        }
        request
    }

    fn finish(&self, response: std::result::Result<ureq::Response, ureq::Error>) -> Result<ureq::Response> {
        match response {
            Ok(response) => {
                // With redirects turned off, a 3xx arrives here as a success.
                // It is a failure, not an empty body.
                if (300..400).contains(&response.status()) {
                    return Err(Error::api(
                        response.status(),
                        "unexpected_redirect",
                        format!("{} redirected the request, which is not followed.", self.base_url),
                    ));
                }
                Ok(response)
            }
            Err(ureq::Error::Status(status, response)) => {
                let (mut code, mut message) = ("http_error".to_string(), format!("HTTP {status}"));
                if let Ok(body) = response.into_json::<Value>() {
                    if let Some(found) = body.get("code").and_then(Value::as_str) {
                        code = found.to_string();
                    }
                    if let Some(found) = body.get("message").and_then(Value::as_str) {
                        message = found.to_string();
                    }
                }
                Err(Error::api(status, code, message))
            }
            Err(ureq::Error::Transport(transport)) => {
                Err(Error::api(0, "network_error", format!("Could not reach {}: {transport}", self.base_url)))
            }
        }
    }

    pub fn request<T: DeserializeOwned>(
        &self,
        method: &str,
        path: &str,
        body: Option<&Value>,
        query: &[(&str, String)],
    ) -> Result<T> {
        let request = self.build(method, path, query);
        let response = match body {
            Some(value) if method != "GET" => self.finish(request.send_json(value))?,
            _ => self.finish(request.call())?,
        };
        let text = response
            .into_string()
            .map_err(|_| Error::api(0, "bad_response", "The API's answer could not be read."))?;
        if text.trim().is_empty() {
            return serde_json::from_str("null")
                .or_else(|_| serde_json::from_str("{}"))
                .map_err(|_| Error::api(0, "bad_response", "The API returned nothing."));
        }
        serde_json::from_str(&text)
            .map_err(|_| Error::api(0, "bad_response", "The API returned something unexpected."))
    }

    /// Raw bytes back instead of JSON, for an attachment body.
    pub fn request_bytes(&self, method: &str, path: &str) -> Result<Vec<u8>> {
        let response = self.finish(self.build(method, path, &[]).call())?;
        let mut out = Vec::new();
        response
            .into_reader()
            .read_to_end(&mut out)
            .map_err(|_| Error::api(0, "bad_response", "The body could not be read."))?;
        Ok(out)
    }
}

use std::io::Read;

/// One path component, escaped.
///
/// Ids come back from the server, and the server is the party this product
/// distrusts: an id carrying a slash or a query string would otherwise change
/// which endpoint a call reaches.
pub fn path_segment(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(byte as char),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}