icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
//! The crate's error type and the codes error replies carry.

use core::fmt;

use serde::{Deserialize, Serialize};

use crate::version::VersionMismatch;

/// Framing, JSON and version errors, and error replies from the peer.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolError {
    /// A frame's length is over [`crate::MAX_FRAME_BYTES`].
    #[error("frame of {0} bytes is over the 64 MiB limit")]
    FrameTooLarge(u64),
    /// A frame or its JSON could not be read. JSON errors are carried as text, because this
    /// crate does not depend on a JSON library.
    #[error("malformed frame: {0}")]
    Malformed(String),
    /// The peer speaks another major version.
    #[error(transparent)]
    Version(#[from] VersionMismatch),
    /// The peer answered with an error.
    #[error("{code}: {message}")]
    Reply {
        /// What went wrong.
        code: ErrorCode,
        /// The peer's explanation.
        message: String,
    },
}

impl From<ErrorBody> for ProtocolError {
    fn from(body: ErrorBody) -> Self {
        ProtocolError::Reply {
            code: body.code,
            message: body.message,
        }
    }
}

/// What an error reply says went wrong.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
    /// The peers speak different major versions.
    ProtocolMismatch,
    /// The request could not be read or names something that does not exist.
    BadRequest,
    /// The window is closed or was never open.
    NoSuchWindow,
    /// A guarded input's node moved or went away.
    Stale,
    /// The window cannot take input yet, such as when minimised.
    NotReady,
    /// Another client is driving the window.
    Busy,
    /// The probe will not do this.
    Refused,
    /// Something failed inside the probe.
    Internal,
}

impl ErrorCode {
    /// The name on the wire.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            ErrorCode::ProtocolMismatch => "protocol_mismatch",
            ErrorCode::BadRequest => "bad_request",
            ErrorCode::NoSuchWindow => "no_such_window",
            ErrorCode::Stale => "stale",
            ErrorCode::NotReady => "not_ready",
            ErrorCode::Busy => "busy",
            ErrorCode::Refused => "refused",
            ErrorCode::Internal => "internal",
        }
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// The body of an error reply.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorBody {
    /// What went wrong.
    pub code: ErrorCode,
    /// A message for people.
    pub message: String,
}

impl ErrorBody {
    /// An error body.
    #[must_use]
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

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

    #[test]
    fn codes_serialise_as_their_names() -> Result<(), serde_json::Error> {
        for code in [
            ErrorCode::ProtocolMismatch,
            ErrorCode::BadRequest,
            ErrorCode::NoSuchWindow,
            ErrorCode::Stale,
            ErrorCode::NotReady,
            ErrorCode::Busy,
            ErrorCode::Refused,
            ErrorCode::Internal,
        ] {
            assert_eq!(serde_json::to_string(&code)?, format!("\"{code}\""));
        }
        Ok(())
    }

    #[test]
    fn reply_errors_print_code_and_message() {
        let error = ProtocolError::from(ErrorBody::new(ErrorCode::Stale, "the node moved"));
        assert_eq!(error.to_string(), "stale: the node moved");
    }
}