Skip to main content

redseat_api/
error.rs

1//! The error type of the crate. Its kinds follow the TypeScript `RedseatErrorKind`
2//! (`@redseat/api` `transport.ts`), plus a few for sign-in and encryption.
3
4/// What went wrong, without the details. Mirrors the TS `RedseatErrorKind`.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6#[non_exhaustive]
7pub enum ErrorKind {
8    /// The server or the cloud could not be reached.
9    Network,
10    /// No answer in time.
11    Timeout,
12    /// 401: missing, expired or refused credentials.
13    Unauthorized,
14    /// 403.
15    Forbidden,
16    /// 404.
17    NotFound,
18    /// 5xx.
19    Server,
20    /// The caller cancelled the operation.
21    Cancelled,
22    /// The answer could not be read (not JSON, wrong shape...).
23    MalformedResponse,
24    /// Any other transport failure, or a client that lacks what the call needs.
25    Transport,
26    /// The Google sign-in failed (refused consent, wrong `state`, token exchange error).
27    SignIn,
28    /// An encrypted library needs its passphrase first.
29    PassphraseRequired,
30    /// The passphrase does not decrypt the library.
31    InvalidPassphrase,
32    /// Encrypted data could not be decrypted.
33    Crypto,
34}
35
36/// The error of every fallible call of the crate.
37#[derive(Debug, thiserror::Error)]
38#[non_exhaustive]
39pub enum Error {
40    #[error("{message}")]
41    Network {
42        message: String,
43        path: Option<String>,
44    },
45    #[error("{message}")]
46    Timeout {
47        message: String,
48        path: Option<String>,
49    },
50    #[error("{message}")]
51    Unauthorized {
52        message: String,
53        status: Option<u16>,
54        path: Option<String>,
55    },
56    #[error("{message}")]
57    Forbidden {
58        message: String,
59        path: Option<String>,
60    },
61    #[error("{message}")]
62    NotFound {
63        message: String,
64        path: Option<String>,
65    },
66    #[error("{message}")]
67    Server {
68        message: String,
69        status: u16,
70        path: Option<String>,
71    },
72    #[error("{message}")]
73    Cancelled { message: String },
74    #[error("{message}")]
75    MalformedResponse {
76        message: String,
77        path: Option<String>,
78    },
79    #[error("{message}")]
80    Transport {
81        message: String,
82        status: Option<u16>,
83        path: Option<String>,
84    },
85    #[error("{message}")]
86    SignIn { message: String },
87    #[error("the library is encrypted: set its passphrase first")]
88    PassphraseRequired,
89    #[error("invalid passphrase: it does not decrypt the library")]
90    InvalidPassphrase,
91    #[error(transparent)]
92    Crypto(#[from] redseat_crypto::Error),
93}
94
95/// Result type of the crate.
96pub type Result<T, E = Error> = std::result::Result<T, E>;
97
98impl Error {
99    /// The kind of the error.
100    pub fn kind(&self) -> ErrorKind {
101        match self {
102            Error::Network { .. } => ErrorKind::Network,
103            Error::Timeout { .. } => ErrorKind::Timeout,
104            Error::Unauthorized { .. } => ErrorKind::Unauthorized,
105            Error::Forbidden { .. } => ErrorKind::Forbidden,
106            Error::NotFound { .. } => ErrorKind::NotFound,
107            Error::Server { .. } => ErrorKind::Server,
108            Error::Cancelled { .. } => ErrorKind::Cancelled,
109            Error::MalformedResponse { .. } => ErrorKind::MalformedResponse,
110            Error::Transport { .. } => ErrorKind::Transport,
111            Error::SignIn { .. } => ErrorKind::SignIn,
112            Error::PassphraseRequired => ErrorKind::PassphraseRequired,
113            Error::InvalidPassphrase => ErrorKind::InvalidPassphrase,
114            Error::Crypto(_) => ErrorKind::Crypto,
115        }
116    }
117
118    /// The HTTP status (or its equivalent in another transport), when there was one.
119    pub fn status(&self) -> Option<u16> {
120        match self {
121            Error::Unauthorized { status, .. } | Error::Transport { status, .. } => *status,
122            Error::Forbidden { .. } => Some(403),
123            Error::NotFound { .. } => Some(404),
124            Error::Server { status, .. } => Some(*status),
125            _ => None,
126        }
127    }
128
129    /// The request path, when the error is tied to one.
130    pub fn path(&self) -> Option<&str> {
131        match self {
132            Error::Network { path, .. }
133            | Error::Timeout { path, .. }
134            | Error::Unauthorized { path, .. }
135            | Error::Forbidden { path, .. }
136            | Error::NotFound { path, .. }
137            | Error::Server { path, .. }
138            | Error::MalformedResponse { path, .. }
139            | Error::Transport { path, .. } => path.as_deref(),
140            _ => None,
141        }
142    }
143
144    pub(crate) fn transport(message: impl Into<String>) -> Self {
145        Error::Transport {
146            message: message.into(),
147            status: None,
148            path: None,
149        }
150    }
151
152    pub(crate) fn malformed(message: impl Into<String>, path: Option<&str>) -> Self {
153        Error::MalformedResponse {
154            message: message.into(),
155            path: path.map(str::to_owned),
156        }
157    }
158
159    pub(crate) fn sign_in(message: impl Into<String>) -> Self {
160        Error::SignIn {
161            message: message.into(),
162        }
163    }
164
165    /// The error for a non-success HTTP status. The message is the `message`, `code` or
166    /// `error` field of a JSON body when there is one, as in the mobile app's `failure()`.
167    pub fn from_status(status: u16, path: Option<&str>, body: &[u8]) -> Self {
168        let path = path.map(str::to_owned);
169        let message = body_message(body).unwrap_or_else(|| format!("HTTP {status}"));
170        match status {
171            401 => Error::Unauthorized {
172                message,
173                status: Some(status),
174                path,
175            },
176            403 => Error::Forbidden { message, path },
177            404 => Error::NotFound { message, path },
178            500.. => Error::Server {
179                message,
180                status,
181                path,
182            },
183            _ => Error::Transport {
184                message,
185                status: Some(status),
186                path,
187            },
188        }
189    }
190}
191
192fn body_message(body: &[u8]) -> Option<String> {
193    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
194    ["message", "code", "error", "error_description"]
195        .iter()
196        .find_map(|field| {
197            value
198                .get(field)
199                .and_then(|v| v.as_str())
200                .filter(|s| !s.is_empty())
201                .map(str::to_owned)
202        })
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn maps_statuses_like_the_ts_transport() {
211        assert_eq!(
212            Error::from_status(401, None, b"").kind(),
213            ErrorKind::Unauthorized
214        );
215        assert_eq!(
216            Error::from_status(403, None, b"").kind(),
217            ErrorKind::Forbidden
218        );
219        assert_eq!(
220            Error::from_status(404, None, b"").kind(),
221            ErrorKind::NotFound
222        );
223        assert_eq!(Error::from_status(502, None, b"").kind(), ErrorKind::Server);
224        assert_eq!(
225            Error::from_status(400, None, b"").kind(),
226            ErrorKind::Transport
227        );
228        assert_eq!(Error::from_status(400, None, b"").status(), Some(400));
229    }
230
231    #[test]
232    fn reads_the_message_of_a_json_body() {
233        let error = Error::from_status(400, Some("/x"), br#"{"code":"INVALID_TOKEN"}"#);
234        assert_eq!(error.to_string(), "INVALID_TOKEN");
235        assert_eq!(error.path(), Some("/x"));
236        assert_eq!(
237            Error::from_status(400, None, b"<html>").to_string(),
238            "HTTP 400"
239        );
240    }
241}