mailcycle 0.2.1

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! The account event stream, `GET /accounts/live`.
//!
//! Receive only. A background thread holds the socket and reconnects with
//! backoff after a drop, saying so through `on_reconnect`, because events that
//! happen while it is down are NOT replayed. It stops for good when the server
//! ends it for a reason reconnecting cannot fix: the credential is gone
//! (4001), the plan does not include the stream (4003), or the upgrade itself
//! was refused.
//!
//! ```no_run
//! # use mailcycle::Mailcycle;
//! # fn main() -> mailcycle::error::Result<()> {
//! # let mc = Mailcycle::sign_in("...", Default::default())?;
//! let stream = mc.events().stream()?;
//! while let Some(event) = stream.next_event(None) {
//!     println!("{}", event.event_type);
//! }
//! # Ok(()) }
//! ```
//!
//! `tungstenite` is behind the `events` feature, so a program that never opens
//! a stream does not build it.

use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "events")]
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;

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

#[cfg(feature = "events")]
const PROTOCOL: &str = "mailcycle.v1";
#[cfg(feature = "events")]
const PING: Duration = Duration::from_secs(4 * 60);
#[cfg(feature = "events")]
const MAX_RETRY_SECONDS: u64 = 60;
/// Closing codes reconnecting cannot fix.
#[cfg(feature = "events")]
const FINAL_CODES: [u16; 2] = [4001, 4003];
/// The same, for an upgrade the server refused outright.
#[cfg(feature = "events")]
const FINAL_STATUSES: [u16; 5] = [400, 401, 403, 404, 426];

enum Item {
    // Only the socket thread sends events, and it exists with `events` on.
    #[cfg_attr(not(feature = "events"), allow(dead_code))]
    Event(Box<AccountEvent>),
    Done,
}

/// Called when the stream reconnects.
pub type OnReconnect = Box<dyn Fn() + Send + Sync>;
/// Called with the API's code and message when the stream is refused.
pub type OnError = Box<dyn Fn(&str, &str) + Send + Sync>;

/// Callbacks, run on the stream's own thread.
#[derive(Default)]
pub struct Hooks {
    /// Events that happen while the stream is down are not replayed, so this
    /// is where to refetch whatever the program is showing.
    pub on_reconnect: Option<OnReconnect>,
    pub on_error: Option<OnError>,
}

struct Shared {
    stopping: AtomicBool,
    opened: Mutex<bool>,
    opened_signal: std::sync::Condvar,
    closed_reason: Mutex<Option<(u16, String)>>,
}

/// A live connection. Read it with [`EventStream::next_event`]; drop or
/// [`close`](EventStream::close) it when finished.
pub struct EventStream {
    receiver: Mutex<Receiver<Item>>,
    sender: Sender<Item>,
    shared: Arc<Shared>,
    handle: Mutex<Option<std::thread::JoinHandle<()>>>,
}

impl EventStream {
    #[cfg(feature = "events")]
    pub fn open(base_url: &str, token: &str, hooks: Hooks) -> Result<Self> {
        let url = base_url
            .replacen("https://", "wss://", 1)
            .replacen("http://", "ws://", 1)
            .trim_end_matches('/')
            .to_string()
            + "/accounts/live";

        let (sender, receiver) = mpsc::channel();
        let shared = Arc::new(Shared {
            stopping: AtomicBool::new(false),
            opened: Mutex::new(false),
            opened_signal: std::sync::Condvar::new(),
            closed_reason: Mutex::new(None),
        });

        let handle = std::thread::Builder::new()
            .name("mailcycle-events".into())
            .spawn({
                let shared = Arc::clone(&shared);
                let sender = sender.clone();
                let token = token.to_string();
                move || run(url, token, hooks, shared, sender)
            })
            .map_err(|e| Error::Unsupported(format!("Could not start the event thread: {e}")))?;

        Ok(EventStream { receiver: Mutex::new(receiver), sender, shared, handle: Mutex::new(Some(handle)) })
    }

    #[cfg(not(feature = "events"))]
    pub fn open(_base_url: &str, _token: &str, _hooks: Hooks) -> Result<Self> {
        Err(Error::Unsupported(
            "The event stream needs the `events` feature: mailcycle = { features = [\"events\"] }".into(),
        ))
    }

    /// The next event, or `None` if the stream ends or `timeout` runs out.
    ///
    /// Blocking forever is right for a long-lived listener and wrong for
    /// anything with a deadline: a stream that is healthy and silent would
    /// never return. Pass a timeout for the second case.
    pub fn next_event(&self, timeout: Option<Duration>) -> Option<AccountEvent> {
        let receiver = self.receiver.lock().ok()?;
        let item = match timeout {
            Some(limit) => match receiver.recv_timeout(limit) {
                Ok(item) => item,
                Err(RecvTimeoutError::Timeout) => return None,
                Err(RecvTimeoutError::Disconnected) => return None,
            },
            None => receiver.recv().ok()?,
        };
        match item {
            Item::Event(event) => Some(*event),
            Item::Done => {
                // Put it back, so a later call still sees the end.
                let _ = self.sender.send(Item::Done);
                None
            }
        }
    }

    /// Blocks until the socket is up, or the stream ends, or time runs out.
    ///
    /// Connecting is retried in the background forever, which is right for a
    /// long-lived listener and wrong for a caller with something else it could
    /// be doing: without this, a stream that never connects looks exactly like
    /// a stream with nothing to say.
    pub fn wait_until_open(&self, timeout: Duration) -> bool {
        let Ok(guard) = self.shared.opened.lock() else { return false };
        let Ok((guard, _)) = self.shared.opened_signal.wait_timeout_while(guard, timeout, |opened| !*opened)
        else {
            return false;
        };
        *guard
    }

    /// True once the stream has stopped for good and will not reconnect.
    pub fn ended(&self) -> bool {
        self.shared.closed_reason.lock().map(|r| r.is_some()).unwrap_or(true)
    }

    /// Why it ended, once it has.
    pub fn closed_reason(&self) -> Option<(u16, String)> {
        self.shared.closed_reason.lock().ok().and_then(|r| r.clone())
    }

    /// Stops listening and closes the socket. Safe to call twice.
    pub fn close(&self) {
        self.shared.stopping.store(true, Ordering::SeqCst);
        // Release anything waiting to open: it is not going to happen now.
        if let Ok(mut opened) = self.shared.opened.lock() {
            *opened = true;
            self.shared.opened_signal.notify_all();
        }
        if let Ok(mut handle) = self.handle.lock() {
            if let Some(joinable) = handle.take() {
                let _ = joinable.join();
            }
        }
        let _ = self.sender.send(Item::Done);
    }
}

impl Drop for EventStream {
    fn drop(&mut self) {
        self.close();
    }
}

#[cfg(feature = "events")]
fn run(url: String, token: String, hooks: Hooks, shared: Arc<Shared>, sender: Sender<Item>) {
    use tungstenite::client::IntoClientRequest;
    use tungstenite::http::HeaderValue;
    use tungstenite::{Error as WsError, Message};

    let finish = |code: u16, reason: String| {
        if let Ok(mut closed) = shared.closed_reason.lock() {
            if closed.is_none() {
                *closed = Some((code, reason));
            }
        }
        // Anything waiting for the socket to come up is waiting for something
        // that is not going to happen now.
        if let Ok(mut opened) = shared.opened.lock() {
            *opened = true;
            shared.opened_signal.notify_all();
        }
        let _ = sender.send(Item::Done);
    };

    let mut retry: u32 = 0;
    let mut ever_opened = false;

    while !shared.stopping.load(Ordering::SeqCst) {
        let mut request = match url.as_str().into_client_request() {
            Ok(request) => request,
            Err(error) => return finish(1006, format!("the stream address is not usable: {error}")),
        };
        // The credential travels as the second subprotocol, which is what the
        // server reads it from; both are plain HTTP tokens.
        match HeaderValue::from_str(&format!("{PROTOCOL}, {token}")) {
            Ok(value) => {
                request.headers_mut().insert("Sec-WebSocket-Protocol", value);
            }
            Err(_) => return finish(1006, "the credential is not a usable subprotocol".into()),
        }

        let mut socket = match tungstenite::connect(request) {
            Ok((socket, _response)) => socket,
            Err(WsError::Http(response)) => {
                // The upgrade itself was refused, which is how the API says
                // the credential is wrong or the plan does not include the
                // stream. Retrying that is pointless.
                let status = response.status().as_u16();
                let reason = format!("the server answered {status} to the upgrade");
                if FINAL_STATUSES.contains(&status) {
                    return finish(1006, reason);
                }
                sleep_backoff(&mut retry);
                continue;
            }
            Err(_) => {
                // A refused connection, a DNS failure, a TLS failure. Worth
                // retrying, because all three are often temporary.
                sleep_backoff(&mut retry);
                continue;
            }
        };

        // A read timeout, so the loop can notice `close()` and send its ping
        // rather than blocking forever on a quiet socket.
        match socket.get_mut() {
            tungstenite::stream::MaybeTlsStream::Plain(stream) => {
                let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
            }
            tungstenite::stream::MaybeTlsStream::NativeTls(stream) => {
                let _ = stream.get_ref().set_read_timeout(Some(Duration::from_secs(5)));
            }
            _ => {}
        }

        if ever_opened {
            if let Some(hook) = &hooks.on_reconnect {
                hook();
            }
        }
        ever_opened = true;
        retry = 0;
        if let Ok(mut opened) = shared.opened.lock() {
            *opened = true;
            shared.opened_signal.notify_all();
        }

        let mut last_ping = std::time::Instant::now();
        let mut refused: Option<(String, String)> = None;
        let mut code = 1006u16;
        let mut reason = String::from("connection lost");

        loop {
            if shared.stopping.load(Ordering::SeqCst) {
                let _ = socket.close(None);
                return finish(1000, "closed".into());
            }
            match socket.read() {
                Ok(Message::Text(text)) => {
                    if let Some(found) = handle_frame(&text, &hooks, &sender) {
                        refused = Some(found);
                        break;
                    }
                }
                Ok(Message::Close(frame)) => {
                    if let Some(frame) = frame {
                        code = frame.code.into();
                        reason = frame.reason.to_string();
                    }
                    break;
                }
                Ok(_) => {}
                Err(WsError::Io(error)) if is_timeout(&error) => {}
                Err(WsError::ConnectionClosed | WsError::AlreadyClosed) => break,
                Err(_) => break,
            }
            if last_ping.elapsed() >= PING {
                let _ = socket.send(Message::Text("ping".into()));
                last_ping = std::time::Instant::now();
            }
        }

        if shared.stopping.load(Ordering::SeqCst) {
            return finish(1000, "closed".into());
        }
        if let Some((refused_code, _)) = &refused {
            return finish(code, refused_code.clone());
        }
        if FINAL_CODES.contains(&code) {
            return finish(code, if reason.is_empty() { "closed".into() } else { reason });
        }
        sleep_backoff(&mut retry);
    }

    finish(1000, "closed".into());
}

#[cfg(feature = "events")]
fn is_timeout(error: &std::io::Error) -> bool {
    matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
}

#[cfg(feature = "events")]
fn handle_frame(text: &str, hooks: &Hooks, sender: &Sender<Item>) -> Option<(String, String)> {
    if text == "pong" {
        return None;
    }
    let frame: serde_json::Value = serde_json::from_str(text).ok()?;
    if !frame.is_object() {
        return None;
    }
    if frame.get("type").and_then(|v| v.as_str()) == Some("error") {
        let code = frame.get("code").and_then(|v| v.as_str()).unwrap_or("error").to_string();
        let message = frame
            .get("message")
            .and_then(|v| v.as_str())
            .unwrap_or("The event stream was refused.")
            .to_string();
        if let Some(hook) = &hooks.on_error {
            hook(&code, &message);
        }
        return Some((code, message));
    }
    let event: AccountEvent = serde_json::from_value(frame).ok()?;
    let _ = sender.send(Item::Event(Box::new(event)));
    None
}

#[cfg(feature = "events")]
fn sleep_backoff(retry: &mut u32) {
    std::thread::sleep(Duration::from_secs(MAX_RETRY_SECONDS.min(1u64 << (*retry).min(6))));
    *retry = (*retry + 1).min(8);
}