hezarfen_backend
Clone
https://git.tahinli.com/archive/hezarfen_backend.git
0 watching·0 forks·Rust·8.3 MiB·0346717·Ahmet Kaan Gümüş·3 months ago·230 commits
| 1 | use axum::Json; |
| 2 | use axum::http::{StatusCode, header}; |
| 3 | use axum::response::{IntoResponse, Response}; |
| 4 | use serde::Serialize; |
| 5 | use serde_json::json; |
| 6 | use utoipa::ToSchema; |
| 7 | |
| 8 | /// Uniform error body shape (`{ "error": "..." }`) used for OpenAPI docs. |
| 9 | #[derive(Serialize, ToSchema)] |
| 10 | pub 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)] |
| 23 | pub 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 | } |
| 46 | |
| 47 | /// The single error type every fallible operation returns. |
| 48 | #[derive(Debug, thiserror::Error)] |
| 49 | pub enum AppError { |
| 50 | #[error(transparent)] |
| 51 | Validation(#[from] ValidationError), |
| 52 | #[error("not found")] |
| 53 | NotFound, |
| 54 | #[error("unauthorized")] |
| 55 | Unauthorized, |
| 56 | #[error("forbidden: {0}")] |
| 57 | Forbidden(&'static str), |
| 58 | #[error("conflict: {0}")] |
| 59 | Conflict(&'static str), |
| 60 | /// A 409 whose message is only known at runtime — e.g. the specific |
| 61 | /// students a homework's narrowed `assigned` list would orphan. Owned |
| 62 | /// string, like [`AppError::PayloadTooLarge`]; static conflicts use |
| 63 | /// [`AppError::Conflict`]. |
| 64 | #[error("conflict: {0}")] |
| 65 | ConflictOwned(String), |
| 66 | /// A 409 that also carries a **machine code**, so a client branches on the |
| 67 | /// cause instead of parsing the sentence (which it cannot translate). The |
| 68 | /// prose is unchanged from what the same refusal always said — `code` is |
| 69 | /// additive, and only a route that publishes its vocabulary uses this. |
| 70 | #[error("conflict: {message}")] |
| 71 | ConflictCoded { code: &'static str, message: String }, |
| 72 | /// A request body (file upload) over the allowed size. Owned string: the |
| 73 | /// school-configured limit is only known at runtime. |
| 74 | #[error("payload too large: {0}")] |
| 75 | PayloadTooLarge(String), |
| 76 | #[error("too many requests")] |
| 77 | TooManyRequests { retry_after_secs: u64 }, |
| 78 | #[error("database error")] |
| 79 | Db(#[source] surrealdb::Error), |
| 80 | /// The database WebSocket dropped and is mid-reconnect. Covers a query in |
| 81 | /// flight when the socket died (the SDK fails it as a connection error) |
| 82 | /// and a query racing the SDK's replay of session state (signin, |
| 83 | /// namespace), which the server refuses before execution. Transient, |
| 84 | /// self-healing, retryable. |
| 85 | #[error("database unavailable")] |
| 86 | DbUnavailable, |
| 87 | /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in |
| 88 | /// practice means it reached the database in the window between the socket |
| 89 | /// dying and the keepalive noticing, and got parked in the SDK's queue. |
| 90 | /// |
| 91 | /// Deliberately NOT `DbUnavailable`: that one promises the query was |
| 92 | /// refused before execution, so a retry is safe. A parked query is still |
| 93 | /// queued and *does* execute once the socket heals (verified: pings |
| 94 | /// abandoned during an outage all fire on reconnect), so retrying can |
| 95 | /// apply the same write twice. Same 503, honest message. |
| 96 | #[error("request timed out")] |
| 97 | DbTimeout, |
| 98 | #[error("internal error: {0}")] |
| 99 | Internal(String), |
| 100 | } |
| 101 | |
| 102 | /// Is this database error a query refused during the SDK's post-reconnect |
| 103 | /// session replay? Two signatures, matched narrowly: "Specify a namespace" |
| 104 | /// (signin replayed, namespace not yet) and "Anonymous access not allowed" |
| 105 | /// (signin not yet). The backend signs in as root, so neither can be a real |
| 106 | /// authorization verdict — but a bare "Not enough permissions" could be, so |
| 107 | /// that alone must never match. |
| 108 | pub(crate) fn is_session_replay_error(message: &str) -> bool { |
| 109 | message.contains("Specify a namespace") || message.contains("Anonymous access not allowed") |
| 110 | } |
| 111 | |
| 112 | impl From<surrealdb::Error> for AppError { |
| 113 | fn from(e: surrealdb::Error) -> Self { |
| 114 | // `is_connection()`: the SDK's own verdict that the socket itself |
| 115 | // failed ("Connection reset", "WebSocket error: ..."). Structurally |
| 116 | // distinct from query/permission errors, so it can't misfile one. |
| 117 | if e.is_connection() || is_session_replay_error(&e.to_string()) { |
| 118 | AppError::DbUnavailable |
| 119 | } else { |
| 120 | AppError::Db(e) |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl From<argon2::password_hash::Error> for AppError { |
| 126 | fn from(e: argon2::password_hash::Error) -> Self { |
| 127 | AppError::Internal(format!("password hashing error: {e}")) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | impl IntoResponse for AppError { |
| 132 | fn into_response(self) -> Response { |
| 133 | let (status, message) = match &self { |
| 134 | // The one arm with an extra header, so it builds its response here. |
| 135 | AppError::TooManyRequests { retry_after_secs } => { |
| 136 | return ( |
| 137 | StatusCode::TOO_MANY_REQUESTS, |
| 138 | [(header::RETRY_AFTER, retry_after_secs.to_string())], |
| 139 | Json(json!({ "error": "too many requests" })), |
| 140 | ) |
| 141 | .into_response(); |
| 142 | } |
| 143 | // Also carries a header: retry in a second, the reconnect is quick. |
| 144 | AppError::DbUnavailable => { |
| 145 | tracing::warn!("database reconnecting — refusing the query with 503"); |
| 146 | return ( |
| 147 | StatusCode::SERVICE_UNAVAILABLE, |
| 148 | [(header::RETRY_AFTER, "1")], |
| 149 | Json(json!({ "error": "database reconnecting — retry shortly" })), |
| 150 | ) |
| 151 | .into_response(); |
| 152 | } |
| 153 | // Same 503, but no Retry-After: the query may still be queued and |
| 154 | // land later, so a blind retry is not advertised as safe. |
| 155 | AppError::DbTimeout => { |
| 156 | tracing::error!("request timed out waiting on the database"); |
| 157 | return ( |
| 158 | StatusCode::SERVICE_UNAVAILABLE, |
| 159 | Json(json!({ "error": "request timed out — the write may or may not have applied" })), |
| 160 | ) |
| 161 | .into_response(); |
| 162 | } |
| 163 | // The one conflict with a second key, so it builds its body here. |
| 164 | AppError::ConflictCoded { code, message } => { |
| 165 | return ( |
| 166 | StatusCode::CONFLICT, |
| 167 | Json(json!({ "error": message, "code": code })), |
| 168 | ) |
| 169 | .into_response(); |
| 170 | } |
| 171 | AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), |
| 172 | AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), |
| 173 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), |
| 174 | AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), |
| 175 | AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), |
| 176 | AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()), |
| 177 | AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()), |
| 178 | AppError::Db(e) => { |
| 179 | tracing::error!("database error: {e}"); |
| 180 | ( |
| 181 | StatusCode::INTERNAL_SERVER_ERROR, |
| 182 | "database error".to_string(), |
| 183 | ) |
| 184 | } |
| 185 | AppError::Internal(m) => { |
| 186 | tracing::error!("internal error: {m}"); |
| 187 | ( |
| 188 | StatusCode::INTERNAL_SERVER_ERROR, |
| 189 | "internal server error".to_string(), |
| 190 | ) |
| 191 | } |
| 192 | }; |
| 193 | (status, Json(json!({ "error": message }))).into_response() |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | #[cfg(test)] |
| 198 | mod tests { |
| 199 | use super::*; |
| 200 | |
| 201 | #[test] |
| 202 | fn replay_signatures_classify_as_unavailable() { |
| 203 | // The two exact refusals a query racing the post-reconnect session |
| 204 | // replay gets, as they appear in the wire error. |
| 205 | assert!(is_session_replay_error("Specify a namespace to use")); |
| 206 | assert!(is_session_replay_error( |
| 207 | "Anonymous access not allowed: Not enough permissions to perform this action" |
| 208 | )); |
| 209 | } |
| 210 | |
| 211 | #[test] |
| 212 | fn connection_errors_classify_as_unavailable() { |
| 213 | // What the SDK fails an in-flight query with when the socket dies — |
| 214 | // same wire error `clear_pending_requests` produces. |
| 215 | let e = surrealdb::Error::connection( |
| 216 | "Connection reset".to_string(), |
| 217 | surrealdb::types::ConnectionError::ConnectionFailed, |
| 218 | ); |
| 219 | assert!(matches!(AppError::from(e), AppError::DbUnavailable)); |
| 220 | } |
| 221 | |
| 222 | #[test] |
| 223 | fn real_errors_stay_db_errors() { |
| 224 | // A genuine authorization verdict shares the suffix but must not match. |
| 225 | assert!(!is_session_replay_error( |
| 226 | "Not enough permissions to perform this action" |
| 227 | )); |
| 228 | assert!(!is_session_replay_error("Parse error: unexpected token")); |
| 229 | assert!(!is_session_replay_error( |
| 230 | "Database index `user_username` already contains 'admin'" |
| 231 | )); |
| 232 | } |
| 233 | } |