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    /// The local copy of a server (feature `mirror`) could not be read or written.
35    Storage,
36}
37
38/// The error of every fallible call of the crate.
39#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum Error {
42    #[error("{message}")]
43    Network {
44        message: String,
45        path: Option<String>,
46    },
47    #[error("{message}")]
48    Timeout {
49        message: String,
50        path: Option<String>,
51    },
52    #[error("{message}")]
53    Unauthorized {
54        message: String,
55        status: Option<u16>,
56        path: Option<String>,
57    },
58    #[error("{message}")]
59    Forbidden {
60        message: String,
61        path: Option<String>,
62    },
63    #[error("{message}")]
64    NotFound {
65        message: String,
66        path: Option<String>,
67    },
68    #[error("{message}")]
69    Server {
70        message: String,
71        status: u16,
72        path: Option<String>,
73    },
74    #[error("{message}")]
75    Cancelled { message: String },
76    #[error("{message}")]
77    MalformedResponse {
78        message: String,
79        path: Option<String>,
80    },
81    #[error("{message}")]
82    Transport {
83        message: String,
84        status: Option<u16>,
85        path: Option<String>,
86    },
87    #[error("{message}")]
88    SignIn { message: String },
89    #[error("the library is encrypted: set its passphrase first")]
90    PassphraseRequired,
91    #[error("invalid passphrase: it does not decrypt the library")]
92    InvalidPassphrase,
93    #[error(transparent)]
94    Crypto(#[from] redseat_crypto::Error),
95    #[error("{message}")]
96    Storage { message: String },
97}
98
99/// Result type of the crate.
100pub type Result<T, E = Error> = std::result::Result<T, E>;
101
102impl Error {
103    /// The kind of the error.
104    pub fn kind(&self) -> ErrorKind {
105        match self {
106            Error::Network { .. } => ErrorKind::Network,
107            Error::Timeout { .. } => ErrorKind::Timeout,
108            Error::Unauthorized { .. } => ErrorKind::Unauthorized,
109            Error::Forbidden { .. } => ErrorKind::Forbidden,
110            Error::NotFound { .. } => ErrorKind::NotFound,
111            Error::Server { .. } => ErrorKind::Server,
112            Error::Cancelled { .. } => ErrorKind::Cancelled,
113            Error::MalformedResponse { .. } => ErrorKind::MalformedResponse,
114            Error::Transport { .. } => ErrorKind::Transport,
115            Error::SignIn { .. } => ErrorKind::SignIn,
116            Error::PassphraseRequired => ErrorKind::PassphraseRequired,
117            Error::InvalidPassphrase => ErrorKind::InvalidPassphrase,
118            Error::Crypto(_) => ErrorKind::Crypto,
119            Error::Storage { .. } => ErrorKind::Storage,
120        }
121    }
122
123    /// The HTTP status (or its equivalent in another transport), when there was one.
124    pub fn status(&self) -> Option<u16> {
125        match self {
126            Error::Unauthorized { status, .. } | Error::Transport { status, .. } => *status,
127            Error::Forbidden { .. } => Some(403),
128            Error::NotFound { .. } => Some(404),
129            Error::Server { status, .. } => Some(*status),
130            _ => None,
131        }
132    }
133
134    /// The request path, when the error is tied to one.
135    pub fn path(&self) -> Option<&str> {
136        match self {
137            Error::Network { path, .. }
138            | Error::Timeout { path, .. }
139            | Error::Unauthorized { path, .. }
140            | Error::Forbidden { path, .. }
141            | Error::NotFound { path, .. }
142            | Error::Server { path, .. }
143            | Error::MalformedResponse { path, .. }
144            | Error::Transport { path, .. } => path.as_deref(),
145            _ => None,
146        }
147    }
148
149    pub(crate) fn transport(message: impl Into<String>) -> Self {
150        Error::Transport {
151            message: message.into(),
152            status: None,
153            path: None,
154        }
155    }
156
157    pub(crate) fn malformed(message: impl Into<String>, path: Option<&str>) -> Self {
158        Error::MalformedResponse {
159            message: message.into(),
160            path: path.map(str::to_owned),
161        }
162    }
163
164    /// A failure of the local storage.
165    pub fn storage(message: impl Into<String>) -> Self {
166        Error::Storage {
167            message: message.into(),
168        }
169    }
170
171    pub(crate) fn sign_in(message: impl Into<String>) -> Self {
172        Error::SignIn {
173            message: message.into(),
174        }
175    }
176
177    /// The error for a non-success HTTP status. The message is the `message`, `code` or
178    /// `error` field of a JSON body when there is one, as in the mobile app's `failure()`.
179    pub fn from_status(status: u16, path: Option<&str>, body: &[u8]) -> Self {
180        let path = path.map(str::to_owned);
181        let message = body_message(body).unwrap_or_else(|| format!("HTTP {status}"));
182        match status {
183            401 => Error::Unauthorized {
184                message,
185                status: Some(status),
186                path,
187            },
188            403 => Error::Forbidden { message, path },
189            404 => Error::NotFound { message, path },
190            500.. => Error::Server {
191                message,
192                status,
193                path,
194            },
195            _ => Error::Transport {
196                message,
197                status: Some(status),
198                path,
199            },
200        }
201    }
202}
203
204fn body_message(body: &[u8]) -> Option<String> {
205    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
206    ["message", "code", "error", "error_description"]
207        .iter()
208        .find_map(|field| {
209            value
210                .get(field)
211                .and_then(|v| v.as_str())
212                .filter(|s| !s.is_empty())
213                .map(str::to_owned)
214        })
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn maps_statuses_like_the_ts_transport() {
223        assert_eq!(
224            Error::from_status(401, None, b"").kind(),
225            ErrorKind::Unauthorized
226        );
227        assert_eq!(
228            Error::from_status(403, None, b"").kind(),
229            ErrorKind::Forbidden
230        );
231        assert_eq!(
232            Error::from_status(404, None, b"").kind(),
233            ErrorKind::NotFound
234        );
235        assert_eq!(Error::from_status(502, None, b"").kind(), ErrorKind::Server);
236        assert_eq!(
237            Error::from_status(400, None, b"").kind(),
238            ErrorKind::Transport
239        );
240        assert_eq!(Error::from_status(400, None, b"").status(), Some(400));
241    }
242
243    #[test]
244    fn reads_the_message_of_a_json_body() {
245        let error = Error::from_status(400, Some("/x"), br#"{"code":"INVALID_TOKEN"}"#);
246        assert_eq!(error.to_string(), "INVALID_TOKEN");
247        assert_eq!(error.path(), Some("/x"));
248        assert_eq!(
249            Error::from_status(400, None, b"<html>").to_string(),
250            "HTTP 400"
251        );
252    }
253}