From 11fa250f1bc6454728277cc7f8f6b09c5a3c601f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 21 Jul 2026 20:16:38 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(db):=20share=20one=20session?= =?UTF-8?q?,=20stop=20cloning=20the=20handle=20per=20request?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The database was never reconnecting. `Surreal`'s own `Clone` mints a fresh server-side session — `Uuid::new_v4()` plus a fire-and-forget `SessionId::Clone` to the router (SDK lib.rs:340) — and axum clones the application state on every request, so `db: Surreal` in `AppState` meant a new session, and a matching `SessionId::Drop`, per request served. Under concurrency those lifecycle events race the queries riding on them. Sessions vanish outright ("Session not found", surfaced as a 500), and a session whose signin has not been replayed yet answers "Anonymous access not allowed" / "Specify a namespace" — the exact strings `is_session_replay_error` attributes to a post-reconnect replay. So the failures were reported as a transient reconnect and a retryable 503, which is why the field logs showed sporadic 503s while the keepalive pinged `ok` every 5s without a single miss. A healthy socket the whole time. `Arc>` shares the one session established at boot; cloning the state is now a refcount bump. `Deref` covers all 175 call sites unchanged. Same storm, 200 logins at 40 parallel, before → after: 23×200 / 16×500 / 161×503 → 200×200, zero "Session not found" 600 at 80 parallel also clean. The classifier is left alone: with the churn gone those two strings can only come from a real post-reconnect replay, which is what it was for. --- src/database.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/database.rs b/src/database.rs index 8fa90be..14bc162 100644 --- a/src/database.rs +++ b/src/database.rs @@ -7,7 +7,21 @@ use surrealdb::opt::auth::Root; use crate::config::Config; use crate::error::AppError; -pub type Database = Surreal; +/// The shared database handle. +/// +/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a +/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget +/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the +/// application state on every request — so a bare `Surreal` here means a +/// new session, and a matching `SessionId::Drop`, for each request served. +/// Under concurrency those lifecycle events race the queries riding on them: +/// sessions disappear ("Session not found"), and a session whose signin has +/// not been replayed answers "Anonymous access not allowed" / "Specify a +/// namespace" — the same strings [`crate::error::is_session_replay_error`] +/// treats as a transient reconnect, so the failures masquerade as one. +/// +/// Cloning the `Arc` shares the single session established at boot instead. +pub type Database = std::sync::Arc>; pub const USER_TABLE: &str = "user"; pub const SESSION_TABLE: &str = "session"; @@ -343,7 +357,7 @@ pub async fn init(cfg: &Config) -> Result { .use_db(cfg.db_name.clone()) .await?; migrate(&db).await?; - Ok(db) + Ok(std::sync::Arc::new(db)) } /// Dial the database, retrying until it answers. @@ -356,7 +370,7 @@ pub async fn init(cfg: &Config) -> Result { /// /// 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 { +async fn connect_with_retry(cfg: &Config) -> Surreal { let mut backoff = 1; loop { match surrealdb::engine::any::connect(cfg.db_url.clone()).await { @@ -378,12 +392,12 @@ pub async fn init_mem() -> Result { let db = surrealdb::engine::any::connect("memory").await?; db.use_ns("hezarfen").use_db("hezarfen").await?; migrate(&db).await?; - Ok(db) + Ok(std::sync::Arc::new(db)) } /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, /// and tests re-run it on a live handle to simulate a second boot. -pub async fn migrate(db: &Database) -> Result<(), AppError> { +pub async fn migrate(db: &Surreal) -> Result<(), AppError> { db.query(MIGRATION).await?.check()?; db.query(BACKFILL).await?.check()?; Ok(())