From 18e1b7bc01666d6c39033ce8d76efa8a00181e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 17:06:54 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20test:=20postgres=20test=20harnes?= =?UTF-8?q?s=20(per-test=20databases)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/database.rs | 446 ++++++++++++++++++++++++++++++++++++++++++-- src/tenant.rs | 52 +++++- tests/common/mod.rs | 246 +++++++----------------- 3 files changed, 542 insertions(+), 202 deletions(-) diff --git a/src/database.rs b/src/database.rs index db98891..6d600e1 100644 --- a/src/database.rs +++ b/src/database.rs @@ -10,19 +10,24 @@ //! Their table names are disjoint by design, which is what lets one prepare //! database carry the union for the compile-time `query!` checks. +use std::collections::HashSet; use std::path::Path; +use std::sync::{Arc, LazyLock, Mutex}; use std::time::Duration; +use sha2::{Digest, Sha256}; +use sqlx::PgPool; use sqlx::migrate::{MigrateError, Migrator}; use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions}; -use sqlx::PgPool; +use uuid::Uuid; use crate::config::Config; use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{Password, Username}; use crate::error::AppError; -use crate::tenant::Tenants; +use crate::module::ModuleSet; +use crate::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants, school_db_name}; /// The shared database handle. /// @@ -84,7 +89,10 @@ pub async fn init(cfg: &Config) -> Result { /// the name every school database hangs off (`{control}_school_{slug}`). pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> { let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| { - AppError::Internal(format!("invalid DATABASE_URL ({}): {err}", cfg.database_url)) + AppError::Internal(format!( + "invalid DATABASE_URL ({}): {err}", + cfg.database_url + )) })?; let db = opts .get_database() @@ -112,7 +120,10 @@ fn pool_options(max_connections: u32) -> PgPoolOptions { /// A pool over one school database with the school pool sizing. The schema is /// the caller's business — [`migrate_school`] for a mint, nothing for a /// re-dial of an existing school. -pub(crate) async fn school_pool(base: &PgConnectOptions, db_name: &str) -> Result { +pub(crate) async fn school_pool( + base: &PgConnectOptions, + db_name: &str, +) -> Result { pool_options(4) .connect_with(base.clone().database(db_name)) .await @@ -225,17 +236,21 @@ async fn ensure_template( base: &PgConnectOptions, name: &str, ) -> Result<(), AppError> { - if let Err(err) = - sqlx::query(sqlx::AssertSqlSafe(create_database_sql("CREATE DATABASE", name))) - .execute(control) - .await + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( + "CREATE DATABASE", + name, + ))) + .execute(control) + .await { if !is_duplicate_database(&err) { return Err(err.into()); } } // One migrator connection, made and closed: the template is never served. - let pool = pool_options(1).connect_with(base.clone().database(name)).await?; + let pool = pool_options(1) + .connect_with(base.clone().database(name)) + .await?; let migrated = migrate_school(&pool).await; pool.close().await; migrated @@ -348,9 +363,9 @@ where Err(err) => return Err(err), } } - Err(last.map(AppError::Db).unwrap_or_else(|| { - AppError::Internal("a guarded transaction never ran".into()) - })) + Err(last + .map(AppError::Db) + .unwrap_or_else(|| AppError::Internal("a guarded transaction never ran".into()))) } fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool { @@ -392,6 +407,412 @@ fn builder_credentials(cfg: &Config) -> Result, App } } +// ---- per-test databases ----------------------------------------------------- +// +// Every test run gets a **private pair of databases** on the compose Postgres: +// a control database and the demo school's database, both named after one +// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_demo` — so +// nextest's parallel processes neither collide nor see each other's rows. The +// school schema is not migrated per test: it is cloned from a shared template +// database whose name carries a hash of `migrations/school`, so a schema edit +// mints a fresh template exactly once and every test after that pays only a +// cheap `CREATE DATABASE … TEMPLATE`. +// +// Cleanup is a lease: every database a deployment minted is recorded in a +// [`TestDatabases`], and its `Drop` — fired when the deployment's last handle +// dies — sends `DROP DATABASE … WITH (FORCE)`. A best-effort janitor at first +// use per process sweeps what a crashed run left behind: only databases past +// a minimum age are candidates, and their `DROP` carries no `WITH (FORCE)`, +// so a live parallel test's databases (connected backends, young name) are +// never touched. +// +// These functions are `pub` rather than `#[cfg(test)]` because the +// integration tests live outside the crate, and `#[doc(hidden)]` because they +// are not part of the API. Their SQL is runtime-checked — the query-style +// rule exempts all test-side SQL from the macros. + +/// The Postgres server the test databases are minted on. The default is the +/// compose stack's maintenance database (`.env.example` documents it). +const TEST_DATABASE_URL_ENV: &str = "HEZARFEN_TEST_DATABASE_URL"; +const TEST_DATABASE_URL_DEFAULT: &str = "postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres"; + +/// Every test database carries this prefix; the janitor only ever drops +/// databases it names. +const TEST_DB_PREFIX: &str = "heztest_"; + +/// How old a `heztest_%` database must be before the janitor will touch it. +/// Anything younger belongs to a test in a parallel process — nextest mints +/// them by the dozen in overlapping seconds. +const TEST_DB_LEFTOVER_MIN_AGE_MS: i64 = 5 * 60 * 1000; + +/// The advisory-lock key the template's create-and-migrate critical section +/// holds (see [`ensure_test_template`]). An arbitrary constant — it only has +/// to be one nobody else on the server uses. +const TEST_TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6500_0001; + +/// The databases one test deployment minted, and the promise to drop them. +/// +/// Cloning shares the lease; the `DROP` statements fire when the **last** +/// copy drops — which is why a [`Tenants`] can carry one: the databases die +/// exactly when the test deployment does, even though the `Router` and the +/// test body hold separate clones of the registry. +#[doc(hidden)] +#[derive(Clone)] +pub struct TestDatabases(Arc); + +struct TestLease { + /// How to reach the maintenance database when the drops run. Dial options, + /// not a pool: the pools a test built belong to the test's runtime and + /// cannot be borrowed from the drop thread after that runtime dies — the + /// drop dials its own one-connection pool instead. + maintenance: PgConnectOptions, + names: Mutex>, +} + +impl TestDatabases { + fn new(maintenance: PgConnectOptions) -> Self { + Self(Arc::new(TestLease { + maintenance, + names: Mutex::new(Vec::new()), + })) + } + + pub(crate) fn track(&self, name: &str) { + self.0 + .names + .lock() + .expect("test lease names") + .push(name.to_owned()); + } + + /// The database names this lease still owes a drop. Diagnostics only. + pub fn names(&self) -> Vec { + self.0.names.lock().expect("test lease names").clone() + } +} + +impl std::fmt::Debug for TestDatabases { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TestDatabases") + .field("names", &self.names()) + .finish() + } +} + +impl Drop for TestLease { + fn drop(&mut self) { + let names = std::mem::take(&mut *self.names.lock().expect("test lease names")); + let maintenance = self.maintenance.clone(); + if names.is_empty() { + return; + } + let run = move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("test-lease drop runtime"); + runtime.block_on(async move { + let Ok(maintenance) = pool_options(1).connect_with(maintenance).await else { + eprintln!( + "test lease: cannot reach the maintenance database to drop {names:?}" + ); + return; + }; + for name in &names { + let sql = + create_database_sql("DROP DATABASE IF EXISTS", name) + " WITH (FORCE)"; + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(&maintenance) + .await + { + eprintln!("test lease: dropping {name} failed: {err}"); + } + } + maintenance.close().await; + }); + }; + // A lease usually dies inside the test's runtime (the last registry + // handle drops at the end of the test future), and a runtime may not + // be built inside another — so the drops always run on a dedicated + // thread. The wait is bounded: a wedged server cannot hang the test's + // teardown forever, and the janitor is the backstop for whatever + // outlives it. + match tokio::runtime::Handle::try_current() { + Ok(_) => { + let (done, done_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + run(); + let _ = done.send(()); + }); + let _ = done_rx.recv_timeout(Duration::from_secs(10)); + } + Err(_) => run(), + } + } +} + +/// A complete test deployment: a fresh control database plus the demo school, +/// whose database is cloned from the shared school template and registered in +/// the control registry under the slug every suite names ([`DEMO_SLUG`]). +/// +/// The databases die with the returned registry's last handle (see +/// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind. +#[doc(hidden)] +pub async fn init_test_tenants() -> Tenants { + let maintenance = maintenance_pool().await; + janitor(&maintenance).await; + let base = test_base(); + let lease = TestDatabases::new(base.clone()); + + let control_db = format!("{TEST_DB_PREFIX}{}", test_suffix()); + create_database(&maintenance, &control_db, None).await; + lease.track(&control_db); + let control = boot_control(&base.clone().database(&control_db)) + .await + .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}")); + + let template = ensure_test_template(&maintenance, &base).await; + + let demo = Slug::try_new(DEMO_SLUG).expect("the demo slug"); + let school_db = school_db_name(&control_db, &demo); + create_database(&maintenance, &school_db, Some(&template)).await; + lease.track(&school_db); + let school = school_pool(&base, &school_db) + .await + .unwrap_or_else(|err| panic!("dial the test demo school {school_db}: {err}")); + + // The registry row, exactly as [`Tenants::create`] would write it — but + // without the per-school migration its `bring_up` runs, which the + // template clone has just replaced. + sqlx::query( + "INSERT INTO school (slug, name, status, created_at, modules) + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(DEMO_SLUG) + .bind("Demo School") + .bind(SchoolStatus::Active) + .bind(Timestamp::now().as_millis()) + .bind(ModuleSet::all().names()) + .execute(&control) + .await + .expect("register the test demo school"); + + Tenants::new_test_adopting( + control, + base.database(&control_db), + control_db, + lease, + [(demo, school)], + ) +} + +/// One school database cloned from the template, for the src-side unit tests +/// that exercise a single store with no tenancy around it. Keep the lease +/// alive for the database's lifetime (`let (db, _leases) = …` binds it to the +/// test's scope); dropping it early drops the database. +#[doc(hidden)] +pub async fn init_test_db() -> (Database, TestDatabases) { + let maintenance = maintenance_pool().await; + janitor(&maintenance).await; + let base = test_base(); + let lease = TestDatabases::new(base.clone()); + let template = ensure_test_template(&maintenance, &base).await; + let name = format!("{TEST_DB_PREFIX}{}", test_suffix()); + create_database(&maintenance, &name, Some(&template)).await; + lease.track(&name); + let db = school_pool(&base, &name) + .await + .unwrap_or_else(|err| panic!("dial the test school database {name}: {err}")); + (db, lease) +} + +/// The school template's name, and as a side effect its existence: created +/// and migrated on first use, adopted when something else already made it. +/// The name carries a hash of `migrations/school`, so a schema edit mints a +/// fresh template and every process converges on the same new one. +/// +/// Competing first uses are real: nextest mints tests in parallel processes +/// and in parallel test threads, all overlapping on the same millisecond. +/// One server-wide advisory lock makes the create-and-migrate a critical +/// section — without it, two migrators interleave their DDL on the same +/// fresh database and one dies on a duplicate table mid-flight (observed). +/// The probe + `42P04` swallow are the belt to that brace: a template made +/// before the lock was ever taken is adopted, not fought. +async fn ensure_test_template(maintenance: &PgPool, base: &PgConnectOptions) -> String { + static ENSURED: LazyLock>> = LazyLock::new(Mutex::default); + let name = template_name(); + let ensured = &*ENSURED; + if ensured.lock().expect("template set").contains(&name) { + return name; + } + let mut session = maintenance + .acquire() + .await + .unwrap_or_else(|err| panic!("lease a maintenance connection: {err}")); + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(TEST_TEMPLATE_LOCK_KEY) + .execute(&mut *session) + .await + .unwrap_or_else(|err| panic!("lock the school template: {err}")); + let exists = sqlx::query_as::<_, (i64,)>("SELECT count(*) FROM pg_database WHERE datname = $1") + .bind(&name) + .fetch_one(&mut *session) + .await + .map(|(count,)| count > 0) + .unwrap_or_else(|err| panic!("probe for the school template {name}: {err}")); + if !exists { + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( + "CREATE DATABASE", + &name, + ))) + .execute(&mut *session) + .await + { + if !is_duplicate_database(&err) { + panic!("create the school template {name}: {err}"); + } + } + } + let pool = pool_options(1) + .connect_with(base.clone().database(&name)) + .await + .unwrap_or_else(|err| panic!("dial the school template {name}: {err}")); + let migrated = migrate_school(&pool).await; + pool.close().await; + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(TEST_TEMPLATE_LOCK_KEY) + .execute(&mut *session) + .await + .unwrap_or_else(|err| panic!("unlock the school template: {err}")); + migrated.unwrap_or_else(|err| panic!("migrate the school template {name}: {err:?}")); + ensured.lock().expect("template set").insert(name.clone()); + name +} + +/// `heztest_tpl_school_` — the hash is over `migrations/school`'s file +/// names and bytes, sorted, so any schema edit changes it. +fn template_name() -> String { + let mut migrations: Vec = std::fs::read_dir(migrations_path("school")) + .expect("read the school migrations directory") + .map(|entry| entry.expect("migration directory entry").path()) + .collect(); + migrations.sort(); + let mut hasher = Sha256::new(); + for path in migrations { + hasher.update( + path.file_name() + .expect("file name") + .to_string_lossy() + .as_bytes(), + ); + hasher.update(std::fs::read(&path).expect("read a school migration")); + } + format!( + "{TEST_DB_PREFIX}tpl_school_{}", + &hex::encode(hasher.finalize())[..8] + ) +} + +/// One sweep per process, at the first mint: `heztest_%` databases a crashed +/// run left behind. See the section header for why a candidate must be old +/// *and* unconnected before it is dropped. +async fn janitor(maintenance: &PgPool) { + static SWEPT: LazyLock<()> = LazyLock::new(|| {}); + LazyLock::force(&SWEPT); + let template = template_name(); + let leftovers = sqlx::query_as::<_, (String,)>( + "SELECT datname FROM pg_database WHERE datname LIKE 'heztest\\_%' ESCAPE '\\'", + ) + .fetch_all(maintenance) + .await + .unwrap_or_else(|err| panic!("list leftover test databases: {err}")); + for (name,) in leftovers { + if name == template || !sweep_candidate(&name) { + continue; + } + // No `WITH (FORCE)`: a database with live backends belongs to a + // running test in a parallel process, and the failed drop *is* the + // skip. + let _ = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( + "DROP DATABASE IF EXISTS", + &name, + ))) + .execute(maintenance) + .await; + } +} + +/// Should this `heztest_%` database be swept? The suffix's leading eleven hex +/// digits are the mint time in unix milliseconds; anything that cannot be +/// read that way is either a template of an older schema hash (swept) or +/// junk (swept too). +fn sweep_candidate(name: &str) -> bool { + let Some(minted_hex) = name.get(TEST_DB_PREFIX.len()..TEST_DB_PREFIX.len() + 11) else { + return true; + }; + match i64::from_str_radix(minted_hex, 16) { + Ok(minted_ms) => Timestamp::now().as_millis() - minted_ms > TEST_DB_LEFTOVER_MIN_AGE_MS, + Err(_) => name.starts_with(&format!("{TEST_DB_PREFIX}tpl_")), + } +} + +/// `<11 hex of unix-ms><5 hex random>`: the mint time, so the janitor can +/// tell a crashed run's leftovers from a parallel test's fresh databases, +/// plus just enough randomness that two processes minting in the same +/// millisecond never collide. +fn test_suffix() -> String { + let minted_ms = Timestamp::now().as_millis() as u64; + format!( + "{minted_ms:011x}{}", + &Uuid::new_v4().simple().to_string()[..5] + ) +} + +/// `CREATE DATABASE` for a harness-minted name, optionally `TEMPLATE`-cloned. +/// Both names are generated here (prefix + hex suffix), never user input — +/// the same audit that licenses [`create_database_sql`]'s `AssertSqlSafe` +/// callers. +async fn create_database(maintenance: &PgPool, name: &str, template: Option<&str>) { + let mut sql = create_database_sql("CREATE DATABASE", name); + if let Some(template) = template { + sql.push_str(&format!(" TEMPLATE \"{}\"", template.replace('"', "\"\""))); + } + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(maintenance) + .await + { + panic!("create the test database {name}: {err}"); + } +} + +/// Dial options for the test Postgres — `HEZARFEN_TEST_DATABASE_URL` or the +/// compose default. The URL's database is the *maintenance* database the +/// `CREATE DATABASE`s run against; the harness names every database itself. +fn test_base() -> PgConnectOptions { + let url = std::env::var(TEST_DATABASE_URL_ENV) + .ok() + .filter(|url| !url.trim().is_empty()) + .unwrap_or_else(|| TEST_DATABASE_URL_DEFAULT.to_owned()); + url.parse().unwrap_or_else(|err| { + panic!("{TEST_DATABASE_URL_ENV}={url:?} is not a Postgres URL: {err}") + }) +} + +/// A small pool over the maintenance database: the janitor's listing and +/// every `CREATE DATABASE` (DDL — not usable inside a transaction) go +/// through it, and each lease keeps a clone for its drops. +async fn maintenance_pool() -> PgPool { + pool_options(2) + .connect_with(test_base()) + .await + .unwrap_or_else(|err| { + panic!( + "cannot reach the test Postgres (set {TEST_DATABASE_URL_ENV}, default \ + {TEST_DATABASE_URL_DEFAULT}): {err} — is the compose stack up?" + ) + }) +} + #[cfg(test)] mod builder_seed_tests { use super::builder_credentials; @@ -423,4 +844,3 @@ mod builder_seed_tests { } } } - diff --git a/src/tenant.rs b/src/tenant.rs index 5fcd74d..8d4cbcb 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -24,8 +24,8 @@ use sqlx::postgres::PgConnectOptions; use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; use crate::database::{ - create_database_sql, is_duplicate_database, migrate_school, school_pool, unique_violation, - Database, + Database, create_database_sql, is_duplicate_database, migrate_school, school_pool, + unique_violation, }; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; @@ -267,6 +267,10 @@ pub struct Tenants { /// The control database's name; every school database is /// [`school_db_name`] of it. control_db: String, + /// Databases a test deployment minted, adopted via + /// [`Tenants::new_test_adopting`]; dropped with this registry's last + /// handle. `None` in production, where databases outlive the process. + leases: Option, } impl Tenants { @@ -278,9 +282,43 @@ impl Tenants { cache: Arc::new(RwLock::new(HashMap::new())), base, control_db, + leases: None, } } + /// Test constructor: wrap already-created databases and adopt their + /// [`crate::database::TestDatabases`] lease, so everything the harness + /// minted dies with this registry's last handle. `prewarmed` pools enter + /// the cache directly — for a template clone there is no re-dial to win. + #[doc(hidden)] + pub fn new_test_adopting( + control: Database, + base: PgConnectOptions, + control_db: String, + leases: crate::database::TestDatabases, + prewarmed: impl IntoIterator, + ) -> Tenants { + let cache: HashMap = prewarmed + .into_iter() + .map(|(slug, db)| (slug.as_str().to_owned(), db)) + .collect(); + Tenants { + control, + cache: Arc::new(RwLock::new(cache)), + base, + control_db, + leases: Some(leases), + } + } + + /// The databases this deployment minted, when it is a test deployment — + /// for a suite that wants to name what will die with it. `None` in + /// production. + #[doc(hidden)] + pub fn test_leases(&self) -> Option<&crate::database::TestDatabases> { + self.leases.as_ref() + } + /// The control database: schools, builders, the shared rate-limit window. /// It is never re-purposed for a school's rows — see this module's header. pub fn control(&self) -> &Database { @@ -383,6 +421,11 @@ impl Tenants { cache.len() }; Self::report_size(size); + // A test deployment's lease learns every school the deployment + // mints, so a school created mid-test dies with the deployment. + if let Some(leases) = &self.leases { + leases.track(&school_db_name(&self.control_db, slug)); + } Ok(db) } @@ -590,9 +633,6 @@ mod tests { } // The control database's own name is never a school's name: the // suffix keeps the namespaces apart. - assert_ne!( - school_db_name(control, &slug("school")), - control - ); + assert_ne!(school_db_name(control, &slug("school")), control); } } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 94cba73..31b028e 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,5 +1,8 @@ -//! Shared helpers for the router-level test binaries (`integration`, `persistence`). -//! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`. +//! Shared helpers for the router-level test binaries (`integration`, +//! `persistence`, and friends). Drives an `axum::Router` in-process via +//! `tower::ServiceExt::oneshot`, over a **per-test pair of Postgres +//! databases** — control plus demo school, cloned from the shared school +//! template by `database::init_test_tenants`, dropped with the test. #![allow(dead_code)] use std::path::PathBuf; @@ -12,7 +15,7 @@ use hezarfen_backend::ai::AiBridge; use hezarfen_backend::database::Database; use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; -use hezarfen_backend::state::{AppState, DbHealth}; +use hezarfen_backend::state::AppState; use hezarfen_backend::telemetry::Metrics; use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; use hezarfen_backend::{build_router, database}; @@ -27,9 +30,18 @@ pub struct Res { pub cookie: Option, } -/// One shared blob directory for every in-memory app in this test process. -/// Blob names are per-row ULIDs, so apps never collide; the static keeps the -/// `TempDir` (and so the directory) alive for the whole run. +/// A well-formed id for a row that exists nowhere — the canonical ghost +/// parent every FK-refusal test aims at. Replaces the ULID literal +/// `01J8XZ0K3Q8G7X2M4N5P6R7S8T` the suites used before the UUID v7 port. +pub const GHOST_ID: &str = "019732e3-7b00-7000-8000-00000000dead"; + +/// A second well-formed, never-minted id, for "look this up, expect a miss". +/// Replaces `01ZZZZZZZZZZZZZZZZZZZZZZZZ`. +pub const ABSENT_ID: &str = "019732e3-7b00-7000-8000-00000000eeee"; + +/// One shared blob directory for every app in this test process. Blob names +/// are per-row ids, so apps never collide; the static keeps the `TempDir` +/// (and so the directory) alive for the whole run. static FILES_DIR: OnceLock = OnceLock::new(); pub fn files_dir() -> PathBuf { @@ -39,7 +51,7 @@ pub fn files_dir() -> PathBuf { .to_path_buf() } -/// A router plus a handle to its (shared) in-memory database. Tests that need to +/// A router plus a handle to its demo school's database. Tests that need to /// grant roles use the handle to seed them directly — the app's only role /// bootstrap path is out-of-band, exactly like production's manual SQL. pub async fn app_and_db() -> (Router, Database) { @@ -49,7 +61,7 @@ pub async fn app_and_db() -> (Router, Database) { /// [`app_and_db`] plus the registry behind it, for the suites whose subject is /// tenancy itself (a second school, a suspension, the builder surface). pub async fn app_and_tenants() -> (Router, Database, Tenants) { - let (app, db, tenants) = app_parts(None, Default::default(), Metrics::noop()).await; + let (app, db, tenants) = app_parts(None, Metrics::noop()).await; (app, db, tenants) } @@ -71,12 +83,12 @@ pub fn cookie_token(cookie: &str) -> &str { .1 } -/// An in-memory deployment: the registry, plus the demo school's handle. For -/// the suites that build their own `AppState` instead of using [`app_and_db`]. +/// A test deployment: the registry, plus the demo school's handle. For the +/// suites that build their own `AppState` instead of using [`app_and_db`]. +/// (The name outlived the in-memory engine; the shape is what the suites +/// bind to.) pub async fn mem_deployment() -> (Tenants, Database) { - let tenants = database::init_mem_tenants() - .await - .expect("in-memory deployment"); + let tenants = database::init_test_tenants().await; let db = demo_db(&tenants).await; (tenants, db) } @@ -93,35 +105,22 @@ pub async fn demo_db(tenants: &Tenants) -> Database { /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the /// bootstrap that makes a QUIC service's reads dispatch into a real router. pub async fn app_with_ai(ai: Option) -> (Router, Database) { - app_with_ai_health(ai, Default::default()).await + let (app, db, _) = app_parts(ai, Metrics::noop()).await; + (app, db) } /// [`app_with_ai`] plus the registry behind it, for the suites whose subject is /// an AI service reading *across* schools. pub async fn app_with_ai_tenants(ai: Option) -> (Router, Database, Tenants) { - app_parts(ai, Default::default(), Metrics::noop()).await -} - -/// [`app_with_ai`] with the liveness flag handed in, so a test can take the -/// database socket down under a running app — the api-read path re-checks it in -/// place of the HTTP db guard it bypasses. -pub async fn app_with_ai_health(ai: Option, db_up: DbHealth) -> (Router, Database) { - let (app, db, _) = app_parts(ai, db_up, Metrics::noop()).await; - (app, db) + app_parts(ai, Metrics::noop()).await } -/// The one bootstrap: an in-memory deployment (control database + the demo +/// The one bootstrap: a fresh test deployment (control database + the demo /// school), a router over it, and the demo school's handle — which is what /// every suite means by "the database", since that is where users and rows /// live. -async fn app_parts( - ai: Option, - db_up: DbHealth, - metrics: hezarfen_backend::telemetry::Metrics, -) -> (Router, Database, Tenants) { - let tenants = database::init_mem_tenants() - .await - .expect("in-memory deployment"); +async fn app_parts(ai: Option, metrics: Metrics) -> (Router, Database, Tenants) { + let tenants = database::init_test_tenants().await; let db = demo_db(&tenants).await; let app = build_router(AppState { db: tenants.control().clone(), @@ -134,7 +133,6 @@ async fn app_parts( chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up, ai, metrics, }); @@ -144,7 +142,7 @@ async fn app_parts( /// The same router with the caller's instruments, so a test can read back what /// the HTTP edge recorded without touching the process-global meter provider. pub async fn app_with_metrics(metrics: Metrics) -> (Router, Database) { - let (app, db, _) = app_parts(None, Default::default(), metrics).await; + let (app, db, _) = app_parts(None, metrics).await; (app, db) } @@ -180,21 +178,21 @@ pub fn is_forbidden_key(key: &str) -> bool { || key.starts_with("http.response.header.") } -/// A router backed by a fresh in-memory database. +/// A router backed by a fresh per-test Postgres deployment. pub async fn mem_app() -> Router { app_and_db().await.0 } -/// Force `username`'s role, mirroring the manual `UPDATE user SET role=...` -/// bootstrap. Roles are read fresh per request, so this takes effect at once. +/// Force `username`'s role, mirroring the manual `UPDATE app_user SET +/// role=...` bootstrap. Roles are read fresh per request, so this takes +/// effect at once. pub async fn set_role(db: &Database, username: &str, role: &str) { - db.query("UPDATE user SET role = $role WHERE username = $u") - .bind(("role", role.to_string())) - .bind(("u", username.to_string())) + sqlx::query("UPDATE app_user SET role = $2 WHERE username = $1") + .bind(username) + .bind(role) + .execute(db) .await - .expect("set_role query") - .check() - .expect("set_role check"); + .expect("set_role query"); } /// Register (password `secret1`), promote to `role`, then log in. Returns the @@ -565,149 +563,34 @@ pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) { assert_eq!(res.status, StatusCode::OK, "enroll {user_id}"); } -// ---- remote (production) mode ------------------------------------------- +// ---- multi-school deployments --------------------------------------------- // -// `Mode::Mem` gives every school its own embedded datastore, so cross-school -// isolation *cannot* fail there. Production is `Mode::Remote`: one server, one -// namespace, a database per school, isolation resting entirely on each -// connection's `use_db` pin. The isolation probes therefore run in both modes, -// and the remote half needs a real server — this is it. - -/// A throwaway `surreal start … memory` server. Owned by the deployments using -/// it: killed as soon as the last one drops, which is what keeps both runners -/// clean — `cargo test` (one process, many tests, one shared server) and -/// `cargo nextest` (process per test, so the kill has to happen inside the -/// test, not at some exit hook the harness never runs). -pub struct RemoteServer { - child: std::sync::Mutex, - pub url: String, -} - -impl Drop for RemoteServer { - fn drop(&mut self) { - let mut child = self.child.lock().expect("server lock"); - let _ = child.kill(); - let _ = child.wait(); - } -} - -/// The live server, if one is still held; otherwise the next call spawns a new -/// one. A `Weak` and not the server itself: a `&'static` could never be -/// dropped, and an un-dropped child is a leaked `surreal` per test process. -static REMOTE: OnceLock>> = OnceLock::new(); - -const SURREAL_BIN: &str = ".surrealdb/surreal"; -const SURREAL_HINT: &str = "install it with `curl -sSf https://install.surrealdb.com | sh`, \ - or set HEZARFEN_SKIP_REMOTE=1 to skip the production-mode isolation tests"; - -/// The shared server, or `None` when `HEZARFEN_SKIP_REMOTE=1` says to skip. -/// A missing binary is a **panic**: remote-mode isolation is the mode -/// production runs in, so it must never quietly not-run. -pub fn remote_server() -> Option> { - if std::env::var("HEZARFEN_SKIP_REMOTE").as_deref() == Ok("1") { - eprintln!("HEZARFEN_SKIP_REMOTE=1 — remote-mode isolation NOT exercised"); - return None; - } - let mut slot = REMOTE - .get_or_init(Default::default) - .lock() - .expect("remote server slot"); - if let Some(server) = slot.upgrade() { - return Some(server); - } - let bin = PathBuf::from(std::env::var("HOME").expect("HOME")).join(SURREAL_BIN); - assert!( - bin.exists(), - "no surreal binary at {} — {SURREAL_HINT}", - bin.display() - ); - // Pick the port by binding and releasing it: two test *processes* (nextest) - // each want a server of their own, and a fixed port would collide. - let port = std::net::TcpListener::bind("127.0.0.1:0") - .expect("a free port") - .local_addr() - .expect("the bound address") - .port(); - let child = std::process::Command::new(&bin) - .args([ - "start", - "--user", - "root", - "--pass", - "root", - "--bind", - &format!("127.0.0.1:{port}"), - "memory", - ]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .unwrap_or_else(|err| panic!("spawn {}: {err}", bin.display())); - let server = std::sync::Arc::new(RemoteServer { - child: std::sync::Mutex::new(child), - url: format!("ws://127.0.0.1:{port}"), - }); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() { - assert!( - std::time::Instant::now() < deadline, - "surreal never listened on 127.0.0.1:{port}" - ); - std::thread::sleep(std::time::Duration::from_millis(20)); - } - *slot = std::sync::Arc::downgrade(&server); - Some(server) -} - -/// A deployment on the shared server: its own namespace, its own blob -/// directory, and the server handle that must outlive both. -pub struct RemoteDeployment { +// The probes whose subject is tenancy itself — cross-school isolation, +// suspension, school deletion — build a deployment with more schools than +// the demo one. Under database-per-school tenancy there is no separate +// "remote" mode to exercise: production *is* this shape, and a second +// deployment is a second `database::init_test_tenants()` away. (The +// `surreal start` remote lane this section used to hold died with the +// embedded engine.) + +/// A deployment with its own blob directory: what the tenancy probes hold. +pub struct TestDeployment { pub app: Router, pub tenants: Tenants, - /// The scratch namespace this deployment owns, so a test can name it. - pub ns: String, - /// `FILES_PATH` — one per deployment, never the shared [`files_dir`], so a - /// remote run's uploads cannot be counted by a memory-mode probe. + /// `FILES_PATH` — this deployment's own directory, never the shared + /// [`files_dir`], so one deployment's uploads cannot be counted by + /// another's probes. pub files: PathBuf, _files: TempDir, - _server: std::sync::Arc, } -/// The remote twin of [`app_and_tenants`]: a real control database in a -/// namespace of its own, the named schools created in it, and the same router -/// over the same `AppState`. `None` when the remote lane is skipped. -pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option { - let server = remote_server()?; +/// [`app_and_tenants`] with named schools created alongside the demo — where +/// the former `remote_deployment` probes re-point. The named schools go +/// through the real [`Tenants::create`], since the create path is part of +/// what the tenancy probes examine. +pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment { let files = tempfile::tempdir().expect("files tempdir"); - // Unique per call: every test in a process shares one server, and a - // namespace collision would put two deployments on one control database. - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let ns = format!( - "t{}x{}", - std::process::id(), - NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) - ); - let cfg = hezarfen_backend::config::Config { - host: "127.0.0.1".into(), - port: 0, - db_url: server.url.clone(), - db_user: "root".into(), - db_pass: "root".into(), - db_ns: ns.clone(), - db_name: "control".into(), - files_path: files.path().display().to_string(), - cookie_secure: false, - rate_limit: RateLimitConfig::unlimited(), - chatbot_per_minute: 0, - builder_username: None, - builder_password: None, - ai_quic_addr: None, - ai_shared_token: None, - ai_tls_cert: None, - ai_tls_key: None, - ai_request_timeout_secs: 30, - }; - let tenants = database::init(&cfg).await.expect("remote control database"); + let tenants = database::init_test_tenants().await; for (slug, name) in schools { tenants .create( @@ -727,16 +610,13 @@ pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option