kaivrpc 0.2.0

RPC over kaiv documents: the request/response envelope, typed params, and line-per-element streaming
Documentation
//! Errors: the crate's own failure type, and the application
//! error a response carries in its tail.

use std::fmt;

/// A kaivrpc-level failure — a malformed request document, a
/// missing method, an emission failure.
#[derive(Debug)]
pub enum Error {
    /// The body is not valid kaiv at any pipeline stage.
    Parse(String),
    /// The document lexes but does not carry what the envelope
    /// requires (no `method`, undecodable params).
    Envelope(String),
    /// Emission failed (a value the canonical line grammar cannot
    /// carry, a bad namepath).
    Emit(String),
    /// The document lexes but does not satisfy its method's
    /// schema — see [`ValidationFailure`](crate::ValidationFailure)
    /// for the line it points at.
    Invalid(Box<crate::request::ValidationFailure>),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(m) => write!(f, "kaivrpc parse: {m}"),
            Error::Envelope(m) => write!(f, "kaivrpc envelope: {m}"),
            Error::Emit(m) => write!(f, "kaivrpc emit: {m}"),
            Error::Invalid(v) => write!(f, "kaivrpc invalid request: {v}"),
        }
    }
}

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

impl From<kaiv::error::PipelineError> for Error {
    fn from(e: kaiv::error::PipelineError) -> Self {
        Error::Emit(e.to_string())
    }
}

impl From<kaiv::serde::Error> for Error {
    fn from(e: kaiv::serde::Error) -> Self {
        Error::Envelope(e.to_string())
    }
}

/// The application error a response reports in its tail —
/// `<code> <name>: <message>`, a shape a client can split back
/// apart. Codes and names are the application's own vocabulary;
/// this crate only carries them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RpcError {
    pub code: i32,
    pub name: String,
    pub message: String,
}

impl RpcError {
    pub fn new(code: i32, name: impl Into<String>, message: impl Into<String>) -> RpcError {
        RpcError {
            code,
            name: name.into(),
            message: message.into(),
        }
    }

    /// The single-line tail form. Newlines and NULs collapse to
    /// spaces — an error message must never break the flat line
    /// that reports it.
    pub fn to_line(&self) -> String {
        let msg = self.message.replace(['\n', '\r', '\0'], " ");
        format!("{} {}: {}", self.code, self.name, msg)
    }

    /// Parse the tail form back. A line that does not match the
    /// shape becomes code 0 with the whole text as the message —
    /// a client should always get *something* readable.
    pub fn from_line(s: &str) -> RpcError {
        let mut parts = s.splitn(2, ": ");
        let head = parts.next().unwrap_or("");
        let message = parts.next().unwrap_or("").to_string();
        let mut head_parts = head.splitn(2, ' ');
        let code = head_parts.next().and_then(|c| c.parse().ok());
        let name = head_parts.next().unwrap_or("").to_string();
        match (code, message.is_empty()) {
            (Some(code), false) => RpcError {
                code,
                name,
                message,
            },
            _ => RpcError {
                code: 0,
                name: String::new(),
                message: s.to_string(),
            },
        }
    }
}

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

    #[test]
    fn error_lines_round_trip_and_stay_flat() {
        let e = RpcError::new(602, "InvalidParams", "ids is empty");
        assert_eq!(e.to_line(), "602 InvalidParams: ids is empty");
        assert_eq!(RpcError::from_line(&e.to_line()), e);
        // Multi-line messages collapse — the tail is one line.
        let m = RpcError::new(500, "Internal", "broke\nbadly").to_line();
        assert_eq!(m, "500 Internal: broke badly");
        // Unparseable text survives as a message rather than
        // vanishing.
        let odd = RpcError::from_line("something went wrong");
        assert_eq!(odd.code, 0);
        assert_eq!(odd.message, "something went wrong");
    }
}