forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBcd6bccfAhmet Kaan Gümüş4 months ago177 commits

error.rs213 lines, 8.4 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}
14
15/// Why a newtype refused to be constructed from raw input. Always maps to `400`.
16#[derive(Debug, thiserror::Error)]
17pub enum ValidationError {
18 #[error("{0} must not be empty")]
19 Empty(&'static str),
20 #[error("{field} must be at least {min} characters (got {got})")]
21 TooShort {
22 field: &'static str,
23 min: usize,
24 got: usize,
25 },
26 #[error("{field} must be at most {max} characters (got {got})")]
27 TooLong {
28 field: &'static str,
29 max: usize,
30 got: usize,
31 },
32 #[error("{0} must be ASCII")]
33 NotAscii(&'static str),
34 #[error("{field}: {reason}")]
35 Invalid {
36 field: &'static str,
37 reason: &'static str,
38 },
39}
40
41/// The single error type every fallible operation returns.
42#[derive(Debug, thiserror::Error)]
43pub enum AppError {
44 #[error(transparent)]
45 Validation(#[from] ValidationError),
46 #[error("not found")]
47 NotFound,
48 #[error("unauthorized")]
49 Unauthorized,
50 #[error("forbidden: {0}")]
51 Forbidden(&'static str),
52 #[error("conflict: {0}")]
53 Conflict(&'static str),
54 /// A 409 whose message is only known at runtime — e.g. the specific
55 /// students a homework's narrowed `assigned` list would orphan. Owned
56 /// string, like [`AppError::PayloadTooLarge`]; static conflicts use
57 /// [`AppError::Conflict`].
58 #[error("conflict: {0}")]
59 ConflictOwned(String),
60 /// A request body (file upload) over the allowed size. Owned string: the
61 /// school-configured limit is only known at runtime.
62 #[error("payload too large: {0}")]
63 PayloadTooLarge(String),
64 #[error("too many requests")]
65 TooManyRequests { retry_after_secs: u64 },
66 #[error("database error")]
67 Db(#[source] surrealdb::Error),
68 /// The database WebSocket dropped and is mid-reconnect. Covers a query in
69 /// flight when the socket died (the SDK fails it as a connection error)
70 /// and a query racing the SDK's replay of session state (signin,
71 /// namespace), which the server refuses before execution. Transient,
72 /// self-healing, retryable.
73 #[error("database unavailable")]
74 DbUnavailable,
75 /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in
76 /// practice means it reached the database in the window between the socket
77 /// dying and the keepalive noticing, and got parked in the SDK's queue.
78 ///
79 /// Deliberately NOT `DbUnavailable`: that one promises the query was
80 /// refused before execution, so a retry is safe. A parked query is still
81 /// queued and *does* execute once the socket heals (verified: pings
82 /// abandoned during an outage all fire on reconnect), so retrying can
83 /// apply the same write twice. Same 503, honest message.
84 #[error("request timed out")]
85 DbTimeout,
86 #[error("internal error: {0}")]
87 Internal(String),
88}
89
90/// Is this database error a query refused during the SDK's post-reconnect
91/// session replay? Two signatures, matched narrowly: "Specify a namespace"
92/// (signin replayed, namespace not yet) and "Anonymous access not allowed"
93/// (signin not yet). The backend signs in as root, so neither can be a real
94/// authorization verdict — but a bare "Not enough permissions" could be, so
95/// that alone must never match.
96pub(crate) fn is_session_replay_error(message: &str) -> bool {
97 message.contains("Specify a namespace") || message.contains("Anonymous access not allowed")
98}
99
100impl From<surrealdb::Error> for AppError {
101 fn from(e: surrealdb::Error) -> Self {
102 // `is_connection()`: the SDK's own verdict that the socket itself
103 // failed ("Connection reset", "WebSocket error: ..."). Structurally
104 // distinct from query/permission errors, so it can't misfile one.
105 if e.is_connection() || is_session_replay_error(&e.to_string()) {
106 AppError::DbUnavailable
107 } else {
108 AppError::Db(e)
109 }
110 }
111}
112
113impl From<argon2::password_hash::Error> for AppError {
114 fn from(e: argon2::password_hash::Error) -> Self {
115 AppError::Internal(format!("password hashing error: {e}"))
116 }
117}
118
119impl IntoResponse for AppError {
120 fn into_response(self) -> Response {
121 let (status, message) = match &self {
122 // The one arm with an extra header, so it builds its response here.
123 AppError::TooManyRequests { retry_after_secs } => {
124 return (
125 StatusCode::TOO_MANY_REQUESTS,
126 [(header::RETRY_AFTER, retry_after_secs.to_string())],
127 Json(json!({ "error": "too many requests" })),
128 )
129 .into_response();
130 }
131 // Also carries a header: retry in a second, the reconnect is quick.
132 AppError::DbUnavailable => {
133 tracing::warn!("database reconnecting — refusing the query with 503");
134 return (
135 StatusCode::SERVICE_UNAVAILABLE,
136 [(header::RETRY_AFTER, "1")],
137 Json(json!({ "error": "database reconnecting — retry shortly" })),
138 )
139 .into_response();
140 }
141 // Same 503, but no Retry-After: the query may still be queued and
142 // land later, so a blind retry is not advertised as safe.
143 AppError::DbTimeout => {
144 tracing::error!("request timed out waiting on the database");
145 return (
146 StatusCode::SERVICE_UNAVAILABLE,
147 Json(json!({ "error": "request timed out — the write may or may not have applied" })),
148 )
149 .into_response();
150 }
151 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
152 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
153 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
154 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
155 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
156 AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
157 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
158 AppError::Db(e) => {
159 tracing::error!("database error: {e}");
160 (
161 StatusCode::INTERNAL_SERVER_ERROR,
162 "database error".to_string(),
163 )
164 }
165 AppError::Internal(m) => {
166 tracing::error!("internal error: {m}");
167 (
168 StatusCode::INTERNAL_SERVER_ERROR,
169 "internal server error".to_string(),
170 )
171 }
172 };
173 (status, Json(json!({ "error": message }))).into_response()
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn replay_signatures_classify_as_unavailable() {
183 // The two exact refusals a query racing the post-reconnect session
184 // replay gets, as they appear in the wire error.
185 assert!(is_session_replay_error("Specify a namespace to use"));
186 assert!(is_session_replay_error(
187 "Anonymous access not allowed: Not enough permissions to perform this action"
188 ));
189 }
190
191 #[test]
192 fn connection_errors_classify_as_unavailable() {
193 // What the SDK fails an in-flight query with when the socket dies —
194 // same wire error `clear_pending_requests` produces.
195 let e = surrealdb::Error::connection(
196 "Connection reset".to_string(),
197 surrealdb::types::ConnectionError::ConnectionFailed,
198 );
199 assert!(matches!(AppError::from(e), AppError::DbUnavailable));
200 }
201
202 #[test]
203 fn real_errors_stay_db_errors() {
204 // A genuine authorization verdict shares the suffix but must not match.
205 assert!(!is_session_replay_error(
206 "Not enough permissions to perform this action"
207 ));
208 assert!(!is_session_replay_error("Parse error: unexpected token"));
209 assert!(!is_session_replay_error(
210 "Database index `user_username` already contains 'admin'"
211 ));
212 }
213}