Skip to main content

weirdnet_service/
error.rs

1//! Errors, as they travel on the wire.
2
3use serde::{Deserialize, Serialize};
4
5/// Why a call or subscription did not complete. Sent to the caller as is, so messages must
6/// never carry secrets.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
8#[serde(rename_all = "snake_case", tag = "kind")]
9#[non_exhaustive]
10pub enum ServiceError {
11    /// The server could not be reached.
12    #[error("unreachable: {message}")]
13    Unreachable { message: String },
14    /// The [`Authorize`](crate::Authorize) hook refused the caller. `reason` is a short code
15    /// such as `unknown-device`, `revoked`, `role` or `join-first`.
16    #[error("refused: {reason}")]
17    Refused { reason: String },
18    /// No such resource or topic, or one the caller may not know about.
19    #[error("not found: {message}")]
20    NotFound { message: String },
21    /// The request could not be decoded or is not valid.
22    #[error("bad request: {message}")]
23    BadRequest { message: String },
24    /// The server does not serve this protocol or wire version.
25    #[error("not supported: {message}")]
26    Unsupported { message: String },
27    /// Too many calls; try again later.
28    #[error("busy")]
29    Busy,
30    /// Known, but not available right now.
31    #[error("unavailable: {message}")]
32    Unavailable { message: String },
33    /// An application error with a stable code.
34    #[error("{code}: {message}")]
35    App { code: String, message: String },
36    /// The handler failed.
37    #[error("failed: {message}")]
38    Failed { message: String },
39    /// The other side broke the protocol.
40    #[error("protocol error: {message}")]
41    Protocol { message: String },
42    /// The stream closed.
43    #[error("connection closed")]
44    Closed,
45    /// No answer in time.
46    #[error("timed out")]
47    Timeout,
48    /// Cancelled by the caller.
49    #[error("cancelled")]
50    Cancelled,
51    /// An error kind from a newer peer.
52    #[serde(other)]
53    #[error("unknown error")]
54    Other,
55}
56
57impl ServiceError {
58    pub fn refused(reason: impl Into<String>) -> Self {
59        Self::Refused { reason: reason.into() }
60    }
61
62    pub fn not_found(message: impl Into<String>) -> Self {
63        Self::NotFound { message: message.into() }
64    }
65
66    pub fn bad_request(message: impl Into<String>) -> Self {
67        Self::BadRequest { message: message.into() }
68    }
69
70    pub fn unsupported(message: impl Into<String>) -> Self {
71        Self::Unsupported { message: message.into() }
72    }
73
74    pub fn unavailable(message: impl Into<String>) -> Self {
75        Self::Unavailable { message: message.into() }
76    }
77
78    pub fn app(code: impl Into<String>, message: impl Into<String>) -> Self {
79        Self::App { code: code.into(), message: message.into() }
80    }
81
82    pub fn failed(message: impl Into<String>) -> Self {
83        Self::Failed { message: message.into() }
84    }
85
86    pub fn protocol(message: impl Into<String>) -> Self {
87        Self::Protocol { message: message.into() }
88    }
89
90    /// Retrying the same thing will get the same answer (refused, not found, bad request,
91    /// unsupported, an application error). [`Live`](crate::Live) stops on these and
92    /// reconnects on the rest.
93    pub fn is_permanent(&self) -> bool {
94        matches!(
95            self,
96            Self::Refused { .. } | Self::NotFound { .. } | Self::BadRequest { .. } | Self::Unsupported { .. } | Self::App { .. } | Self::Other
97        )
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::codec::{from_cbor, to_cbor};
105
106    #[test]
107    fn errors_round_trip_and_unknown_kinds_decode() {
108        for e in [ServiceError::refused("role"), ServiceError::Closed, ServiceError::app("limit", "over the daily limit")] {
109            assert_eq!(from_cbor::<ServiceError>(&to_cbor(&e).unwrap()).unwrap(), e);
110        }
111        #[derive(Serialize)]
112        struct Future {
113            kind: &'static str,
114            detail: u32,
115        }
116        let newer = to_cbor(&Future { kind: "quota_exceeded", detail: 3 }).unwrap();
117        assert_eq!(from_cbor::<ServiceError>(&newer).unwrap(), ServiceError::Other);
118        assert!(ServiceError::refused("x").is_permanent() && !ServiceError::Timeout.is_permanent());
119    }
120}