Skip to main content

townos_api/
error.rs

1use serde::Deserialize;
2
3/// An RFC 9457 problem detail, when the server sent one.
4///
5/// The control plane emits these for most refusals; older handlers still answer
6/// with echo's `{"message": ...}`. [`ApiError::detail`] reads either, so callers
7/// that only want something to show a user never have to tell them apart.
8#[derive(Debug, Clone, Deserialize)]
9pub struct Problem {
10    #[serde(default)]
11    pub r#type: String,
12    #[serde(default)]
13    pub title: String,
14    #[serde(default)]
15    pub status: u16,
16    #[serde(default)]
17    pub detail: String,
18}
19
20#[derive(Debug, thiserror::Error)]
21pub enum Error {
22    /// The server answered with a non-200 status.
23    ///
24    /// The control plane returns 200 for every success, including the ones that
25    /// carry no body, so anything else is a refusal worth surfacing.
26    #[error("{method} {path}: {detail}")]
27    Status {
28        method: &'static str,
29        path: String,
30        status: u16,
31        detail: String,
32        /// Boxed because this variant otherwise sets the size of every `Result`
33        /// the crate returns, and `Problem` is 80 bytes of it. Every method here
34        /// is fallible, so the cost is paid on every call and the refusal that
35        /// needs the allocation is the rare path.
36        problem: Option<Box<Problem>>,
37        body: String,
38    },
39
40    #[error("transport: {0}")]
41    Transport(#[from] reqwest::Error),
42
43    #[error("decoding {path}: {source}")]
44    Decode {
45        path: String,
46        #[source]
47        source: serde_json::Error,
48    },
49
50    #[error("invalid base URL: {0}")]
51    BaseUrl(String),
52
53    /// A local file could not be read or written. Only the two archive calls
54    /// touch the filesystem, and a failure there is the user's disk rather than
55    /// the box, so it must not read as an API error.
56    #[error("{path}: {source}")]
57    Io {
58        path: String,
59        #[source]
60        source: std::io::Error,
61    },
62
63    /// The box did not answer within the deadline.
64    ///
65    /// Distinct from `Transport` on purpose. A transport error means something
66    /// said no — the connection was refused, the name did not resolve, TLS was
67    /// rejected — and the user can usually act on it. This means the box said
68    /// nothing at all, which points at a different set of causes: a tunnel that
69    /// is down, a machine that is asleep, a box under load. Telling a user
70    /// "it did not answer" when the truth is "it refused" sends them looking in
71    /// the wrong place.
72    #[error("{verb} {path}: no answer within {after:?}")]
73    Timeout {
74        verb: &'static str,
75        path: String,
76        after: std::time::Duration,
77    },
78
79    /// No session token is set but the endpoint requires one.
80    #[error("not authenticated")]
81    Unauthenticated,
82}
83
84impl Error {
85    pub(crate) fn status(method: &'static str, path: &str, status: u16, body: String) -> Self {
86        let problem = serde_json::from_str::<Problem>(&body)
87            .ok()
88            .filter(|p| !p.r#type.is_empty() && p.status != 0)
89            .map(Box::new);
90
91        let detail = problem
92            .as_ref()
93            .map(|p| p.detail.clone())
94            .filter(|d| !d.is_empty())
95            .or_else(|| {
96                serde_json::from_str::<serde_json::Value>(&body)
97                    .ok()
98                    .and_then(|v| {
99                        v.get("detail")
100                            .or_else(|| v.get("message"))
101                            .and_then(|m| m.as_str().map(str::to_owned))
102                    })
103            })
104            .filter(|d| !d.is_empty())
105            .unwrap_or_else(|| {
106                if body.trim().is_empty() {
107                    format!("status {status}")
108                } else {
109                    body.trim().to_owned()
110                }
111            });
112
113        Error::Status {
114            method,
115            path: path.to_owned(),
116            status,
117            detail,
118            problem,
119            body,
120        }
121    }
122
123    /// The HTTP status, when this was a refusal from the server.
124    pub fn http_status(&self) -> Option<u16> {
125        match self {
126            Error::Status { status, .. } => Some(*status),
127            _ => None,
128        }
129    }
130
131    /// Whether the session token was rejected, so the UI should send the user
132    /// back to the sign-in screen rather than showing an error.
133    ///
134    /// A 401 is a token the server will not accept at all; a 403 is a token it
135    /// accepts from an account that lacks the grant, which is a real answer and
136    /// not a reason to sign out.
137    pub fn is_unauthenticated(&self) -> bool {
138        matches!(self, Error::Unauthenticated) || self.http_status() == Some(401)
139    }
140
141    /// Whether the account is authenticated but lacks the grant this endpoint
142    /// needs. Most write paths are admin-only, so a read-only account hits this
143    /// routinely and it should read as "not yours to change", not as a fault.
144    pub fn is_forbidden(&self) -> bool {
145        self.http_status() == Some(403)
146    }
147
148    /// Whether the box could not be reached at all, as opposed to answering
149    /// with something the user needs to know about.
150    ///
151    /// Both of these mean "there is nothing to talk to here": a transport
152    /// failure is a refusal, a timeout is a silence. The UI groups them because
153    /// the user's next move is the same for both — check the address, check the
154    /// tunnel — and neither is worth the alarm of a red error on a first run
155    /// against a box that is simply not up yet.
156    pub fn is_unreachable(&self) -> bool {
157        matches!(self, Error::Transport(_) | Error::Timeout { .. })
158    }
159
160    /// A message fit to put in front of a user.
161    pub fn detail(&self) -> String {
162        match self {
163            Error::Status { detail, .. } => detail.clone(),
164            other => other.to_string(),
165        }
166    }
167}
168
169pub type Result<T> = std::result::Result<T, Error>;