forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

error.rs342 lines, 14.5 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 /// The resource existed, its retention window has passed, and nothing
67 /// about it is served any more — a podcast job older than
68 /// [`crate::constant::PODCAST_JOB_RETENTION_SECS`] today. A dedicated
69 /// `410` so a client can tell "gone for good" from "never existed" (`404`)
70 /// and from "not written yet" (`409`) without parsing a sentence.
71 #[error("expired: {0}")]
72 Expired(&'static str),
73 #[error("unauthorized")]
74 Unauthorized,
75 #[error("forbidden: {0}")]
76 Forbidden(&'static str),
77 /// The school has not bought this module. A dedicated arm because the body
78 /// carries a second key — the module's name — so a client can tell "your
79 /// school does not have this" from every other `403` without parsing prose.
80 #[error("module disabled: {0}")]
81 ModuleDisabled(crate::module::Module),
82 #[error("conflict: {0}")]
83 Conflict(&'static str),
84 /// A 409 whose message is only known at runtime — e.g. the specific
85 /// students a homework's narrowed `assigned` list would orphan. Owned
86 /// string, like [`AppError::PayloadTooLarge`]; static conflicts use
87 /// [`AppError::Conflict`].
88 #[error("conflict: {0}")]
89 ConflictOwned(String),
90 /// A 409 that also carries a **machine code**, so a client branches on the
91 /// cause instead of parsing the sentence (which it cannot translate). The
92 /// prose is unchanged from what the same refusal always said — `code` is
93 /// additive, and only a route that publishes its vocabulary uses this.
94 #[error("conflict: {message}")]
95 ConflictCoded { code: &'static str, message: String },
96 /// A request body (file upload) over the allowed size. Owned string: the
97 /// school-configured limit is only known at runtime.
98 #[error("payload too large: {0}")]
99 PayloadTooLarge(String),
100 #[error("too many requests")]
101 TooManyRequests { retry_after_secs: u64 },
102 #[error("database error")]
103 Db(#[source] sqlx::Error),
104 /// The pool refused before the statement ran: the pool timed out waiting
105 /// for a connection, was closed, or TLS to the server failed to come up.
106 /// Nothing executed, so a retry is safe. Transient, self-healing,
107 /// retryable.
108 #[error("database unavailable")]
109 DbUnavailable,
110 /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], or the
111 /// connection it rode died mid-flight (Postgres reports that as an I/O
112 /// error, not a verdict).
113 ///
114 /// Deliberately NOT `DbUnavailable`: that one promises the statement was
115 /// refused before it executed, so a retry is safe. A request that died on
116 /// the wire may still have applied server-side (the commit can race the
117 /// connection dropping), so retrying can apply the same write twice.
118 /// Same 503, honest message.
119 #[error("request timed out")]
120 DbTimeout,
121 #[error("internal error: {0}")]
122 Internal(String),
123}
124
125impl From<sqlx::Error> for AppError {
126 fn from(e: sqlx::Error) -> Self {
127 match e {
128 // A `fetch_one` that found nothing is the caller's 404, not a 500.
129 sqlx::Error::RowNotFound => AppError::NotFound,
130 // Pool problems refuse on the acquire path: nothing was queued,
131 // let alone executed, so a retry cannot double-apply a write.
132 sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Tls(_) => {
133 AppError::DbUnavailable
134 }
135 // A connection that died under a request. The statement may or
136 // may not have applied — the honest, retry-unsafe 503.
137 sqlx::Error::Io(_) => AppError::DbTimeout,
138 // Everything else is a verdict (or a bug) the server returned —
139 // refusals included; the helpers in [`crate::database`] read the
140 // SQLSTATE off it.
141 _ => AppError::Db(e),
142 }
143 }
144}
145
146impl From<argon2::password_hash::Error> for AppError {
147 fn from(e: argon2::password_hash::Error) -> Self {
148 AppError::Internal(format!("password hashing error: {e}"))
149 }
150}
151
152impl AppError {
153 /// The stable, snake_case name of this refusal's *class* — the value of the
154 /// `error.type` attribute on the span and on `errors_total`. It is a
155 /// dashboard's grouping key, so it never carries anything from the request:
156 /// no field name, no id, no message. Rename an arm freely; never rename one
157 /// of these strings.
158 fn class(&self) -> &'static str {
159 match self {
160 AppError::Validation(_) => "validation",
161 AppError::NotFound => "not_found",
162 AppError::Expired(_) => "expired",
163 AppError::Unauthorized => "unauthorized",
164 AppError::Forbidden(_) => "forbidden",
165 AppError::ModuleDisabled(_) => "module_disabled",
166 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
167 AppError::ConflictCoded { .. } => "conflict_coded",
168 AppError::PayloadTooLarge(_) => "payload_too_large",
169 AppError::TooManyRequests { .. } => "too_many_requests",
170 AppError::Db(_) => "db",
171 AppError::DbUnavailable => "db_unavailable",
172 AppError::DbTimeout => "db_timeout",
173 AppError::Internal(_) => "internal",
174 }
175 }
176
177 /// What a `5xx` log line says beyond its class — the underlying error, which
178 /// the arm's own `Display` hides (`AppError::Db` renders as "database
179 /// error", keeping the SDK's text out of the response body). `None` for
180 /// everything the caller caused: a `4xx` is not an incident and its message
181 /// is derived from what was sent.
182 fn detail(&self) -> Option<String> {
183 match self {
184 AppError::Db(e) => Some(e.to_string()),
185 AppError::Internal(m) => Some(m.clone()),
186 AppError::DbTimeout => Some("the write may or may not have applied".to_owned()),
187 _ => None,
188 }
189 }
190}
191
192impl IntoResponse for AppError {
193 fn into_response(self) -> Response {
194 let class = self.class();
195 let detail = self.detail();
196 let response = self.render();
197 let status = response.status();
198
199 // The request span carries the class; the route is already on the span
200 // and on every metric `measure` records, so the counter needs only the
201 // class and the status.
202 tracing::Span::current().record("error.type", class);
203 crate::telemetry::Metrics::global().errors_total.add(
204 1,
205 &[
206 opentelemetry::KeyValue::new("error.type", class),
207 opentelemetry::KeyValue::new(
208 "http.response.status_code",
209 i64::from(status.as_u16()),
210 ),
211 ],
212 );
213 let detail = detail.as_deref().unwrap_or("");
214 match status.as_u16() {
215 // Expected under load or during a reconnect: worth a line, not a page.
216 429 | 503 if class != "db_timeout" => {
217 tracing::warn!(error.type = class, "refused the request");
218 }
219 500..=599 => tracing::error!(error.type = class, "{detail}"),
220 // The caller's fault, and the loudest thing in the log if it were
221 // any higher: a bad request is not an incident.
222 _ => tracing::debug!(error.type = class, "refused the request"),
223 }
224 response
225 }
226}
227
228impl AppError {
229 /// The wire response, byte for byte what each arm has always answered.
230 fn render(self) -> Response {
231 let (status, message) = match &self {
232 // The one arm with an extra header, so it builds its response here.
233 AppError::TooManyRequests { retry_after_secs } => {
234 return (
235 StatusCode::TOO_MANY_REQUESTS,
236 [(header::RETRY_AFTER, retry_after_secs.to_string())],
237 Json(json!({ "error": "too many requests" })),
238 )
239 .into_response();
240 }
241 // Also carries a header: retry in a second, the reconnect is quick.
242 AppError::DbUnavailable => {
243 return (
244 StatusCode::SERVICE_UNAVAILABLE,
245 [(header::RETRY_AFTER, "1")],
246 Json(json!({ "error": "database reconnecting — retry shortly" })),
247 )
248 .into_response();
249 }
250 // Same 503, but no Retry-After: the query may still be queued and
251 // land later, so a blind retry is not advertised as safe.
252 AppError::DbTimeout => {
253 return (
254 StatusCode::SERVICE_UNAVAILABLE,
255 Json(json!({ "error": "request timed out — the write may or may not have applied" })),
256 )
257 .into_response();
258 }
259 // The one conflict with a second key, so it builds its body here.
260 AppError::ConflictCoded { code, message } => {
261 return (
262 StatusCode::CONFLICT,
263 Json(json!({ "error": message, "code": code })),
264 )
265 .into_response();
266 }
267 // Also carries a second key: which module was refused.
268 AppError::ModuleDisabled(module) => {
269 return (
270 StatusCode::FORBIDDEN,
271 Json(json!({ "error": "module disabled", "module": module.as_str() })),
272 )
273 .into_response();
274 }
275 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
276 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
277 AppError::Expired(m) => (StatusCode::GONE, m.to_string()),
278 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
279 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
280 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
281 AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
282 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
283 AppError::Db(_) => (
284 StatusCode::INTERNAL_SERVER_ERROR,
285 "database error".to_string(),
286 ),
287 AppError::Internal(_) => (
288 StatusCode::INTERNAL_SERVER_ERROR,
289 "internal server error".to_string(),
290 ),
291 };
292 (status, Json(json!({ "error": message }))).into_response()
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 /// The refusal a gated nest answers with. Both keys, and the `403` — a
301 /// client switches on `module`, so neither may drift.
302 #[tokio::test]
303 async fn a_disabled_module_is_a_403_naming_itself() {
304 use crate::module::Module;
305 let response = AppError::ModuleDisabled(Module::CourseNotes).into_response();
306 assert_eq!(response.status(), StatusCode::FORBIDDEN);
307 let body = axum::body::to_bytes(response.into_body(), 4096)
308 .await
309 .unwrap();
310 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
311 assert_eq!(body["error"], "module disabled");
312 assert_eq!(body["module"], "course_notes");
313 }
314
315 #[test]
316 fn sqlx_errors_split_into_honest_classes() {
317 use sqlx::Error;
318 // Pool problems refuse on the acquire path: nothing executed, so a
319 // retry is safe.
320 assert!(matches!(
321 AppError::from(Error::PoolTimedOut),
322 AppError::DbUnavailable
323 ));
324 assert!(matches!(
325 AppError::from(Error::PoolClosed),
326 AppError::DbUnavailable
327 ));
328 assert!(matches!(
329 AppError::from(Error::Tls("tls".into())),
330 AppError::DbUnavailable
331 ));
332 // A connection that died under a request: the honest 503 — the write
333 // may or may not have applied, so a retry is NOT advertised as safe.
334 let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone");
335 assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout));
336 // A query that found no row is the caller's 404, never a 500.
337 assert!(matches!(
338 AppError::from(Error::RowNotFound),
339 AppError::NotFound
340 ));
341 }
342}