forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 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
118
119impl From<sqlx::Error> for AppError {
120 fn from(e: sqlx::Error) -> Self {
121 match e {
122 // A `fetch_one` that found nothing is the caller's 404, not a 500.
123 sqlx::Error::RowNotFound => AppError::NotFound,
124 // Pool problems refuse on the acquire path: nothing was queued,
125 // let alone executed, so a retry cannot double-apply a write.
126 sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Tls(_) => {
127 AppError::DbUnavailable
128 }
129 // A connection that died under a request. The statement may or
130 // may not have applied — the honest, retry-unsafe 503.
131 sqlx::Error::Io(_) => AppError::DbTimeout,
132 // Everything else is a verdict (or a bug) the server returned —
133 // refusals included; the helpers in [`crate::database`] read the
134 // SQLSTATE off it.
135 _ => AppError::Db(e),
136 }
137 }
138}
139
140impl From<argon2::password_hash::Error> for AppError {
141 fn from(e: argon2::password_hash::Error) -> Self {
142 AppError::Internal(format!("password hashing error: {e}"))
143 }
144}
145
146impl AppError {
147 /// The stable, snake_case name of this refusal's *class* — the value of the
148 /// `error.type` attribute on the span and on `errors_total`. It is a
149 /// dashboard's grouping key, so it never carries anything from the request:
150 /// no field name, no id, no message. Rename an arm freely; never rename one
151 /// of these strings.
152 fn class(&self) -> &'static str {
153 match self {
154 AppError::Validation(_) => "validation",
155 AppError::NotFound => "not_found",
156 AppError::Unauthorized => "unauthorized",
157 AppError::Forbidden(_) => "forbidden",
158 AppError::ModuleDisabled(_) => "module_disabled",
159 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
160 AppError::ConflictCoded { .. } => "conflict_coded",
161 AppError::PayloadTooLarge(_) => "payload_too_large",
162 AppError::TooManyRequests { .. } => "too_many_requests",
163 AppError::Db(_) => "db",
164 AppError::DbUnavailable => "db_unavailable",
165 AppError::DbTimeout => "db_timeout",
166 AppError::Internal(_) => "internal",
167 }
168 }
169
170 /// What a `5xx` log line says beyond its class — the underlying error, which
171 /// the arm's own `Display` hides (`AppError::Db` renders as "database
172 /// error", keeping the SDK's text out of the response body). `None` for
173 /// everything the caller caused: a `4xx` is not an incident and its message
174 /// is derived from what was sent.
175 fn detail(&self) -> Option<String> {
176 match self {
177 AppError::Db(e) => Some(e.to_string()),
178 AppError::Internal(m) => Some(m.clone()),
179 AppError::DbTimeout => Some("the write may or may not have applied".to_owned()),
180 _ => None,
181 }
182 }
183}
184
185impl IntoResponse for AppError {
186 fn into_response(self) -> Response {
187 let class = self.class();
188 let detail = self.detail();
189 let response = self.render();
190 let status = response.status();
191
192 // The request span carries the class; the route is already on the span
193 // and on every metric `measure` records, so the counter needs only the
194 // class and the status.
195 tracing::Span::current().record("error.type", class);
196 crate::telemetry::Metrics::global().errors_total.add(
197 1,
198 &[
199 opentelemetry::KeyValue::new("error.type", class),
200 opentelemetry::KeyValue::new(
201 "http.response.status_code",
202 i64::from(status.as_u16()),
203 ),
204 ],
205 );
206 let detail = detail.as_deref().unwrap_or("");
207 match status.as_u16() {
208 // Expected under load or during a reconnect: worth a line, not a page.
209 429 | 503 if class != "db_timeout" => {
210 tracing::warn!(error.type = class, "refused the request");
211 }
212 500..=599 => tracing::error!(error.type = class, "{detail}"),
213 // The caller's fault, and the loudest thing in the log if it were
214 // any higher: a bad request is not an incident.
215 _ => tracing::debug!(error.type = class, "refused the request"),
216 }
217 response
218 }
219}
220
221impl AppError {
222 /// The wire response, byte for byte what each arm has always answered.
223 fn render(self) -> Response {
224 let (status, message) = match &self {
225 // The one arm with an extra header, so it builds its response here.
226 AppError::TooManyRequests { retry_after_secs } => {
227 return (
228 StatusCode::TOO_MANY_REQUESTS,
229 [(header::RETRY_AFTER, retry_after_secs.to_string())],
230 Json(json!({ "error": "too many requests" })),
231 )
232 .into_response();
233 }
234 // Also carries a header: retry in a second, the reconnect is quick.
235 AppError::DbUnavailable => {
236 return (
237 StatusCode::SERVICE_UNAVAILABLE,
238 [(header::RETRY_AFTER, "1")],
239 Json(json!({ "error": "database reconnecting — retry shortly" })),
240 )
241 .into_response();
242 }
243 // Same 503, but no Retry-After: the query may still be queued and
244 // land later, so a blind retry is not advertised as safe.
245 AppError::DbTimeout => {
246 return (
247 StatusCode::SERVICE_UNAVAILABLE,
248 Json(json!({ "error": "request timed out — the write may or may not have applied" })),
249 )
250 .into_response();
251 }
252 // The one conflict with a second key, so it builds its body here.
253 AppError::ConflictCoded { code, message } => {
254 return (
255 StatusCode::CONFLICT,
256 Json(json!({ "error": message, "code": code })),
257 )
258 .into_response();
259 }
260 // Also carries a second key: which module was refused.
261 AppError::ModuleDisabled(module) => {
262 return (
263 StatusCode::FORBIDDEN,
264 Json(json!({ "error": "module disabled", "module": module.as_str() })),
265 )
266 .into_response();
267 }
268 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
269 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
270 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
271 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
272 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
273 AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
274 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
275 AppError::Db(_) => (
276 StatusCode::INTERNAL_SERVER_ERROR,
277 "database error".to_string(),
278 ),
279 AppError::Internal(_) => (
280 StatusCode::INTERNAL_SERVER_ERROR,
281 "internal server error".to_string(),
282 ),
283 };
284 (status, Json(json!({ "error": message }))).into_response()
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292
293 /// The refusal a gated nest answers with. Both keys, and the `403` — a
294 /// client switches on `module`, so neither may drift.
295 #[tokio::test]
296 async fn a_disabled_module_is_a_403_naming_itself() {
297 use crate::module::Module;
298 let response = AppError::ModuleDisabled(Module::CourseNotes).into_response();
299 assert_eq!(response.status(), StatusCode::FORBIDDEN);
300 let body = axum::body::to_bytes(response.into_body(), 4096)
301 .await
302 .unwrap();
303 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
304 assert_eq!(body["error"], "module disabled");
305 assert_eq!(body["module"], "course_notes");
306 }
307
308 #[test]
309 fn sqlx_errors_split_into_honest_classes() {
310 use sqlx::Error;
311 // Pool problems refuse on the acquire path: nothing executed, so a
312 // retry is safe.
313 assert!(matches!(
314 AppError::from(Error::PoolTimedOut),
315 AppError::DbUnavailable
316 ));
317 assert!(matches!(
318 AppError::from(Error::PoolClosed),
319 AppError::DbUnavailable
320 ));
321 assert!(matches!(
322 AppError::from(Error::Tls("tls".into())),
323 AppError::DbUnavailable
324 ));
325 // A connection that died under a request: the honest 503 — the write
326 // may or may not have applied, so a retry is NOT advertised as safe.
327 let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone");
328 assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout));
329 // A query that found no row is the caller's 404, never a 500.
330 assert!(matches!(AppError::from(Error::RowNotFound), AppError::NotFound));
331 }
332
333}