diff --git a/README.md b/README.md index b62f05b..b251cdf 100644 --- a/README.md +++ b/README.md @@ -110,11 +110,29 @@ container so the published port works. Production knobs (`COOKIE_SECURE`, means dev mirror mode without credentials; a cookie-using browser frontend must be allowlisted explicitly. Works with `docker compose` too. -The backend keeps its database WebSocket alive with a periodic trivial query, -and the SDK reconnects on its own if the socket drops anyway (a `podman -restart hezarfen-surrealdb`, say). During that brief reconnect window requests -answer `503` with `Retry-After: 1` instead of a `500` — the outage is -transient, so clients just retry a moment later. +The backend survives the database going away, at boot and at runtime. + +At boot it retries the connection (1s doubling to 5s) until the server +answers, rather than exiting. Exiting looks tidier but is worse: the container +runtime restarts the process, it fails again in milliseconds, and a few +seconds of startup skew burns the whole restart budget and leaves the backend +down for good. + +At runtime a keepalive query every 5s doubles as a liveness probe. This +matters more than it sounds: a query issued while the socket is down does +*not* fail — the SDK's reconnect loop stops draining its request queue, so the +query parks until the database returns and only *then* runs. Left alone, a +request waits out the entire outage and any write it carries lands long after +the caller gave up. + +So while the probe says the socket is down, requests are refused at the edge +with `503` and `Retry-After: 1`, before they can reach the database. Nothing +is queued, which is what makes that retry safe. Requests that slip through in +the window between the socket dying and the probe noticing are capped at 30s +and answer `503` *without* `Retry-After`, with a message saying the write may +or may not have applied — they were already queued, so retrying them could +apply the same write twice. WebSocket and SSE routes are unaffected: both +return their response immediately and stream afterwards. Without compose: diff --git a/src/constant.rs b/src/constant.rs index b72627b..f110b7d 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -150,8 +150,29 @@ pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; /// Cadence of the background keepalive query on the database WebSocket. The /// traffic keeps the connection from being dropped as idle; when it does drop, /// the ping also makes the SDK notice and reconnect long before the next real -/// request would. -pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 30; +/// request would. Doubles as the liveness probe behind +/// [`crate::state::DbHealth`], so this is also the widest window in which a +/// request can reach a socket already known-dead — keep it short. +pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 5; + +/// How long a keepalive ping may hang before the socket counts as down. The +/// SDK parks queries indefinitely while it reconnects (its retry loop stops +/// draining the request channel), so the ping needs its own deadline or the +/// probe hangs with everything else and never reports. +pub const DB_PING_TIMEOUT_SECS: u64 = 2; + +/// Ceiling on a single HTTP request. Backstop for requests that reached the +/// database in the window between the socket dying and the keepalive noticing: +/// without it they park until the database returns, which can be hours. +/// Generous enough not to clip a legitimate slow upload at `max_file_bytes`. +pub const REQUEST_TIMEOUT_SECS: u64 = 30; + +/// Backoff ceiling for the boot connection retry. The database is usually a +/// sibling container coming up in parallel, so the first attempts fail; the +/// process retries forever rather than exiting, because exiting turns a +/// few-second wait into a container restart loop that outruns its budget and +/// stays down. +pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5; /// Cadence of the `state` ticks on the student exam-room WebSocket /// (`GET /exams/{id}/attempt/ws`). diff --git a/src/database.rs b/src/database.rs index 9c4f68e..026bac0 100644 --- a/src/database.rs +++ b/src/database.rs @@ -327,7 +327,7 @@ const BACKFILL: &str = " /// Connect to the SurrealDB server, sign in as root, and apply the schema. pub async fn init(cfg: &Config) -> Result { - let db = surrealdb::engine::any::connect(cfg.db_url.clone()).await?; + let db = connect_with_retry(cfg).await; db.signin(Root { username: cfg.db_user.clone(), password: cfg.db_pass.clone(), @@ -340,6 +340,33 @@ pub async fn init(cfg: &Config) -> Result { Ok(db) } +/// Dial the database, retrying until it answers. +/// +/// Never gives up, because giving up is worse than waiting: the database is +/// normally a sibling container booting in parallel, and a process that exits +/// on the first refusal gets restarted by the runtime, fails again in ~100ms, +/// and burns its whole restart budget inside a second — leaving the backend +/// permanently down over a startup skew that would have cleared on its own. +/// +/// Only the dial is retried. Bad credentials or a broken migration still fail +/// hard, since no amount of waiting fixes those. +async fn connect_with_retry(cfg: &Config) -> Database { + let mut backoff = 1; + loop { + match surrealdb::engine::any::connect(cfg.db_url.clone()).await { + Ok(db) => return db, + Err(err) => { + tracing::warn!( + "database at {} unreachable ({err}) — retrying in {backoff}s", + cfg.db_url + ); + tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; + backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS); + } + } + } +} + /// A fresh in-memory database with the schema applied. For tests. pub async fn init_mem() -> Result { let db = surrealdb::engine::any::connect("memory").await?; diff --git a/src/error.rs b/src/error.rs index 7729a04..eb672bd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -66,6 +66,17 @@ pub enum AppError { /// self-healing, retryable. #[error("database unavailable")] DbUnavailable, + /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in + /// practice means it reached the database in the window between the socket + /// dying and the keepalive noticing, and got parked in the SDK's queue. + /// + /// Deliberately NOT `DbUnavailable`: that one promises the query was + /// refused before execution, so a retry is safe. A parked query is still + /// queued and *does* execute once the socket heals (verified: pings + /// abandoned during an outage all fire on reconnect), so retrying can + /// apply the same write twice. Same 503, honest message. + #[error("request timed out")] + DbTimeout, #[error("internal error: {0}")] Internal(String), } @@ -121,6 +132,16 @@ impl IntoResponse for AppError { ) .into_response(); } + // Same 503, but no Retry-After: the query may still be queued and + // land later, so a blind retry is not advertised as safe. + AppError::DbTimeout => { + tracing::error!("request timed out waiting on the database"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({ "error": "request timed out — the write may or may not have applied" })), + ) + .into_response(); + } AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), diff --git a/src/lib.rs b/src/lib.rs index b9ad7b6..993e5f2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod web; use axum::extract::Request; use axum::http::{HeaderValue, Method, header}; use axum::middleware::{self, Next}; +use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::{Json, Router}; use serde_json::json; @@ -22,6 +23,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use utoipa_swagger_ui::SwaggerUi; +use crate::error::AppError; use crate::rate_limit::RateLimiter; use crate::state::AppState; @@ -107,6 +109,8 @@ pub fn build_router(state: AppState) -> Router { state.rate_limit.trust_proxy, ); + let db_up = state.db_up.clone(); + let cors_allowlist = cors_allowlist_from_env(); if state.cookie_secure && cors_allowlist.is_empty() { tracing::warn!( @@ -117,6 +121,10 @@ pub fn build_router(state: AppState) -> Router { router .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) .with_state(state) + .layer(middleware::from_fn(move |req: Request, next: Next| { + let health = db_up.clone(); + async move { db_guard(health, req, next).await } + })) .layer(middleware::from_fn(move |req: Request, next: Next| { let limiter = api_limiter.clone(); async move { limiter.enforce(req, next).await } @@ -125,6 +133,34 @@ pub fn build_router(state: AppState) -> Router { .layer(TraceLayer::new_for_http()) } +/// Refuse work the database cannot currently do, and cap how long any request +/// may wait on it. +/// +/// Both halves exist because a query issued while the database socket is down +/// never fails — the SDK parks it until the connection returns, so without a +/// guard a handler waits out the entire outage holding a connection open. +/// +/// Order matters. The liveness check comes first and is the honest path: it +/// answers before the request touches the database, so nothing is queued and +/// the caller's retry cannot double-apply a write. The timeout only catches +/// requests that slipped through in the window between the socket dying and +/// the keepalive noticing — those are already queued, hence the weaker +/// [`AppError::DbTimeout`] verdict. +/// +/// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream +/// both return their response immediately and do the work afterwards, so +/// neither is measured against the timeout. +async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response { + if !health.is_up() { + return AppError::DbUnavailable.into_response(); + } + let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS); + match tokio::time::timeout(timeout, next.run(req)).await { + Ok(response) => response, + Err(_) => AppError::DbTimeout.into_response(), + } +} + /// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset. fn cors_allowlist_from_env() -> Vec { std::env::var("CORS_ALLOWED_ORIGINS") diff --git a/src/main.rs b/src/main.rs index 2e52744..fdbbe8f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ use anyhow::Context; use hezarfen_backend::config::Config; use hezarfen_backend::database::Database; use hezarfen_backend::domain::user::{Password, User, Username}; -use hezarfen_backend::state::AppState; +use hezarfen_backend::state::{AppState, DbHealth}; use hezarfen_backend::{build_router, database}; #[tokio::main] @@ -18,7 +18,8 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::from_env(); let db = database::init(&cfg).await?; seed_admin(&cfg, &db).await?; - keepalive(db.clone()); + let db_up = DbHealth::default(); + keepalive(db.clone(), db_up.clone()); tokio::fs::create_dir_all(&cfg.files_path) .await .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; @@ -28,6 +29,7 @@ async fn main() -> anyhow::Result<()> { cookie_secure: cfg.cookie_secure, rate_limit: cfg.rate_limit.clone(), exam_presence: Default::default(), + db_up, }); let addr = format!("{}:{}", cfg.host, cfg.port); @@ -46,19 +48,41 @@ async fn main() -> anyhow::Result<()> { } /// Ping the database forever so the WebSocket never sits idle long enough to -/// be dropped. A failed ping is the reconnect window itself — the SDK replays -/// the session and heals on its own — so it logs at debug, not error. -fn keepalive(db: Database) { +/// be dropped, and publish each verdict to `health` so the request guard can +/// refuse callers while the socket is down. +/// +/// The ping needs its own deadline. A query issued while the socket is down +/// does not fail — the SDK parks it until the connection returns, so an +/// un-deadlined ping hangs exactly as long as the outage and never reports the +/// outage it exists to detect. +fn keepalive(db: Database, health: DbHealth) { tokio::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs( hezarfen_backend::constant::DB_KEEPALIVE_INTERVAL_SECS, )); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let ping_timeout = std::time::Duration::from_secs( + hezarfen_backend::constant::DB_PING_TIMEOUT_SECS, + ); loop { interval.tick().await; - match db.query("RETURN 1").await { - Ok(_) => tracing::debug!("database keepalive ping ok"), - Err(err) => tracing::debug!("database keepalive ping failed: {err}"), + // ponytail: an abandoned ping stays queued in the SDK and replays + // when the socket heals, so a long outage lands a burst of no-op + // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial + // instead if that burst ever shows up in a profile. + match tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await { + Ok(Ok(_)) => { + health.set(true); + tracing::debug!("database keepalive ping ok"); + } + Ok(Err(err)) => { + health.set(false); + tracing::debug!("database keepalive ping failed: {err}"); + } + Err(_) => { + health.set(false); + tracing::debug!("database keepalive ping timed out"); + } } } }); diff --git a/src/state.rs b/src/state.rs index cd5bf54..cff070d 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use crate::database::Database; @@ -21,6 +22,47 @@ pub struct AppState { pub rate_limit: RateLimitConfig, /// Who is inside which exam room right now (see [`ExamPresence`]). pub exam_presence: ExamPresence, + /// Whether the database socket answered its last ping (see [`DbHealth`]). + pub db_up: DbHealth, +} + +/// Last known state of the database WebSocket, published by the keepalive task +/// in `main` and read by the guard layer in [`crate::build_router`]. +/// +/// It exists because a query issued while the socket is down does not fail — +/// it hangs. The SDK's reconnect loop stops draining its request channel while +/// it retries, so the query is parked until the database returns, and *then* +/// executes. Refusing at the edge is what keeps a 503 honest: nothing was +/// queued, so the caller's retry cannot double-apply a write. +/// +/// Starts up: `init` only returns once a connection and the migration +/// succeeded, so the first ping has nothing to correct. +#[derive(Clone)] +pub struct DbHealth(Arc); + +impl Default for DbHealth { + fn default() -> Self { + Self(Arc::new(AtomicBool::new(true))) + } +} + +impl DbHealth { + /// Did the last ping answer? + pub fn is_up(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + /// Publish the latest ping verdict, logging only the transitions — a long + /// outage should not print a line every [`crate::constant::DB_KEEPALIVE_INTERVAL_SECS`]. + pub fn set(&self, up: bool) { + if self.0.swap(up, Ordering::Relaxed) != up { + if up { + tracing::info!("database socket recovered — serving requests again"); + } else { + tracing::error!("database socket down — refusing requests with 503"); + } + } + } } /// How many exam-room sockets each attempt has open right now, keyed by the diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 8e907d8..1134d0e 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -440,6 +440,10 @@ fn error_frame(err: &AppError) -> Value { tracing::warn!("exam room: database reconnecting"); "database reconnecting — retry shortly".to_string() } + AppError::DbTimeout => { + tracing::error!("exam room: database timed out"); + "the database timed out — reload the room".to_string() + } AppError::Db(_) | AppError::Internal(_) => { tracing::error!("exam room error: {err}"); "internal server error".to_string() diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 31afef2..798d266 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -48,6 +48,7 @@ pub async fn app_and_db() -> (Router, Database) { // `rate_limit` test binary opts into tight configs on purpose. rate_limit: RateLimitConfig::unlimited(), exam_presence: Default::default(), + db_up: Default::default(), }); (app, db) } diff --git a/tests/e2e.rs b/tests/e2e.rs index 9c62b68..a16c744 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -23,6 +23,7 @@ async fn spawn_server() -> (String, Database) { // meter the whole suite as one client. Off; `rate_limit.rs` covers it. rate_limit: RateLimitConfig::unlimited(), exam_presence: Default::default(), + db_up: Default::default(), }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); diff --git a/tests/integration.rs b/tests/integration.rs index d72ee3d..db3984e 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4975,6 +4975,7 @@ async fn session_cookie_secure_attribute_follows_config() { cookie_secure: true, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), exam_presence: Default::default(), + db_up: Default::default(), }); let secure = login_set_cookie(&app).await; assert!( @@ -4987,6 +4988,100 @@ async fn session_cookie_secure_attribute_follows_config() { ); } +/// A query issued while the database socket is down does not fail — the SDK +/// parks it until the connection returns and *then* runs it, so a handler that +/// reaches the database mid-outage waits out the whole outage and any write it +/// carries lands late. The guard layer refuses at the edge instead, before the +/// request can touch the database, which is what makes the 503 safe to retry. +#[tokio::test] +async fn db_down_refuses_before_touching_the_database() { + async fn count_rows(db: &hezarfen_backend::database::Database, table: &str) -> usize { + let mut rows = db + .query(format!("SELECT id FROM {table}")) + .await + .expect("count query"); + let ids: Vec = rows.take(0).expect("ids"); + ids.len() + } + + let db = database::init_mem().await.unwrap(); + let db_up = hezarfen_backend::state::DbHealth::default(); + let app = build_router(AppState { + db: db.clone(), + files_path: common::files_dir(), + cookie_secure: false, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + exam_presence: Default::default(), + db_up: db_up.clone(), + }); + + // Healthy: a login against the seeded user reaches the handler as usual. + let before: usize = count_rows(&db, "user").await; + let ok = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/auth/register") + .header("content-type", "application/json") + .body(Body::from( + json!({"username": "gulsah", "password": "sifre12345"}).to_string(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(ok.status(), StatusCode::CREATED); + assert_eq!(count_rows(&db, "user").await, before + 1, "the write landed"); + + // Socket reported down: refused with a retryable 503, and — the point of + // refusing at the edge rather than timing out — nothing was written. + db_up.set(false); + let refused = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/auth/register") + .header("content-type", "application/json") + .body(Body::from( + json!({"username": "kerem", "password": "sifre12345"}).to_string(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(refused.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + refused.headers().get("retry-after").unwrap(), + "1", + "a pre-execution refusal must advertise that retrying is safe" + ); + assert_eq!( + count_rows(&db, "user").await, + before + 1, + "a refused request must not have reached the database" + ); + + // Recovery flips back without a restart. + db_up.set(true); + let healed = app + .oneshot( + Request::builder() + .method("POST") + .uri("/auth/register") + .header("content-type", "application/json") + .body(Body::from( + json!({"username": "kerem", "password": "sifre12345"}).to_string(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(healed.status(), StatusCode::CREATED); + assert_eq!(count_rows(&db, "user").await, before + 2); +} + /// Regression: PATCH could set an event's times but never clear them — a JSON /// `null` was indistinguishable from an omitted field and silently kept the old /// value. An explicit `null` now clears the field; omitted still keeps it. diff --git a/tests/persistence.rs b/tests/persistence.rs index ca052f4..690e242 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -25,6 +25,7 @@ async fn reboot(db: &Database) -> Router { cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), exam_presence: Default::default(), + db_up: Default::default(), }) } diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 0ed1f7e..017c8a1 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -25,6 +25,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { cookie_secure: false, rate_limit, exam_presence: Default::default(), + db_up: Default::default(), }) } @@ -316,6 +317,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { cookie_secure: false, rate_limit, exam_presence: Default::default(), + db_up: Default::default(), }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap();