forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBebffd41Ahmet Kaan Gümüş2 months ago509 commits

error.rs333 lines, 14.0 KiBHistoryRawDownload
1use axum::Json;
2use axum::http::{StatusCode, header};
3use axum::response::{IntoResponse, Response};
4use serde::Serialize;
5use serde_json::json;
6use utoipa::ToSchema;
7
8/// Uniform error body shape (`{ "error": "..." }`) used for OpenAPI docs.
9#[derive(Serialize, ToSchema)]
10pub struct ErrorResponse {
11 /// Human-readable failure reason.
12 pub error: String,
13 /// Machine-readable refusal code, present only where a route documents its
14 /// vocabulary (today: the two manual class-attach routes, which answer the
15 /// codes a blueprint pump reports as a skip). Absent everywhere else, so a
16 /// client branches on it where it is published and reads `error` otherwise.
17 #[serde(skip_serializing_if = "Option::is_none")]
18 pub code: Option<String>,
19}
20
21/// Why a newtype refused to be constructed from raw input. Always maps to `400`.
22#[derive(Debug, thiserror::Error)]
23pub enum ValidationError {
24 #[error("{0} must not be empty")]
25 Empty(&'static str),
26 #[error("{field} must be at least {min} characters (got {got})")]
27 TooShort {
28 field: &'static str,
29 min: usize,
30 got: usize,
31 },
32 #[error("{field} must be at most {max} characters (got {got})")]
33 TooLong {
34 field: &'static str,
35 max: usize,
36 got: usize,
37 },
38 #[error("{0} must be ASCII")]
39 NotAscii(&'static str),
40 #[error("{field}: {reason}")]
41 Invalid {
42 field: &'static str,
43 reason: &'static str,
44 },
45 /// A closed value set refused a name it does not contain — and says which
46 /// name, which [`ValidationError::Invalid`] cannot: its `reason` is
47 /// `&'static str`, so the offending value could only be described, never
48 /// quoted.
49 #[error("{field}: `{value}` is not a known {field}")]
50 Unknown { field: &'static str, value: String },
51 /// One request asked for a name in two opposite directions at once — a
52 /// batch that contradicts itself. Names the value, like
53 /// [`ValidationError::Unknown`], because "one of your lists overlaps" would
54 /// leave the caller diffing them by hand.
55 #[error("{field}: `{value}` is asked for in both directions at once")]
56 Contradictory { field: &'static str, value: String },
57}
58
59/// The single error type every fallible operation returns.
60#[derive(Debug, thiserror::Error)]
61pub enum AppError {
62 #[error(transparent)]
63 Validation(#[from] ValidationError),
64 #[error("not found")]
65 NotFound,
66 #[error("unauthorized")]
67 Unauthorized,
68 #[error("forbidden: {0}")]
69 Forbidden(&'static str),
70 /// The school has not bought this module. A dedicated arm because the body
71 /// carries a second key — the module's name — so a client can tell "your
72 /// school does not have this" from every other `403` without parsing prose.
73 #[error("module disabled: {0}")]
74 ModuleDisabled(crate::module::Module),
75 #[error("conflict: {0}")]
76 Conflict(&'static str),
77 /// A 409 whose message is only known at runtime — e.g. the specific
78 /// students a homework's narrowed `assigned` list would orphan. Owned
79 /// string, like [`AppError::PayloadTooLarge`]; static conflicts use
80 /// [`AppError::Conflict`].
81 #[error("conflict: {0}")]
82 ConflictOwned(String),
83 /// A 409 that also carries a **machine code**, so a client branches on the
84 /// cause instead of parsing the sentence (which it cannot translate). The
85 /// prose is unchanged from what the same refusal always said — `code` is
86 /// additive, and only a route that publishes its vocabulary uses this.
87 #[error("conflict: {message}")]
88 ConflictCoded { code: &'static str, message: String },
89 /// A request body (file upload) over the allowed size. Owned string: the
90 /// school-configured limit is only known at runtime.
91 #[error("payload too large: {0}")]
92 PayloadTooLarge(String),
93 #[error("too many requests")]
94 TooManyRequests { retry_after_secs: u64 },
95 #[error("database error")]
96 Db(#[source] sqlx::Error),
97 /// The pool refused before the statement ran: the pool timed out waiting
98 /// for a connection, was closed, or TLS to the server failed to come up.
99 /// Nothing executed, so a retry is safe. Transient, self-healing,
100 /// retryable.
101 #[error("database unavailable")]
102 DbUnavailable,
103 /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], or the
104 /// connection it rode died mid-flight (Postgres reports that as an I/O
105 /// error, not a verdict).
106 ///
107 /// Deliberately NOT `DbUnavailable`: that one promises the statement was
108 /// refused before it executed, so a retry is safe. A request that died on
109 /// the wire may still have applied server-side (the commit can race the
110 /// connection dropping), so retrying can apply the same write twice.
111 /// Same 503, honest message.
112 #[error("request timed out")]
113 DbTimeout,
114 #[error("internal error: {0}")]
115 Internal(String),
116}
117
118impl From<sqlx::Error> for AppError {
119 fn from(e: sqlx::Error) -> Self {
120 match e {
121 // A `fetch_one` that found nothing is the caller's 404, not a 500.
122 sqlx::Error::RowNotFound => AppError::NotFound,
123 // Pool problems refuse on the acquire path: nothing was queued,
124 // let alone executed, so a retry cannot double-apply a write.
125 sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Tls(_) => {
126 AppError::DbUnavailable
127 }
128 // A connection that died under a request. The statement may or
129 // may not have applied — the honest, retry-unsafe 503.
130 sqlx::Error::Io(_) => AppError::DbTimeout,
131 // Everything else is a verdict (or a bug) the server returned —
132 // refusals included; the helpers in [`crate::database`] read the
133 // SQLSTATE off it.
134 _ => AppError::Db(e),
135 }
136 }
137}
138
139impl From<argon2::password_hash::Error> for AppError {
140 fn from(e: argon2::password_hash::Error) -> Self {
141 AppError::Internal(format!("password hashing error: {e}"))
142 }
143}
144
145impl AppError {
146 /// The stable, snake_case name of this refusal's *class* — the value of the
147 /// `error.type` attribute on the span and on `errors_total`. It is a
148 /// dashboard's grouping key, so it never carries anything from the request:
149 /// no field name, no id, no message. Rename an arm freely; never rename one
150 /// of these strings.
151 fn class(&self) -> &'static str {
152 match self {
153 AppError::Validation(_) => "validation",
154 AppError::NotFound => "not_found",
155 AppError::Unauthorized => "unauthorized",
156 AppError::Forbidden(_) => "forbidden",
157 AppError::ModuleDisabled(_) => "module_disabled",
158 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
159 AppError::ConflictCoded { .. } => "conflict_coded",
160 AppError::PayloadTooLarge(_) => "payload_too_large",
161 AppError::TooManyRequests { .. } => "too_many_requests",
162 AppError::Db(_) => "db",
163 AppError::DbUnavailable => "db_unavailable",
164 AppError::DbTimeout => "db_timeout",
165 AppError::Internal(_) => "internal",
166 }
167 }
168
169 /// What a `5xx` log line says beyond its class — the underlying error, which
170 /// the arm's own `Display` hides (`AppError::Db` renders as "database
171 /// error", keeping the SDK's text out of the response body). `None` for
172 /// everything the caller caused: a `4xx` is not an incident and its message
173 /// is derived from what was sent.
174 fn detail(&self) -> Option<String> {
175 match self {
176 AppError::Db(e) => Some(e.to_string()),
177 AppError::Internal(m) => Some(m.clone()),
178 AppError::DbTimeout => Some("the write may or may not have applied".to_owned()),
179 _ => None,
180 }
181 }
182}
183
184impl IntoResponse for AppError {
185 fn into_response(self) -> Response {
186 let class = self.class();
187 let detail = self.detail();
188 let response = self.render();
189 let status = response.status();
190
191 // The request span carries the class; the route is already on the span
192 // and on every metric `measure` records, so the counter needs only the
193 // class and the status.
194 tracing::Span::current().record("error.type", class);
195 crate::telemetry::Metrics::global().errors_total.add(
196 1,
197 &[
198 opentelemetry::KeyValue::new("error.type", class),
199 opentelemetry::KeyValue::new(
200 "http.response.status_code",
201 i64::from(status.as_u16()),
202 ),
203 ],
204 );
205 let detail = detail.as_deref().unwrap_or("");
206 match status.as_u16() {
207 // Expected under load or during a reconnect: worth a line, not a page.
208 429 | 503 if class != "db_timeout" => {
209 tracing::warn!(error.type = class, "refused the request");
210 }
211 500..=599 => tracing::error!(error.type = class, "{detail}"),
212 // The caller's fault, and the loudest thing in the log if it were
213 // any higher: a bad request is not an incident.
214 _ => tracing::debug!(error.type = class, "refused the request"),
215 }
216 response
217 }
218}
219
220impl AppError {
221 /// The wire response, byte for byte what each arm has always answered.
222 fn render(self) -> Response {
223 let (status, message) = match &self {
224 // The one arm with an extra header, so it builds its response here.
225 AppError::TooManyRequests { retry_after_secs } => {
226 return (
227 StatusCode::TOO_MANY_REQUESTS,
228 [(header::RETRY_AFTER, retry_after_secs.to_string())],
229 Json(json!({ "error": "too many requests" })),
230 )
231 .into_response();
232 }
233 // Also carries a header: retry in a second, the reconnect is quick.
234 AppError::DbUnavailable => {
235 return (
236 StatusCode::SERVICE_UNAVAILABLE,
237 [(header::RETRY_AFTER, "1")],
238 Json(json!({ "error": "database reconnecting — retry shortly" })),
239 )
240 .into_response();
241 }
242 // Same 503, but no Retry-After: the query may still be queued and
243 // land later, so a blind retry is not advertised as safe.
244 AppError::DbTimeout => {
245 return (
246 StatusCode::SERVICE_UNAVAILABLE,
247 Json(json!({ "error": "request timed out — the write may or may not have applied" })),
248 )
249 .into_response();
250 }
251 // The one conflict with a second key, so it builds its body here.
252 AppError::ConflictCoded { code, message } => {
253 return (
254 StatusCode::CONFLICT,
255 Json(json!({ "error": message, "code": code })),
256 )
257 .into_response();
258 }
259 // Also carries a second key: which module was refused.
260 AppError::ModuleDisabled(module) => {
261 return (
262 StatusCode::FORBIDDEN,
263 Json(json!({ "error": "module disabled", "module": module.as_str() })),
264 )
265 .into_response();
266 }
267 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
268 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
269 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
270 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
271 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
272 AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
273 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
274 AppError::Db(_) => (
275 StatusCode::INTERNAL_SERVER_ERROR,
276 "database error".to_string(),
277 ),
278 AppError::Internal(_) => (
279 StatusCode::INTERNAL_SERVER_ERROR,
280 "internal server error".to_string(),
281 ),
282 };
283 (status, Json(json!({ "error": message }))).into_response()
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 /// The refusal a gated nest answers with. Both keys, and the `403` — a
292 /// client switches on `module`, so neither may drift.
293 #[tokio::test]
294 async fn a_disabled_module_is_a_403_naming_itself() {
295 use crate::module::Module;
296 let response = AppError::ModuleDisabled(Module::CourseNotes).into_response();
297 assert_eq!(response.status(), StatusCode::FORBIDDEN);
298 let body = axum::body::to_bytes(response.into_body(), 4096)
299 .await
300 .unwrap();
301 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
302 assert_eq!(body["error"], "module disabled");
303 assert_eq!(body["module"], "course_notes");
304 }
305
306 #[test]
307 fn sqlx_errors_split_into_honest_classes() {
308 use sqlx::Error;
309 // Pool problems refuse on the acquire path: nothing executed, so a
310 // retry is safe.
311 assert!(matches!(
312 AppError::from(Error::PoolTimedOut),
313 AppError::DbUnavailable
314 ));
315 assert!(matches!(
316 AppError::from(Error::PoolClosed),
317 AppError::DbUnavailable
318 ));
319 assert!(matches!(
320 AppError::from(Error::Tls("tls".into())),
321 AppError::DbUnavailable
322 ));
323 // A connection that died under a request: the honest 503 — the write
324 // may or may not have applied, so a retry is NOT advertised as safe.
325 let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone");
326 assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout));
327 // A query that found no row is the caller's 404, never a 500.
328 assert!(matches!(
329 AppError::from(Error::RowNotFound),
330 AppError::NotFound
331 ));
332 }
333}