forge
Explore
Log in

Don't you dare go Hollow

Retry boot connect, refuse while socket down

Browse files at this commit

bebca49f714a4a5a94ad2b19f815981b387eb7deAhmet Kaan GümüşParent: 6627128
  • fix
    • retry boot connect, refuse while socket down
Show full message
🐛 fix(db): retry boot connect, refuse while socket down

Two failures survived 6627128, which only classified errors from queries
in flight *at* the drop — queries arriving after it produce no error at
all, so there was nothing to classify.

Boot did one connect() and exited on refusal. The runtime then restarted
the process, it failed again in ~100ms, and a few seconds of startup skew
burned the whole restart budget: 6 deaths in 0.6s in the field log, then
down for 12h. Now retries 1s doubling to 5s, forever — only the dial,
since bad credentials never heal by waiting.

A query issued while the socket is down does not fail. The SDK's
router_reconnect loops on 1s retries and stops draining route_rx, so the
query parks until the database returns and only then executes. Reproduced:
POST /auth/login gave no response at 25s, and the keepalive went silent
4m17s before firing two pings in the same millisecond on heal.

Those two pings rule out a plain timeout middleware — a parked query still
runs, so a timeout-sourced 503 would let a client retry double-apply a
mark or an exam answer. Instead the keepalive (now 5s) publishes DbHealth
and db_guard refuses at the edge, before anything is queued, which is what
keeps Retry-After: 1 honest. The 30s request timeout is only a backstop
for requests racing detection; those answer DbTimeout — same 503, no
Retry-After, "may or may not have applied". WS and SSE are unaffected:
both return their response immediately and stream afterwards.

Known gap: exam_ws socket-loop queries run after the upgrade response, so
db_guard does not cover them; they still park and heal on reconnect.

Verified in podman against the existing volume: boot with the database
down backs off and stays alive, requests during an outage answer 503 in
0.3ms, recovery needs no restart.
README.mdmodified+23 -5
@@ -110,11 +110,29 @@ container so the published port works. Production knobs (`COOKIE_SECURE`,
110 means dev mirror mode without credentials; a cookie-using browser frontend110 means dev mirror mode without credentials; a cookie-using browser frontend
111 must be allowlisted explicitly. Works with `docker compose` too.111 must be allowlisted explicitly. Works with `docker compose` too.
112 112
113-The backend keeps its database WebSocket alive with a periodic trivial query,113+The backend survives the database going away, at boot and at runtime.
114-and the SDK reconnects on its own if the socket drops anyway (a `podman114+
115-restart hezarfen-surrealdb`, say). During that brief reconnect window requests115+At boot it retries the connection (1s doubling to 5s) until the server
116-answer `503` with `Retry-After: 1` instead of a `500` — the outage is116+answers, rather than exiting. Exiting looks tidier but is worse: the container
117-transient, so clients just retry a moment later.117+runtime restarts the process, it fails again in milliseconds, and a few
118+seconds of startup skew burns the whole restart budget and leaves the backend
119+down for good.
120+
121+At runtime a keepalive query every 5s doubles as a liveness probe. This
122+matters more than it sounds: a query issued while the socket is down does
123+*not* fail — the SDK's reconnect loop stops draining its request queue, so the
124+query parks until the database returns and only *then* runs. Left alone, a
125+request waits out the entire outage and any write it carries lands long after
126+the caller gave up.
127+
128+So while the probe says the socket is down, requests are refused at the edge
129+with `503` and `Retry-After: 1`, before they can reach the database. Nothing
130+is queued, which is what makes that retry safe. Requests that slip through in
131+the window between the socket dying and the probe noticing are capped at 30s
132+and answer `503` *without* `Retry-After`, with a message saying the write may
133+or may not have applied — they were already queued, so retrying them could
134+apply the same write twice. WebSocket and SSE routes are unaffected: both
135+return their response immediately and stream afterwards.
118 136
119 Without compose:137 Without compose:
120 138
src/constant.rsmodified+23 -2
@@ -150,8 +150,29 @@ pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2;
150 /// Cadence of the background keepalive query on the database WebSocket. The150 /// Cadence of the background keepalive query on the database WebSocket. The
151 /// traffic keeps the connection from being dropped as idle; when it does drop,151 /// traffic keeps the connection from being dropped as idle; when it does drop,
152 /// the ping also makes the SDK notice and reconnect long before the next real152 /// the ping also makes the SDK notice and reconnect long before the next real
153-/// request would.153+/// request would. Doubles as the liveness probe behind
154-pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 30;154+/// [`crate::state::DbHealth`], so this is also the widest window in which a
155+/// request can reach a socket already known-dead — keep it short.
156+pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 5;
157+
158+/// How long a keepalive ping may hang before the socket counts as down. The
159+/// SDK parks queries indefinitely while it reconnects (its retry loop stops
160+/// draining the request channel), so the ping needs its own deadline or the
161+/// probe hangs with everything else and never reports.
162+pub const DB_PING_TIMEOUT_SECS: u64 = 2;
163+
164+/// Ceiling on a single HTTP request. Backstop for requests that reached the
165+/// database in the window between the socket dying and the keepalive noticing:
166+/// without it they park until the database returns, which can be hours.
167+/// Generous enough not to clip a legitimate slow upload at `max_file_bytes`.
168+pub const REQUEST_TIMEOUT_SECS: u64 = 30;
169+
170+/// Backoff ceiling for the boot connection retry. The database is usually a
171+/// sibling container coming up in parallel, so the first attempts fail; the
172+/// process retries forever rather than exiting, because exiting turns a
173+/// few-second wait into a container restart loop that outruns its budget and
174+/// stays down.
175+pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
155 176
156 /// Cadence of the `state` ticks on the student exam-room WebSocket177 /// Cadence of the `state` ticks on the student exam-room WebSocket
157 /// (`GET /exams/{id}/attempt/ws`).178 /// (`GET /exams/{id}/attempt/ws`).
src/database.rsmodified+28 -1
@@ -327,7 +327,7 @@ const BACKFILL: &str = "
327 327
328 /// Connect to the SurrealDB server, sign in as root, and apply the schema.328 /// Connect to the SurrealDB server, sign in as root, and apply the schema.
329 pub async fn init(cfg: &Config) -> Result<Database, AppError> {329 pub async fn init(cfg: &Config) -> Result<Database, AppError> {
330- let db = surrealdb::engine::any::connect(cfg.db_url.clone()).await?;330+ let db = connect_with_retry(cfg).await;
331 db.signin(Root {331 db.signin(Root {
332 username: cfg.db_user.clone(),332 username: cfg.db_user.clone(),
333 password: cfg.db_pass.clone(),333 password: cfg.db_pass.clone(),
@@ -340,6 +340,33 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
340 Ok(db)340 Ok(db)
341 }341 }
342 342
343+/// Dial the database, retrying until it answers.
344+///
345+/// Never gives up, because giving up is worse than waiting: the database is
346+/// normally a sibling container booting in parallel, and a process that exits
347+/// on the first refusal gets restarted by the runtime, fails again in ~100ms,
348+/// and burns its whole restart budget inside a second — leaving the backend
349+/// permanently down over a startup skew that would have cleared on its own.
350+///
351+/// Only the dial is retried. Bad credentials or a broken migration still fail
352+/// hard, since no amount of waiting fixes those.
353+async fn connect_with_retry(cfg: &Config) -> Database {
354+ let mut backoff = 1;
355+ loop {
356+ match surrealdb::engine::any::connect(cfg.db_url.clone()).await {
357+ Ok(db) => return db,
358+ Err(err) => {
359+ tracing::warn!(
360+ "database at {} unreachable ({err}) — retrying in {backoff}s",
361+ cfg.db_url
362+ );
363+ tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
364+ backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS);
365+ }
366+ }
367+ }
368+}
369+
343 /// A fresh in-memory database with the schema applied. For tests.370 /// A fresh in-memory database with the schema applied. For tests.
344 pub async fn init_mem() -> Result<Database, AppError> {371 pub async fn init_mem() -> Result<Database, AppError> {
345 let db = surrealdb::engine::any::connect("memory").await?;372 let db = surrealdb::engine::any::connect("memory").await?;
src/error.rsmodified+21 -0
@@ -66,6 +66,17 @@ pub enum AppError {
66 /// self-healing, retryable.66 /// self-healing, retryable.
67 #[error("database unavailable")]67 #[error("database unavailable")]
68 DbUnavailable,68 DbUnavailable,
69+ /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in
70+ /// practice means it reached the database in the window between the socket
71+ /// dying and the keepalive noticing, and got parked in the SDK's queue.
72+ ///
73+ /// Deliberately NOT `DbUnavailable`: that one promises the query was
74+ /// refused before execution, so a retry is safe. A parked query is still
75+ /// queued and *does* execute once the socket heals (verified: pings
76+ /// abandoned during an outage all fire on reconnect), so retrying can
77+ /// apply the same write twice. Same 503, honest message.
78+ #[error("request timed out")]
79+ DbTimeout,
69 #[error("internal error: {0}")]80 #[error("internal error: {0}")]
70 Internal(String),81 Internal(String),
71 }82 }
@@ -121,6 +132,16 @@ impl IntoResponse for AppError {
121 )132 )
122 .into_response();133 .into_response();
123 }134 }
135+ // Same 503, but no Retry-After: the query may still be queued and
136+ // land later, so a blind retry is not advertised as safe.
137+ AppError::DbTimeout => {
138+ tracing::error!("request timed out waiting on the database");
139+ return (
140+ StatusCode::SERVICE_UNAVAILABLE,
141+ Json(json!({ "error": "request timed out — the write may or may not have applied" })),
142+ )
143+ .into_response();
144+ }
124 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),145 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
125 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),146 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
126 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),147 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
src/lib.rsmodified+36 -0
@@ -11,6 +11,7 @@ pub mod web;
11 use axum::extract::Request;11 use axum::extract::Request;
12 use axum::http::{HeaderValue, Method, header};12 use axum::http::{HeaderValue, Method, header};
13 use axum::middleware::{self, Next};13 use axum::middleware::{self, Next};
14+use axum::response::{IntoResponse, Response};
14 use axum::routing::get;15 use axum::routing::get;
15 use axum::{Json, Router};16 use axum::{Json, Router};
16 use serde_json::json;17 use serde_json::json;
@@ -22,6 +23,7 @@ use utoipa_axum::router::OpenApiRouter;
22 use utoipa_axum::routes;23 use utoipa_axum::routes;
23 use utoipa_swagger_ui::SwaggerUi;24 use utoipa_swagger_ui::SwaggerUi;
24 25
26+use crate::error::AppError;
25 use crate::rate_limit::RateLimiter;27 use crate::rate_limit::RateLimiter;
26 use crate::state::AppState;28 use crate::state::AppState;
27 29
@@ -107,6 +109,8 @@ pub fn build_router(state: AppState) -> Router {
107 state.rate_limit.trust_proxy,109 state.rate_limit.trust_proxy,
108 );110 );
109 111
112+ let db_up = state.db_up.clone();
113+
110 let cors_allowlist = cors_allowlist_from_env();114 let cors_allowlist = cors_allowlist_from_env();
111 if state.cookie_secure && cors_allowlist.is_empty() {115 if state.cookie_secure && cors_allowlist.is_empty() {
112 tracing::warn!(116 tracing::warn!(
@@ -117,6 +121,10 @@ pub fn build_router(state: AppState) -> Router {
117 router121 router
118 .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api))122 .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api))
119 .with_state(state)123 .with_state(state)
124+ .layer(middleware::from_fn(move |req: Request, next: Next| {
125+ let health = db_up.clone();
126+ async move { db_guard(health, req, next).await }
127+ }))
120 .layer(middleware::from_fn(move |req: Request, next: Next| {128 .layer(middleware::from_fn(move |req: Request, next: Next| {
121 let limiter = api_limiter.clone();129 let limiter = api_limiter.clone();
122 async move { limiter.enforce(req, next).await }130 async move { limiter.enforce(req, next).await }
@@ -125,6 +133,34 @@ pub fn build_router(state: AppState) -> Router {
125 .layer(TraceLayer::new_for_http())133 .layer(TraceLayer::new_for_http())
126 }134 }
127 135
136+/// Refuse work the database cannot currently do, and cap how long any request
137+/// may wait on it.
138+///
139+/// Both halves exist because a query issued while the database socket is down
140+/// never fails — the SDK parks it until the connection returns, so without a
141+/// guard a handler waits out the entire outage holding a connection open.
142+///
143+/// Order matters. The liveness check comes first and is the honest path: it
144+/// answers before the request touches the database, so nothing is queued and
145+/// the caller's retry cannot double-apply a write. The timeout only catches
146+/// requests that slipped through in the window between the socket dying and
147+/// the keepalive noticing — those are already queued, hence the weaker
148+/// [`AppError::DbTimeout`] verdict.
149+///
150+/// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream
151+/// both return their response immediately and do the work afterwards, so
152+/// neither is measured against the timeout.
153+async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response {
154+ if !health.is_up() {
155+ return AppError::DbUnavailable.into_response();
156+ }
157+ let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS);
158+ match tokio::time::timeout(timeout, next.run(req)).await {
159+ Ok(response) => response,
160+ Err(_) => AppError::DbTimeout.into_response(),
161+ }
162+}
163+
128 /// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset.164 /// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset.
129 fn cors_allowlist_from_env() -> Vec<HeaderValue> {165 fn cors_allowlist_from_env() -> Vec<HeaderValue> {
130 std::env::var("CORS_ALLOWED_ORIGINS")166 std::env::var("CORS_ALLOWED_ORIGINS")
src/main.rsmodified+32 -8
@@ -2,7 +2,7 @@ use anyhow::Context;
2 use hezarfen_backend::config::Config;2 use hezarfen_backend::config::Config;
3 use hezarfen_backend::database::Database;3 use hezarfen_backend::database::Database;
4 use hezarfen_backend::domain::user::{Password, User, Username};4 use hezarfen_backend::domain::user::{Password, User, Username};
5-use hezarfen_backend::state::AppState;5+use hezarfen_backend::state::{AppState, DbHealth};
6 use hezarfen_backend::{build_router, database};6 use hezarfen_backend::{build_router, database};
7 7
8 #[tokio::main]8 #[tokio::main]
@@ -18,7 +18,8 @@ async fn main() -> anyhow::Result<()> {
18 let cfg = Config::from_env();18 let cfg = Config::from_env();
19 let db = database::init(&cfg).await?;19 let db = database::init(&cfg).await?;
20 seed_admin(&cfg, &db).await?;20 seed_admin(&cfg, &db).await?;
21- keepalive(db.clone());21+ let db_up = DbHealth::default();
22+ keepalive(db.clone(), db_up.clone());
22 tokio::fs::create_dir_all(&cfg.files_path)23 tokio::fs::create_dir_all(&cfg.files_path)
23 .await24 .await
24 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;25 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;
@@ -28,6 +29,7 @@ async fn main() -> anyhow::Result<()> {
28 cookie_secure: cfg.cookie_secure,29 cookie_secure: cfg.cookie_secure,
29 rate_limit: cfg.rate_limit.clone(),30 rate_limit: cfg.rate_limit.clone(),
30 exam_presence: Default::default(),31 exam_presence: Default::default(),
32+ db_up,
31 });33 });
32 34
33 let addr = format!("{}:{}", cfg.host, cfg.port);35 let addr = format!("{}:{}", cfg.host, cfg.port);
@@ -46,19 +48,41 @@ async fn main() -> anyhow::Result<()> {
46 }48 }
47 49
48 /// Ping the database forever so the WebSocket never sits idle long enough to50 /// Ping the database forever so the WebSocket never sits idle long enough to
49-/// be dropped. A failed ping is the reconnect window itself — the SDK replays51+/// be dropped, and publish each verdict to `health` so the request guard can
50-/// the session and heals on its own — so it logs at debug, not error.52+/// refuse callers while the socket is down.
51-fn keepalive(db: Database) {53+///
54+/// The ping needs its own deadline. A query issued while the socket is down
55+/// does not fail — the SDK parks it until the connection returns, so an
56+/// un-deadlined ping hangs exactly as long as the outage and never reports the
57+/// outage it exists to detect.
58+fn keepalive(db: Database, health: DbHealth) {
52 tokio::spawn(async move {59 tokio::spawn(async move {
53 let mut interval = tokio::time::interval(std::time::Duration::from_secs(60 let mut interval = tokio::time::interval(std::time::Duration::from_secs(
54 hezarfen_backend::constant::DB_KEEPALIVE_INTERVAL_SECS,61 hezarfen_backend::constant::DB_KEEPALIVE_INTERVAL_SECS,
55 ));62 ));
56 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);63 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
64+ let ping_timeout = std::time::Duration::from_secs(
65+ hezarfen_backend::constant::DB_PING_TIMEOUT_SECS,
66+ );
57 loop {67 loop {
58 interval.tick().await;68 interval.tick().await;
59- match db.query("RETURN 1").await {69+ // ponytail: an abandoned ping stays queued in the SDK and replays
60- Ok(_) => tracing::debug!("database keepalive ping ok"),70+ // when the socket heals, so a long outage lands a burst of no-op
61- Err(err) => tracing::debug!("database keepalive ping failed: {err}"),71+ // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial
72+ // instead if that burst ever shows up in a profile.
73+ match tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await {
74+ Ok(Ok(_)) => {
75+ health.set(true);
76+ tracing::debug!("database keepalive ping ok");
77+ }
78+ Ok(Err(err)) => {
79+ health.set(false);
80+ tracing::debug!("database keepalive ping failed: {err}");
81+ }
82+ Err(_) => {
83+ health.set(false);
84+ tracing::debug!("database keepalive ping timed out");
85+ }
62 }86 }
63 }87 }
64 });88 });
src/state.rsmodified+42 -0
@@ -1,5 +1,6 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 use std::path::PathBuf;2 use std::path::PathBuf;
3+use std::sync::atomic::{AtomicBool, Ordering};
3 use std::sync::{Arc, Mutex};4 use std::sync::{Arc, Mutex};
4 5
5 use crate::database::Database;6 use crate::database::Database;
@@ -21,6 +22,47 @@ pub struct AppState {
21 pub rate_limit: RateLimitConfig,22 pub rate_limit: RateLimitConfig,
22 /// Who is inside which exam room right now (see [`ExamPresence`]).23 /// Who is inside which exam room right now (see [`ExamPresence`]).
23 pub exam_presence: ExamPresence,24 pub exam_presence: ExamPresence,
25+ /// Whether the database socket answered its last ping (see [`DbHealth`]).
26+ pub db_up: DbHealth,
27+}
28+
29+/// Last known state of the database WebSocket, published by the keepalive task
30+/// in `main` and read by the guard layer in [`crate::build_router`].
31+///
32+/// It exists because a query issued while the socket is down does not fail —
33+/// it hangs. The SDK's reconnect loop stops draining its request channel while
34+/// it retries, so the query is parked until the database returns, and *then*
35+/// executes. Refusing at the edge is what keeps a 503 honest: nothing was
36+/// queued, so the caller's retry cannot double-apply a write.
37+///
38+/// Starts up: `init` only returns once a connection and the migration
39+/// succeeded, so the first ping has nothing to correct.
40+#[derive(Clone)]
41+pub struct DbHealth(Arc<AtomicBool>);
42+
43+impl Default for DbHealth {
44+ fn default() -> Self {
45+ Self(Arc::new(AtomicBool::new(true)))
46+ }
47+}
48+
49+impl DbHealth {
50+ /// Did the last ping answer?
51+ pub fn is_up(&self) -> bool {
52+ self.0.load(Ordering::Relaxed)
53+ }
54+
55+ /// Publish the latest ping verdict, logging only the transitions — a long
56+ /// outage should not print a line every [`crate::constant::DB_KEEPALIVE_INTERVAL_SECS`].
57+ pub fn set(&self, up: bool) {
58+ if self.0.swap(up, Ordering::Relaxed) != up {
59+ if up {
60+ tracing::info!("database socket recovered — serving requests again");
61+ } else {
62+ tracing::error!("database socket down — refusing requests with 503");
63+ }
64+ }
65+ }
24 }66 }
25 67
26 /// How many exam-room sockets each attempt has open right now, keyed by the68 /// How many exam-room sockets each attempt has open right now, keyed by the
src/web/exam_ws.rsmodified+4 -0
@@ -440,6 +440,10 @@ fn error_frame(err: &AppError) -> Value {
440 tracing::warn!("exam room: database reconnecting");440 tracing::warn!("exam room: database reconnecting");
441 "database reconnecting — retry shortly".to_string()441 "database reconnecting — retry shortly".to_string()
442 }442 }
443+ AppError::DbTimeout => {
444+ tracing::error!("exam room: database timed out");
445+ "the database timed out — reload the room".to_string()
446+ }
443 AppError::Db(_) | AppError::Internal(_) => {447 AppError::Db(_) | AppError::Internal(_) => {
444 tracing::error!("exam room error: {err}");448 tracing::error!("exam room error: {err}");
445 "internal server error".to_string()449 "internal server error".to_string()
tests/common/mod.rsmodified+1 -0
@@ -48,6 +48,7 @@ pub async fn app_and_db() -> (Router, Database) {
48 // `rate_limit` test binary opts into tight configs on purpose.48 // `rate_limit` test binary opts into tight configs on purpose.
49 rate_limit: RateLimitConfig::unlimited(),49 rate_limit: RateLimitConfig::unlimited(),
50 exam_presence: Default::default(),50 exam_presence: Default::default(),
51+ db_up: Default::default(),
51 });52 });
52 (app, db)53 (app, db)
53 }54 }
tests/e2e.rsmodified+1 -0
@@ -23,6 +23,7 @@ async fn spawn_server() -> (String, Database) {
23 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.23 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
24 rate_limit: RateLimitConfig::unlimited(),24 rate_limit: RateLimitConfig::unlimited(),
25 exam_presence: Default::default(),25 exam_presence: Default::default(),
26+ db_up: Default::default(),
26 });27 });
27 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();28 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
28 let addr = listener.local_addr().unwrap();29 let addr = listener.local_addr().unwrap();
tests/integration.rsmodified+95 -0
@@ -4975,6 +4975,7 @@ async fn session_cookie_secure_attribute_follows_config() {
4975 cookie_secure: true,4975 cookie_secure: true,
4976 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),4976 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
4977 exam_presence: Default::default(),4977 exam_presence: Default::default(),
4978+ db_up: Default::default(),
4978 });4979 });
4979 let secure = login_set_cookie(&app).await;4980 let secure = login_set_cookie(&app).await;
4980 assert!(4981 assert!(
@@ -4987,6 +4988,100 @@ async fn session_cookie_secure_attribute_follows_config() {
4987 );4988 );
4988 }4989 }
4989 4990
4991+/// A query issued while the database socket is down does not fail — the SDK
4992+/// parks it until the connection returns and *then* runs it, so a handler that
4993+/// reaches the database mid-outage waits out the whole outage and any write it
4994+/// carries lands late. The guard layer refuses at the edge instead, before the
4995+/// request can touch the database, which is what makes the 503 safe to retry.
4996+#[tokio::test]
4997+async fn db_down_refuses_before_touching_the_database() {
4998+ async fn count_rows(db: &hezarfen_backend::database::Database, table: &str) -> usize {
4999+ let mut rows = db
5000+ .query(format!("SELECT id FROM {table}"))
5001+ .await
5002+ .expect("count query");
5003+ let ids: Vec<surrealdb::types::RecordId> = rows.take(0).expect("ids");
5004+ ids.len()
5005+ }
5006+
5007+ let db = database::init_mem().await.unwrap();
5008+ let db_up = hezarfen_backend::state::DbHealth::default();
5009+ let app = build_router(AppState {
5010+ db: db.clone(),
5011+ files_path: common::files_dir(),
5012+ cookie_secure: false,
5013+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
5014+ exam_presence: Default::default(),
5015+ db_up: db_up.clone(),
5016+ });
5017+
5018+ // Healthy: a login against the seeded user reaches the handler as usual.
5019+ let before: usize = count_rows(&db, "user").await;
5020+ let ok = app
5021+ .clone()
5022+ .oneshot(
5023+ Request::builder()
5024+ .method("POST")
5025+ .uri("/auth/register")
5026+ .header("content-type", "application/json")
5027+ .body(Body::from(
5028+ json!({"username": "gulsah", "password": "sifre12345"}).to_string(),
5029+ ))
5030+ .unwrap(),
5031+ )
5032+ .await
5033+ .unwrap();
5034+ assert_eq!(ok.status(), StatusCode::CREATED);
5035+ assert_eq!(count_rows(&db, "user").await, before + 1, "the write landed");
5036+
5037+ // Socket reported down: refused with a retryable 503, and — the point of
5038+ // refusing at the edge rather than timing out — nothing was written.
5039+ db_up.set(false);
5040+ let refused = app
5041+ .clone()
5042+ .oneshot(
5043+ Request::builder()
5044+ .method("POST")
5045+ .uri("/auth/register")
5046+ .header("content-type", "application/json")
5047+ .body(Body::from(
5048+ json!({"username": "kerem", "password": "sifre12345"}).to_string(),
5049+ ))
5050+ .unwrap(),
5051+ )
5052+ .await
5053+ .unwrap();
5054+ assert_eq!(refused.status(), StatusCode::SERVICE_UNAVAILABLE);
5055+ assert_eq!(
5056+ refused.headers().get("retry-after").unwrap(),
5057+ "1",
5058+ "a pre-execution refusal must advertise that retrying is safe"
5059+ );
5060+ assert_eq!(
5061+ count_rows(&db, "user").await,
5062+ before + 1,
5063+ "a refused request must not have reached the database"
5064+ );
5065+
5066+ // Recovery flips back without a restart.
5067+ db_up.set(true);
5068+ let healed = app
5069+ .oneshot(
5070+ Request::builder()
5071+ .method("POST")
5072+ .uri("/auth/register")
5073+ .header("content-type", "application/json")
5074+ .body(Body::from(
5075+ json!({"username": "kerem", "password": "sifre12345"}).to_string(),
5076+ ))
5077+ .unwrap(),
5078+ )
5079+ .await
5080+ .unwrap();
5081+ assert_eq!(healed.status(), StatusCode::CREATED);
5082+ assert_eq!(count_rows(&db, "user").await, before + 2);
5083+}
5084+
4990 /// Regression: PATCH could set an event's times but never clear them — a JSON5085 /// Regression: PATCH could set an event's times but never clear them — a JSON
4991 /// `null` was indistinguishable from an omitted field and silently kept the old5086 /// `null` was indistinguishable from an omitted field and silently kept the old
4992 /// value. An explicit `null` now clears the field; omitted still keeps it.5087 /// value. An explicit `null` now clears the field; omitted still keeps it.
tests/persistence.rsmodified+1 -0
@@ -25,6 +25,7 @@ async fn reboot(db: &Database) -> Router {
25 cookie_secure: false,25 cookie_secure: false,
26 rate_limit: RateLimitConfig::unlimited(),26 rate_limit: RateLimitConfig::unlimited(),
27 exam_presence: Default::default(),27 exam_presence: Default::default(),
28+ db_up: Default::default(),
28 })29 })
29 }30 }
30 31
tests/rate_limit.rsmodified+2 -0
@@ -25,6 +25,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
25 cookie_secure: false,25 cookie_secure: false,
26 rate_limit,26 rate_limit,
27 exam_presence: Default::default(),27 exam_presence: Default::default(),
28+ db_up: Default::default(),
28 })29 })
29 }30 }
30 31
@@ -316,6 +317,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
316 cookie_secure: false,317 cookie_secure: false,
317 rate_limit,318 rate_limit,
318 exam_presence: Default::default(),319 exam_presence: Default::default(),
320+ db_up: Default::default(),
319 });321 });
320 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();322 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
321 let addr = listener.local_addr().unwrap();323 let addr = listener.local_addr().unwrap();