forge
Explore
Log in

Don't you dare go Hollow

Share one session, stop cloning the handle per request

Browse files at this commit

11fa250f1bc6454728277cc7f8f6b09c5a3c601fAhmet Kaan GümüşParent: 5ff771b
  • fix
    • share one session, stop cloning the handle per request
Show full message
🐛 fix(db): share one session, stop cloning the handle per request

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<Any>` 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<Surreal<Any>>` 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.rsmodified+19 -5
@@ -7,7 +7,21 @@ use surrealdb::opt::auth::Root;
7 use crate::config::Config;7 use crate::config::Config;
8 use crate::error::AppError;8 use crate::error::AppError;
9 9
10-pub type Database = Surreal<Any>;10+/// The shared database handle.
11+///
12+/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a
13+/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget
14+/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the
15+/// application state on every request — so a bare `Surreal<Any>` here means a
16+/// new session, and a matching `SessionId::Drop`, for each request served.
17+/// Under concurrency those lifecycle events race the queries riding on them:
18+/// sessions disappear ("Session not found"), and a session whose signin has
19+/// not been replayed answers "Anonymous access not allowed" / "Specify a
20+/// namespace" — the same strings [`crate::error::is_session_replay_error`]
21+/// treats as a transient reconnect, so the failures masquerade as one.
22+///
23+/// Cloning the `Arc` shares the single session established at boot instead.
24+pub type Database = std::sync::Arc<Surreal<Any>>;
11 25
12 pub const USER_TABLE: &str = "user";26 pub const USER_TABLE: &str = "user";
13 pub const SESSION_TABLE: &str = "session";27 pub const SESSION_TABLE: &str = "session";
@@ -343,7 +357,7 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
343 .use_db(cfg.db_name.clone())357 .use_db(cfg.db_name.clone())
344 .await?;358 .await?;
345 migrate(&db).await?;359 migrate(&db).await?;
346- Ok(db)360+ Ok(std::sync::Arc::new(db))
347 }361 }
348 362
349 /// Dial the database, retrying until it answers.363 /// Dial the database, retrying until it answers.
@@ -356,7 +370,7 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
356 ///370 ///
357 /// Only the dial is retried. Bad credentials or a broken migration still fail371 /// Only the dial is retried. Bad credentials or a broken migration still fail
358 /// hard, since no amount of waiting fixes those.372 /// hard, since no amount of waiting fixes those.
359-async fn connect_with_retry(cfg: &Config) -> Database {373+async fn connect_with_retry(cfg: &Config) -> Surreal<Any> {
360 let mut backoff = 1;374 let mut backoff = 1;
361 loop {375 loop {
362 match surrealdb::engine::any::connect(cfg.db_url.clone()).await {376 match surrealdb::engine::any::connect(cfg.db_url.clone()).await {
@@ -378,12 +392,12 @@ pub async fn init_mem() -> Result<Database, AppError> {
378 let db = surrealdb::engine::any::connect("memory").await?;392 let db = surrealdb::engine::any::connect("memory").await?;
379 db.use_ns("hezarfen").use_db("hezarfen").await?;393 db.use_ns("hezarfen").use_db("hezarfen").await?;
380 migrate(&db).await?;394 migrate(&db).await?;
381- Ok(db)395+ Ok(std::sync::Arc::new(db))
382 }396 }
383 397
384 /// Apply the schema + backfills. Idempotent — `init` runs it on every boot,398 /// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
385 /// and tests re-run it on a live handle to simulate a second boot.399 /// and tests re-run it on a live handle to simulate a second boot.
386-pub async fn migrate(db: &Database) -> Result<(), AppError> {400+pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
387 db.query(MIGRATION).await?.check()?;401 db.query(MIGRATION).await?.check()?;
388 db.query(BACKFILL).await?.check()?;402 db.query(BACKFILL).await?.check()?;
389 Ok(())403 Ok(())