Skip to main content

icedwright_protocol/
error.rs

1//! The crate's error type and the codes error replies carry.
2
3use core::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::version::VersionMismatch;
8
9/// Framing, JSON and version errors, and error replies from the peer.
10#[derive(Debug, Clone, PartialEq, thiserror::Error)]
11#[non_exhaustive]
12pub enum ProtocolError {
13    /// A frame's length is over [`crate::MAX_FRAME_BYTES`].
14    #[error("frame of {0} bytes is over the 64 MiB limit")]
15    FrameTooLarge(u64),
16    /// A frame or its JSON could not be read. JSON errors are carried as text, because this
17    /// crate does not depend on a JSON library.
18    #[error("malformed frame: {0}")]
19    Malformed(String),
20    /// The peer speaks another major version.
21    #[error(transparent)]
22    Version(#[from] VersionMismatch),
23    /// The peer answered with an error.
24    #[error("{code}: {message}")]
25    Reply {
26        /// What went wrong.
27        code: ErrorCode,
28        /// The peer's explanation.
29        message: String,
30    },
31}
32
33impl From<ErrorBody> for ProtocolError {
34    fn from(body: ErrorBody) -> Self {
35        ProtocolError::Reply {
36            code: body.code,
37            message: body.message,
38        }
39    }
40}
41
42/// What an error reply says went wrong.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45#[non_exhaustive]
46pub enum ErrorCode {
47    /// The peers speak different major versions.
48    ProtocolMismatch,
49    /// The request could not be read or names something that does not exist.
50    BadRequest,
51    /// The window is closed or was never open.
52    NoSuchWindow,
53    /// A guarded input's node moved or went away.
54    Stale,
55    /// The window cannot take input yet, such as when minimised.
56    NotReady,
57    /// Another client is driving the window.
58    Busy,
59    /// The probe will not do this.
60    Refused,
61    /// Something failed inside the probe.
62    Internal,
63}
64
65impl ErrorCode {
66    /// The name on the wire.
67    #[must_use]
68    pub const fn name(self) -> &'static str {
69        match self {
70            ErrorCode::ProtocolMismatch => "protocol_mismatch",
71            ErrorCode::BadRequest => "bad_request",
72            ErrorCode::NoSuchWindow => "no_such_window",
73            ErrorCode::Stale => "stale",
74            ErrorCode::NotReady => "not_ready",
75            ErrorCode::Busy => "busy",
76            ErrorCode::Refused => "refused",
77            ErrorCode::Internal => "internal",
78        }
79    }
80}
81
82impl fmt::Display for ErrorCode {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(self.name())
85    }
86}
87
88/// The body of an error reply.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ErrorBody {
91    /// What went wrong.
92    pub code: ErrorCode,
93    /// A message for people.
94    pub message: String,
95}
96
97impl ErrorBody {
98    /// An error body.
99    #[must_use]
100    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
101        Self {
102            code,
103            message: message.into(),
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn codes_serialise_as_their_names() -> Result<(), serde_json::Error> {
114        for code in [
115            ErrorCode::ProtocolMismatch,
116            ErrorCode::BadRequest,
117            ErrorCode::NoSuchWindow,
118            ErrorCode::Stale,
119            ErrorCode::NotReady,
120            ErrorCode::Busy,
121            ErrorCode::Refused,
122            ErrorCode::Internal,
123        ] {
124            assert_eq!(serde_json::to_string(&code)?, format!("\"{code}\""));
125        }
126        Ok(())
127    }
128
129    #[test]
130    fn reply_errors_print_code_and_message() {
131        let error = ProtocolError::from(ErrorBody::new(ErrorCode::Stale, "the node moved"));
132        assert_eq!(error.to_string(), "stale: the node moved");
133    }
134}