forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBe2d0e43Ahmet Kaan Gümüş2 months ago397 commits

error.rs341 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 #[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] surrealdb::Error),
97 /// The database WebSocket dropped and is mid-reconnect. Covers a query in
98 /// flight when the socket died (the SDK fails it as a connection error)
99 /// and a query racing the SDK's replay of session state (signin,
100 /// namespace), which the server refuses before execution. Transient,
101 /// self-healing, retryable.
102 #[error("database unavailable")]
103 DbUnavailable,
104 /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in
105 /// practice means it reached the database in the window between the socket
106 /// dying and the keepalive noticing, and got parked in the SDK's queue.
107 ///
108 /// Deliberately NOT `DbUnavailable`: that one promises the query was
109 /// refused before execution, so a retry is safe. A parked query is still
110 /// queued and *does* execute once the socket heals (verified: pings
111 /// abandoned during an outage all fire on reconnect), so retrying can
112 /// apply the same write twice. Same 503, honest message.
113 #[error("request timed out")]
114 DbTimeout,
115 #[error("internal error: {0}")]
116 Internal(String),
117}
118
119/// Is this database error a query refused during the SDK's post-reconnect
120/// session replay? Two signatures, matched narrowly: "Specify a namespace"
121/// (signin replayed, namespace not yet) and "Anonymous access not allowed"
122/// (signin not yet). The backend signs in as root, so neither can be a real
123/// authorization verdict — but a bare "Not enough permissions" could be, so
124/// that alone must never match.
125pub(crate) fn is_session_replay_error(message: &str) -> bool {
126 message.contains("Specify a namespace") || message.contains("Anonymous access not allowed")
127}
128
129impl From<surrealdb::Error> for AppError {
130 fn from(e: surrealdb::Error) -> Self {
131 // `is_connection()`: the SDK's own verdict that the socket itself
132 // failed ("Connection reset", "WebSocket error: ..."). Structurally
133 // distinct from query/permission errors, so it can't misfile one.
134 if e.is_connection() || is_session_replay_error(&e.to_string()) {
135 AppError::DbUnavailable
136 } else {
137 AppError::Db(e)
138 }
139 }
140}
141
142impl From<argon2::password_hash::Error> for AppError {
143 fn from(e: argon2::password_hash::Error) -> Self {
144 AppError::Internal(format!("password hashing error: {e}"))
145 }
146}
147
148impl AppError {
149 /// The stable, snake_case name of this refusal's *class* — the value of the
150 /// `error.type` attribute on the span and on `errors_total`. It is a
151 /// dashboard's grouping key, so it never carries anything from the request:
152 /// no field name, no id, no message. Rename an arm freely; never rename one
153 /// of these strings.
154 fn class(&self) -> &'static str {
155 match self {
156 AppError::Validation(_) => "validation",
157 AppError::NotFound => "not_found",
158 AppError::Unauthorized => "unauthorized",
159 AppError::Forbidden(_) => "forbidden",
160 AppError::ModuleDisabled(_) => "module_disabled",
161 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
162 AppError::ConflictCoded { .. } => "conflict_coded",
163 AppError::PayloadTooLarge(_) => "payload_too_large",
164 AppError::TooManyRequests { .. } => "too_many_requests",
165 AppError::Db(_) => "db",
166 AppError::DbUnavailable => "db_unavailable",
167 AppError::DbTimeout => "db_timeout",
168 AppError::Internal(_) => "internal",
169 }
170 }
171
172 /// What a `5xx` log line says beyond its class — the underlying error, which
173 /// the arm's own `Display` hides (`AppError::Db` renders as "database
174 /// error", keeping the SDK's text out of the response body). `None` for
175 /// everything the caller caused: a `4xx` is not an incident and its message
176 /// is derived from what was sent.
177 fn detail(&self) -> Option<String> {
178 match self {
179 AppError::Db(e) => Some(e.to_string()),
180 AppError::Internal(m) => Some(m.clone()),
181 AppError::DbTimeout => Some("the write may or may not have applied".to_owned()),
182 _ => None,
183 }
184 }
185}
186
187impl IntoResponse for AppError {
188 fn into_response(self) -> Response {
189 let class = self.class();
190 let detail = self.detail();
191 let response = self.render();
192 let status = response.status();
193
194 // The request span carries the class; the route is already on the span
195 // and on every metric `measure` records, so the counter needs only the
196 // class and the status.
197 tracing::Span::current().record("error.type", class);
198 crate::telemetry::Metrics::global().errors_total.add(
199 1,
200 &[
201 opentelemetry::KeyValue::new("error.type", class),
202 opentelemetry::KeyValue::new(
203 "http.response.status_code",
204 i64::from(status.as_u16()),
205 ),
206 ],
207 );
208 let detail = detail.as_deref().unwrap_or("");
209 match status.as_u16() {
210 // Expected under load or during a reconnect: worth a line, not a page.
211 429 | 503 if class != "db_timeout" => {
212 tracing::warn!(error.type = class, "refused the request");
213 }
214 500..=599 => tracing::error!(error.type = class, "{detail}"),
215 // The caller's fault, and the loudest thing in the log if it were
216 // any higher: a bad request is not an incident.
217 _ => tracing::debug!(error.type = class, "refused the request"),
218 }
219 response
220 }
221}
222
223impl AppError {
224 /// The wire response, byte for byte what each arm has always answered.
225 fn render(self) -> Response {
226 let (status, message) = match &self {
227 // The one arm with an extra header, so it builds its response here.
228 AppError::TooManyRequests { retry_after_secs } => {
229 return (
230 StatusCode::TOO_MANY_REQUESTS,
231 [(header::RETRY_AFTER, retry_after_secs.to_string())],
232 Json(json!({ "error": "too many requests" })),
233 )
234 .into_response();
235 }
236 // Also carries a header: retry in a second, the reconnect is quick.
237 AppError::DbUnavailable => {
238 return (
239 StatusCode::SERVICE_UNAVAILABLE,
240 [(header::RETRY_AFTER, "1")],
241 Json(json!({ "error": "database reconnecting — retry shortly" })),
242 )
243 .into_response();
244 }
245 // Same 503, but no Retry-After: the query may still be queued and
246 // land later, so a blind retry is not advertised as safe.
247 AppError::DbTimeout => {
248 return (
249 StatusCode::SERVICE_UNAVAILABLE,
250 Json(json!({ "error": "request timed out — the write may or may not have applied" })),
251 )
252 .into_response();
253 }
254 // The one conflict with a second key, so it builds its body here.
255 AppError::ConflictCoded { code, message } => {
256 return (
257 StatusCode::CONFLICT,
258 Json(json!({ "error": message, "code": code })),
259 )
260 .into_response();
261 }
262 // Also carries a second key: which module was refused.
263 AppError::ModuleDisabled(module) => {
264 return (
265 StatusCode::FORBIDDEN,
266 Json(json!({ "error": "module disabled", "module": module.as_str() })),
267 )
268 .into_response();
269 }
270 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
271 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
272 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
273 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
274 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
275 AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
276 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
277 AppError::Db(_) => (
278 StatusCode::INTERNAL_SERVER_ERROR,
279 "database error".to_string(),
280 ),
281 AppError::Internal(_) => (
282 StatusCode::INTERNAL_SERVER_ERROR,
283 "internal server error".to_string(),
284 ),
285 };
286 (status, Json(json!({ "error": message }))).into_response()
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 #[test]
295 fn replay_signatures_classify_as_unavailable() {
296 // The two exact refusals a query racing the post-reconnect session
297 // replay gets, as they appear in the wire error.
298 assert!(is_session_replay_error("Specify a namespace to use"));
299 assert!(is_session_replay_error(
300 "Anonymous access not allowed: Not enough permissions to perform this action"
301 ));
302 }
303
304 #[test]
305 fn connection_errors_classify_as_unavailable() {
306 // What the SDK fails an in-flight query with when the socket dies —
307 // same wire error `clear_pending_requests` produces.
308 let e = surrealdb::Error::connection(
309 "Connection reset".to_string(),
310 surrealdb::types::ConnectionError::ConnectionFailed,
311 );
312 assert!(matches!(AppError::from(e), AppError::DbUnavailable));
313 }
314
315 /// The refusal a gated nest answers with. Both keys, and the `403` — a
316 /// client switches on `module`, so neither may drift.
317 #[tokio::test]
318 async fn a_disabled_module_is_a_403_naming_itself() {
319 use crate::module::Module;
320 let response = AppError::ModuleDisabled(Module::CourseNotes).into_response();
321 assert_eq!(response.status(), StatusCode::FORBIDDEN);
322 let body = axum::body::to_bytes(response.into_body(), 4096)
323 .await
324 .unwrap();
325 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
326 assert_eq!(body["error"], "module disabled");
327 assert_eq!(body["module"], "course_notes");
328 }
329
330 #[test]
331 fn real_errors_stay_db_errors() {
332 // A genuine authorization verdict shares the suffix but must not match.
333 assert!(!is_session_replay_error(
334 "Not enough permissions to perform this action"
335 ));
336 assert!(!is_session_replay_error("Parse error: unexpected token"));
337 assert!(!is_session_replay_error(
338 "Database index `user_username` already contains 'admin'"
339 ));
340 }
341}