forge
Explore
Log in

Don't you dare go Hollow

Postgres test harness (per-test databases)

Browse files at this commit

18e1b7bc01666d6c39033ce8d76efa8a00181e8bAhmet Kaan GümüşParent: 1b4406a
  • test
    • postgres test harness (per-test databases)
Show full message
🧪 test: postgres test harness (per-test databases)
src/database.rsmodified+433 -13
@@ -10,19 +10,24 @@
10 //! Their table names are disjoint by design, which is what lets one prepare10 //! Their table names are disjoint by design, which is what lets one prepare
11 //! database carry the union for the compile-time `query!` checks.11 //! database carry the union for the compile-time `query!` checks.
12 12
13+use std::collections::HashSet;
13 use std::path::Path;14 use std::path::Path;
15+use std::sync::{Arc, LazyLock, Mutex};
14 use std::time::Duration;16 use std::time::Duration;
15 17
18+use sha2::{Digest, Sha256};
19+use sqlx::PgPool;
16 use sqlx::migrate::{MigrateError, Migrator};20 use sqlx::migrate::{MigrateError, Migrator};
17 use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};21 use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};
18-use sqlx::PgPool;22+use uuid::Uuid;
19 23
20 use crate::config::Config;24 use crate::config::Config;
21 use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};25 use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};
22 use crate::domain::timestamp::Timestamp;26 use crate::domain::timestamp::Timestamp;
23 use crate::domain::user::{Password, Username};27 use crate::domain::user::{Password, Username};
24 use crate::error::AppError;28 use crate::error::AppError;
25-use crate::tenant::Tenants;29+use crate::module::ModuleSet;
30+use crate::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants, school_db_name};
26 31
27 /// The shared database handle.32 /// The shared database handle.
28 ///33 ///
@@ -84,7 +89,10 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
84 /// the name every school database hangs off (`{control}_school_{slug}`).89 /// the name every school database hangs off (`{control}_school_{slug}`).
85 pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> {90 pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> {
86 let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| {91 let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| {
87- AppError::Internal(format!("invalid DATABASE_URL ({}): {err}", cfg.database_url))92+ AppError::Internal(format!(
93+ "invalid DATABASE_URL ({}): {err}",
94+ cfg.database_url
95+ ))
88 })?;96 })?;
89 let db = opts97 let db = opts
90 .get_database()98 .get_database()
@@ -112,7 +120,10 @@ fn pool_options(max_connections: u32) -> PgPoolOptions {
112 /// A pool over one school database with the school pool sizing. The schema is120 /// A pool over one school database with the school pool sizing. The schema is
113 /// the caller's business — [`migrate_school`] for a mint, nothing for a121 /// the caller's business — [`migrate_school`] for a mint, nothing for a
114 /// re-dial of an existing school.122 /// re-dial of an existing school.
115-pub(crate) async fn school_pool(base: &PgConnectOptions, db_name: &str) -> Result<PgPool, AppError> {123+pub(crate) async fn school_pool(
124+ base: &PgConnectOptions,
125+ db_name: &str,
126+) -> Result<PgPool, AppError> {
116 pool_options(4)127 pool_options(4)
117 .connect_with(base.clone().database(db_name))128 .connect_with(base.clone().database(db_name))
118 .await129 .await
@@ -225,17 +236,21 @@ async fn ensure_template(
225 base: &PgConnectOptions,236 base: &PgConnectOptions,
226 name: &str,237 name: &str,
227 ) -> Result<(), AppError> {238 ) -> Result<(), AppError> {
228- if let Err(err) =239+ if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
229- sqlx::query(sqlx::AssertSqlSafe(create_database_sql("CREATE DATABASE", name)))240+ "CREATE DATABASE",
230- .execute(control)241+ name,
231- .await242+ )))
243+ .execute(control)
244+ .await
232 {245 {
233 if !is_duplicate_database(&err) {246 if !is_duplicate_database(&err) {
234 return Err(err.into());247 return Err(err.into());
235 }248 }
236 }249 }
237 // One migrator connection, made and closed: the template is never served.250 // One migrator connection, made and closed: the template is never served.
238- let pool = pool_options(1).connect_with(base.clone().database(name)).await?;251+ let pool = pool_options(1)
252+ .connect_with(base.clone().database(name))
253+ .await?;
239 let migrated = migrate_school(&pool).await;254 let migrated = migrate_school(&pool).await;
240 pool.close().await;255 pool.close().await;
241 migrated256 migrated
@@ -348,9 +363,9 @@ where
348 Err(err) => return Err(err),363 Err(err) => return Err(err),
349 }364 }
350 }365 }
351- Err(last.map(AppError::Db).unwrap_or_else(|| {366+ Err(last
352- AppError::Internal("a guarded transaction never ran".into())367+ .map(AppError::Db)
353- }))368+ .unwrap_or_else(|| AppError::Internal("a guarded transaction never ran".into())))
354 }369 }
355 370
356 fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool {371 fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool {
@@ -392,6 +407,412 @@ fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, App
392 }407 }
393 }408 }
394 409
410+// ---- per-test databases -----------------------------------------------------
411+//
412+// Every test run gets a **private pair of databases** on the compose Postgres:
413+// a control database and the demo school's database, both named after one
414+// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_demo` — so
415+// nextest's parallel processes neither collide nor see each other's rows. The
416+// school schema is not migrated per test: it is cloned from a shared template
417+// database whose name carries a hash of `migrations/school`, so a schema edit
418+// mints a fresh template exactly once and every test after that pays only a
419+// cheap `CREATE DATABASE … TEMPLATE`.
420+//
421+// Cleanup is a lease: every database a deployment minted is recorded in a
422+// [`TestDatabases`], and its `Drop` — fired when the deployment's last handle
423+// dies — sends `DROP DATABASE … WITH (FORCE)`. A best-effort janitor at first
424+// use per process sweeps what a crashed run left behind: only databases past
425+// a minimum age are candidates, and their `DROP` carries no `WITH (FORCE)`,
426+// so a live parallel test's databases (connected backends, young name) are
427+// never touched.
428+//
429+// These functions are `pub` rather than `#[cfg(test)]` because the
430+// integration tests live outside the crate, and `#[doc(hidden)]` because they
431+// are not part of the API. Their SQL is runtime-checked — the query-style
432+// rule exempts all test-side SQL from the macros.
433+
434+/// The Postgres server the test databases are minted on. The default is the
435+/// compose stack's maintenance database (`.env.example` documents it).
436+const TEST_DATABASE_URL_ENV: &str = "HEZARFEN_TEST_DATABASE_URL";
437+const TEST_DATABASE_URL_DEFAULT: &str = "postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres";
438+
439+/// Every test database carries this prefix; the janitor only ever drops
440+/// databases it names.
441+const TEST_DB_PREFIX: &str = "heztest_";
442+
443+/// How old a `heztest_%` database must be before the janitor will touch it.
444+/// Anything younger belongs to a test in a parallel process — nextest mints
445+/// them by the dozen in overlapping seconds.
446+const TEST_DB_LEFTOVER_MIN_AGE_MS: i64 = 5 * 60 * 1000;
447+
448+/// The advisory-lock key the template's create-and-migrate critical section
449+/// holds (see [`ensure_test_template`]). An arbitrary constant — it only has
450+/// to be one nobody else on the server uses.
451+const TEST_TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6500_0001;
452+
453+/// The databases one test deployment minted, and the promise to drop them.
454+///
455+/// Cloning shares the lease; the `DROP` statements fire when the **last**
456+/// copy drops — which is why a [`Tenants`] can carry one: the databases die
457+/// exactly when the test deployment does, even though the `Router` and the
458+/// test body hold separate clones of the registry.
459+#[doc(hidden)]
460+#[derive(Clone)]
461+pub struct TestDatabases(Arc<TestLease>);
462+
463+struct TestLease {
464+ /// How to reach the maintenance database when the drops run. Dial options,
465+ /// not a pool: the pools a test built belong to the test's runtime and
466+ /// cannot be borrowed from the drop thread after that runtime dies — the
467+ /// drop dials its own one-connection pool instead.
468+ maintenance: PgConnectOptions,
469+ names: Mutex<Vec<String>>,
470+}
471+
472+impl TestDatabases {
473+ fn new(maintenance: PgConnectOptions) -> Self {
474+ Self(Arc::new(TestLease {
475+ maintenance,
476+ names: Mutex::new(Vec::new()),
477+ }))
478+ }
479+
480+ pub(crate) fn track(&self, name: &str) {
481+ self.0
482+ .names
483+ .lock()
484+ .expect("test lease names")
485+ .push(name.to_owned());
486+ }
487+
488+ /// The database names this lease still owes a drop. Diagnostics only.
489+ pub fn names(&self) -> Vec<String> {
490+ self.0.names.lock().expect("test lease names").clone()
491+ }
492+}
493+
494+impl std::fmt::Debug for TestDatabases {
495+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496+ f.debug_struct("TestDatabases")
497+ .field("names", &self.names())
498+ .finish()
499+ }
500+}
501+
502+impl Drop for TestLease {
503+ fn drop(&mut self) {
504+ let names = std::mem::take(&mut *self.names.lock().expect("test lease names"));
505+ let maintenance = self.maintenance.clone();
506+ if names.is_empty() {
507+ return;
508+ }
509+ let run = move || {
510+ let runtime = tokio::runtime::Builder::new_current_thread()
511+ .enable_all()
512+ .build()
513+ .expect("test-lease drop runtime");
514+ runtime.block_on(async move {
515+ let Ok(maintenance) = pool_options(1).connect_with(maintenance).await else {
516+ eprintln!(
517+ "test lease: cannot reach the maintenance database to drop {names:?}"
518+ );
519+ return;
520+ };
521+ for name in &names {
522+ let sql =
523+ create_database_sql("DROP DATABASE IF EXISTS", name) + " WITH (FORCE)";
524+ if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
525+ .execute(&maintenance)
526+ .await
527+ {
528+ eprintln!("test lease: dropping {name} failed: {err}");
529+ }
530+ }
531+ maintenance.close().await;
532+ });
533+ };
534+ // A lease usually dies inside the test's runtime (the last registry
535+ // handle drops at the end of the test future), and a runtime may not
536+ // be built inside another — so the drops always run on a dedicated
537+ // thread. The wait is bounded: a wedged server cannot hang the test's
538+ // teardown forever, and the janitor is the backstop for whatever
539+ // outlives it.
540+ match tokio::runtime::Handle::try_current() {
541+ Ok(_) => {
542+ let (done, done_rx) = std::sync::mpsc::channel();
543+ std::thread::spawn(move || {
544+ run();
545+ let _ = done.send(());
546+ });
547+ let _ = done_rx.recv_timeout(Duration::from_secs(10));
548+ }
549+ Err(_) => run(),
550+ }
551+ }
552+}
553+
554+/// A complete test deployment: a fresh control database plus the demo school,
555+/// whose database is cloned from the shared school template and registered in
556+/// the control registry under the slug every suite names ([`DEMO_SLUG`]).
557+///
558+/// The databases die with the returned registry's last handle (see
559+/// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind.
560+#[doc(hidden)]
561+pub async fn init_test_tenants() -> Tenants {
562+ let maintenance = maintenance_pool().await;
563+ janitor(&maintenance).await;
564+ let base = test_base();
565+ let lease = TestDatabases::new(base.clone());
566+
567+ let control_db = format!("{TEST_DB_PREFIX}{}", test_suffix());
568+ create_database(&maintenance, &control_db, None).await;
569+ lease.track(&control_db);
570+ let control = boot_control(&base.clone().database(&control_db))
571+ .await
572+ .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));
573+
574+ let template = ensure_test_template(&maintenance, &base).await;
575+
576+ let demo = Slug::try_new(DEMO_SLUG).expect("the demo slug");
577+ let school_db = school_db_name(&control_db, &demo);
578+ create_database(&maintenance, &school_db, Some(&template)).await;
579+ lease.track(&school_db);
580+ let school = school_pool(&base, &school_db)
581+ .await
582+ .unwrap_or_else(|err| panic!("dial the test demo school {school_db}: {err}"));
583+
584+ // The registry row, exactly as [`Tenants::create`] would write it — but
585+ // without the per-school migration its `bring_up` runs, which the
586+ // template clone has just replaced.
587+ sqlx::query(
588+ "INSERT INTO school (slug, name, status, created_at, modules)
589+ VALUES ($1, $2, $3, $4, $5)",
590+ )
591+ .bind(DEMO_SLUG)
592+ .bind("Demo School")
593+ .bind(SchoolStatus::Active)
594+ .bind(Timestamp::now().as_millis())
595+ .bind(ModuleSet::all().names())
596+ .execute(&control)
597+ .await
598+ .expect("register the test demo school");
599+
600+ Tenants::new_test_adopting(
601+ control,
602+ base.database(&control_db),
603+ control_db,
604+ lease,
605+ [(demo, school)],
606+ )
607+}
608+
609+/// One school database cloned from the template, for the src-side unit tests
610+/// that exercise a single store with no tenancy around it. Keep the lease
611+/// alive for the database's lifetime (`let (db, _leases) = …` binds it to the
612+/// test's scope); dropping it early drops the database.
613+#[doc(hidden)]
614+pub async fn init_test_db() -> (Database, TestDatabases) {
615+ let maintenance = maintenance_pool().await;
616+ janitor(&maintenance).await;
617+ let base = test_base();
618+ let lease = TestDatabases::new(base.clone());
619+ let template = ensure_test_template(&maintenance, &base).await;
620+ let name = format!("{TEST_DB_PREFIX}{}", test_suffix());
621+ create_database(&maintenance, &name, Some(&template)).await;
622+ lease.track(&name);
623+ let db = school_pool(&base, &name)
624+ .await
625+ .unwrap_or_else(|err| panic!("dial the test school database {name}: {err}"));
626+ (db, lease)
627+}
628+
629+/// The school template's name, and as a side effect its existence: created
630+/// and migrated on first use, adopted when something else already made it.
631+/// The name carries a hash of `migrations/school`, so a schema edit mints a
632+/// fresh template and every process converges on the same new one.
633+///
634+/// Competing first uses are real: nextest mints tests in parallel processes
635+/// and in parallel test threads, all overlapping on the same millisecond.
636+/// One server-wide advisory lock makes the create-and-migrate a critical
637+/// section — without it, two migrators interleave their DDL on the same
638+/// fresh database and one dies on a duplicate table mid-flight (observed).
639+/// The probe + `42P04` swallow are the belt to that brace: a template made
640+/// before the lock was ever taken is adopted, not fought.
641+async fn ensure_test_template(maintenance: &PgPool, base: &PgConnectOptions) -> String {
642+ static ENSURED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
643+ let name = template_name();
644+ let ensured = &*ENSURED;
645+ if ensured.lock().expect("template set").contains(&name) {
646+ return name;
647+ }
648+ let mut session = maintenance
649+ .acquire()
650+ .await
651+ .unwrap_or_else(|err| panic!("lease a maintenance connection: {err}"));
652+ sqlx::query("SELECT pg_advisory_lock($1)")
653+ .bind(TEST_TEMPLATE_LOCK_KEY)
654+ .execute(&mut *session)
655+ .await
656+ .unwrap_or_else(|err| panic!("lock the school template: {err}"));
657+ let exists = sqlx::query_as::<_, (i64,)>("SELECT count(*) FROM pg_database WHERE datname = $1")
658+ .bind(&name)
659+ .fetch_one(&mut *session)
660+ .await
661+ .map(|(count,)| count > 0)
662+ .unwrap_or_else(|err| panic!("probe for the school template {name}: {err}"));
663+ if !exists {
664+ if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
665+ "CREATE DATABASE",
666+ &name,
667+ )))
668+ .execute(&mut *session)
669+ .await
670+ {
671+ if !is_duplicate_database(&err) {
672+ panic!("create the school template {name}: {err}");
673+ }
674+ }
675+ }
676+ let pool = pool_options(1)
677+ .connect_with(base.clone().database(&name))
678+ .await
679+ .unwrap_or_else(|err| panic!("dial the school template {name}: {err}"));
680+ let migrated = migrate_school(&pool).await;
681+ pool.close().await;
682+ sqlx::query("SELECT pg_advisory_unlock($1)")
683+ .bind(TEST_TEMPLATE_LOCK_KEY)
684+ .execute(&mut *session)
685+ .await
686+ .unwrap_or_else(|err| panic!("unlock the school template: {err}"));
687+ migrated.unwrap_or_else(|err| panic!("migrate the school template {name}: {err:?}"));
688+ ensured.lock().expect("template set").insert(name.clone());
689+ name
690+}
691+
692+/// `heztest_tpl_school_<hash>` — the hash is over `migrations/school`'s file
693+/// names and bytes, sorted, so any schema edit changes it.
694+fn template_name() -> String {
695+ let mut migrations: Vec<std::path::PathBuf> = std::fs::read_dir(migrations_path("school"))
696+ .expect("read the school migrations directory")
697+ .map(|entry| entry.expect("migration directory entry").path())
698+ .collect();
699+ migrations.sort();
700+ let mut hasher = Sha256::new();
701+ for path in migrations {
702+ hasher.update(
703+ path.file_name()
704+ .expect("file name")
705+ .to_string_lossy()
706+ .as_bytes(),
707+ );
708+ hasher.update(std::fs::read(&path).expect("read a school migration"));
709+ }
710+ format!(
711+ "{TEST_DB_PREFIX}tpl_school_{}",
712+ &hex::encode(hasher.finalize())[..8]
713+ )
714+}
715+
716+/// One sweep per process, at the first mint: `heztest_%` databases a crashed
717+/// run left behind. See the section header for why a candidate must be old
718+/// *and* unconnected before it is dropped.
719+async fn janitor(maintenance: &PgPool) {
720+ static SWEPT: LazyLock<()> = LazyLock::new(|| {});
721+ LazyLock::force(&SWEPT);
722+ let template = template_name();
723+ let leftovers = sqlx::query_as::<_, (String,)>(
724+ "SELECT datname FROM pg_database WHERE datname LIKE 'heztest\\_%' ESCAPE '\\'",
725+ )
726+ .fetch_all(maintenance)
727+ .await
728+ .unwrap_or_else(|err| panic!("list leftover test databases: {err}"));
729+ for (name,) in leftovers {
730+ if name == template || !sweep_candidate(&name) {
731+ continue;
732+ }
733+ // No `WITH (FORCE)`: a database with live backends belongs to a
734+ // running test in a parallel process, and the failed drop *is* the
735+ // skip.
736+ let _ = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
737+ "DROP DATABASE IF EXISTS",
738+ &name,
739+ )))
740+ .execute(maintenance)
741+ .await;
742+ }
743+}
744+
745+/// Should this `heztest_%` database be swept? The suffix's leading eleven hex
746+/// digits are the mint time in unix milliseconds; anything that cannot be
747+/// read that way is either a template of an older schema hash (swept) or
748+/// junk (swept too).
749+fn sweep_candidate(name: &str) -> bool {
750+ let Some(minted_hex) = name.get(TEST_DB_PREFIX.len()..TEST_DB_PREFIX.len() + 11) else {
751+ return true;
752+ };
753+ match i64::from_str_radix(minted_hex, 16) {
754+ Ok(minted_ms) => Timestamp::now().as_millis() - minted_ms > TEST_DB_LEFTOVER_MIN_AGE_MS,
755+ Err(_) => name.starts_with(&format!("{TEST_DB_PREFIX}tpl_")),
756+ }
757+}
758+
759+/// `<11 hex of unix-ms><5 hex random>`: the mint time, so the janitor can
760+/// tell a crashed run's leftovers from a parallel test's fresh databases,
761+/// plus just enough randomness that two processes minting in the same
762+/// millisecond never collide.
763+fn test_suffix() -> String {
764+ let minted_ms = Timestamp::now().as_millis() as u64;
765+ format!(
766+ "{minted_ms:011x}{}",
767+ &Uuid::new_v4().simple().to_string()[..5]
768+ )
769+}
770+
771+/// `CREATE DATABASE` for a harness-minted name, optionally `TEMPLATE`-cloned.
772+/// Both names are generated here (prefix + hex suffix), never user input —
773+/// the same audit that licenses [`create_database_sql`]'s `AssertSqlSafe`
774+/// callers.
775+async fn create_database(maintenance: &PgPool, name: &str, template: Option<&str>) {
776+ let mut sql = create_database_sql("CREATE DATABASE", name);
777+ if let Some(template) = template {
778+ sql.push_str(&format!(" TEMPLATE \"{}\"", template.replace('"', "\"\"")));
779+ }
780+ if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
781+ .execute(maintenance)
782+ .await
783+ {
784+ panic!("create the test database {name}: {err}");
785+ }
786+}
787+
788+/// Dial options for the test Postgres — `HEZARFEN_TEST_DATABASE_URL` or the
789+/// compose default. The URL's database is the *maintenance* database the
790+/// `CREATE DATABASE`s run against; the harness names every database itself.
791+fn test_base() -> PgConnectOptions {
792+ let url = std::env::var(TEST_DATABASE_URL_ENV)
793+ .ok()
794+ .filter(|url| !url.trim().is_empty())
795+ .unwrap_or_else(|| TEST_DATABASE_URL_DEFAULT.to_owned());
796+ url.parse().unwrap_or_else(|err| {
797+ panic!("{TEST_DATABASE_URL_ENV}={url:?} is not a Postgres URL: {err}")
798+ })
799+}
800+
801+/// A small pool over the maintenance database: the janitor's listing and
802+/// every `CREATE DATABASE` (DDL — not usable inside a transaction) go
803+/// through it, and each lease keeps a clone for its drops.
804+async fn maintenance_pool() -> PgPool {
805+ pool_options(2)
806+ .connect_with(test_base())
807+ .await
808+ .unwrap_or_else(|err| {
809+ panic!(
810+ "cannot reach the test Postgres (set {TEST_DATABASE_URL_ENV}, default \
811+ {TEST_DATABASE_URL_DEFAULT}): {err} — is the compose stack up?"
812+ )
813+ })
814+}
815+
395 #[cfg(test)]816 #[cfg(test)]
396 mod builder_seed_tests {817 mod builder_seed_tests {
397 use super::builder_credentials;818 use super::builder_credentials;
@@ -423,4 +844,3 @@ mod builder_seed_tests {
423 }844 }
424 }845 }
425 }846 }
426-
src/tenant.rsmodified+46 -6
@@ -24,8 +24,8 @@ use sqlx::postgres::PgConnectOptions;
24 24
25 use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};25 use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
26 use crate::database::{26 use crate::database::{
27- create_database_sql, is_duplicate_database, migrate_school, school_pool, unique_violation,27+ Database, create_database_sql, is_duplicate_database, migrate_school, school_pool,
28- Database,28+ unique_violation,
29 };29 };
30 use crate::domain::timestamp::Timestamp;30 use crate::domain::timestamp::Timestamp;
31 use crate::error::{AppError, ValidationError};31 use crate::error::{AppError, ValidationError};
@@ -267,6 +267,10 @@ pub struct Tenants {
267 /// The control database's name; every school database is267 /// The control database's name; every school database is
268 /// [`school_db_name`] of it.268 /// [`school_db_name`] of it.
269 control_db: String,269 control_db: String,
270+ /// Databases a test deployment minted, adopted via
271+ /// [`Tenants::new_test_adopting`]; dropped with this registry's last
272+ /// handle. `None` in production, where databases outlive the process.
273+ leases: Option<crate::database::TestDatabases>,
270 }274 }
271 275
272 impl Tenants {276 impl Tenants {
@@ -278,9 +282,43 @@ impl Tenants {
278 cache: Arc::new(RwLock::new(HashMap::new())),282 cache: Arc::new(RwLock::new(HashMap::new())),
279 base,283 base,
280 control_db,284 control_db,
285+ leases: None,
281 }286 }
282 }287 }
283 288
289+ /// Test constructor: wrap already-created databases and adopt their
290+ /// [`crate::database::TestDatabases`] lease, so everything the harness
291+ /// minted dies with this registry's last handle. `prewarmed` pools enter
292+ /// the cache directly — for a template clone there is no re-dial to win.
293+ #[doc(hidden)]
294+ pub fn new_test_adopting(
295+ control: Database,
296+ base: PgConnectOptions,
297+ control_db: String,
298+ leases: crate::database::TestDatabases,
299+ prewarmed: impl IntoIterator<Item = (Slug, Database)>,
300+ ) -> Tenants {
301+ let cache: HashMap<String, Database> = prewarmed
302+ .into_iter()
303+ .map(|(slug, db)| (slug.as_str().to_owned(), db))
304+ .collect();
305+ Tenants {
306+ control,
307+ cache: Arc::new(RwLock::new(cache)),
308+ base,
309+ control_db,
310+ leases: Some(leases),
311+ }
312+ }
313+
314+ /// The databases this deployment minted, when it is a test deployment —
315+ /// for a suite that wants to name what will die with it. `None` in
316+ /// production.
317+ #[doc(hidden)]
318+ pub fn test_leases(&self) -> Option<&crate::database::TestDatabases> {
319+ self.leases.as_ref()
320+ }
321+
284 /// The control database: schools, builders, the shared rate-limit window.322 /// The control database: schools, builders, the shared rate-limit window.
285 /// It is never re-purposed for a school's rows — see this module's header.323 /// It is never re-purposed for a school's rows — see this module's header.
286 pub fn control(&self) -> &Database {324 pub fn control(&self) -> &Database {
@@ -383,6 +421,11 @@ impl Tenants {
383 cache.len()421 cache.len()
384 };422 };
385 Self::report_size(size);423 Self::report_size(size);
424+ // A test deployment's lease learns every school the deployment
425+ // mints, so a school created mid-test dies with the deployment.
426+ if let Some(leases) = &self.leases {
427+ leases.track(&school_db_name(&self.control_db, slug));
428+ }
386 Ok(db)429 Ok(db)
387 }430 }
388 431
@@ -590,9 +633,6 @@ mod tests {
590 }633 }
591 // The control database's own name is never a school's name: the634 // The control database's own name is never a school's name: the
592 // suffix keeps the namespaces apart.635 // suffix keeps the namespaces apart.
593- assert_ne!(636+ assert_ne!(school_db_name(control, &slug("school")), control);
594- school_db_name(control, &slug("school")),
595- control
596- );
597 }637 }
598 }638 }
tests/common/mod.rsmodified+63 -183
@@ -1,5 +1,8 @@
1-//! Shared helpers for the router-level test binaries (`integration`, `persistence`).1+//! Shared helpers for the router-level test binaries (`integration`,
2-//! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`.2+//! `persistence`, and friends). Drives an `axum::Router` in-process via
3+//! `tower::ServiceExt::oneshot`, over a **per-test pair of Postgres
4+//! databases** — control plus demo school, cloned from the shared school
5+//! template by `database::init_test_tenants`, dropped with the test.
3 #![allow(dead_code)]6 #![allow(dead_code)]
4 7
5 use std::path::PathBuf;8 use std::path::PathBuf;
@@ -12,7 +15,7 @@ use hezarfen_backend::ai::AiBridge;
12 use hezarfen_backend::database::Database;15 use hezarfen_backend::database::Database;
13 use hezarfen_backend::module::ModuleSet;16 use hezarfen_backend::module::ModuleSet;
14 use hezarfen_backend::rate_limit::RateLimitConfig;17 use hezarfen_backend::rate_limit::RateLimitConfig;
15-use hezarfen_backend::state::{AppState, DbHealth};18+use hezarfen_backend::state::AppState;
16 use hezarfen_backend::telemetry::Metrics;19 use hezarfen_backend::telemetry::Metrics;
17 use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants};20 use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants};
18 use hezarfen_backend::{build_router, database};21 use hezarfen_backend::{build_router, database};
@@ -27,9 +30,18 @@ pub struct Res {
27 pub cookie: Option<String>,30 pub cookie: Option<String>,
28 }31 }
29 32
30-/// One shared blob directory for every in-memory app in this test process.33+/// A well-formed id for a row that exists nowhere — the canonical ghost
31-/// Blob names are per-row ULIDs, so apps never collide; the static keeps the34+/// parent every FK-refusal test aims at. Replaces the ULID literal
32-/// `TempDir` (and so the directory) alive for the whole run.35+/// `01J8XZ0K3Q8G7X2M4N5P6R7S8T` the suites used before the UUID v7 port.
36+pub const GHOST_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
37+
38+/// A second well-formed, never-minted id, for "look this up, expect a miss".
39+/// Replaces `01ZZZZZZZZZZZZZZZZZZZZZZZZ`.
40+pub const ABSENT_ID: &str = "019732e3-7b00-7000-8000-00000000eeee";
41+
42+/// One shared blob directory for every app in this test process. Blob names
43+/// are per-row ids, so apps never collide; the static keeps the `TempDir`
44+/// (and so the directory) alive for the whole run.
33 static FILES_DIR: OnceLock<TempDir> = OnceLock::new();45 static FILES_DIR: OnceLock<TempDir> = OnceLock::new();
34 46
35 pub fn files_dir() -> PathBuf {47 pub fn files_dir() -> PathBuf {
@@ -39,7 +51,7 @@ pub fn files_dir() -> PathBuf {
39 .to_path_buf()51 .to_path_buf()
40 }52 }
41 53
42-/// A router plus a handle to its (shared) in-memory database. Tests that need to54+/// A router plus a handle to its demo school's database. Tests that need to
43 /// grant roles use the handle to seed them directly — the app's only role55 /// grant roles use the handle to seed them directly — the app's only role
44 /// bootstrap path is out-of-band, exactly like production's manual SQL.56 /// bootstrap path is out-of-band, exactly like production's manual SQL.
45 pub async fn app_and_db() -> (Router, Database) {57 pub async fn app_and_db() -> (Router, Database) {
@@ -49,7 +61,7 @@ pub async fn app_and_db() -> (Router, Database) {
49 /// [`app_and_db`] plus the registry behind it, for the suites whose subject is61 /// [`app_and_db`] plus the registry behind it, for the suites whose subject is
50 /// tenancy itself (a second school, a suspension, the builder surface).62 /// tenancy itself (a second school, a suspension, the builder surface).
51 pub async fn app_and_tenants() -> (Router, Database, Tenants) {63 pub async fn app_and_tenants() -> (Router, Database, Tenants) {
52- let (app, db, tenants) = app_parts(None, Default::default(), Metrics::noop()).await;64+ let (app, db, tenants) = app_parts(None, Metrics::noop()).await;
53 (app, db, tenants)65 (app, db, tenants)
54 }66 }
55 67
@@ -71,12 +83,12 @@ pub fn cookie_token(cookie: &str) -> &str {
71 .183 .1
72 }84 }
73 85
74-/// An in-memory deployment: the registry, plus the demo school's handle. For86+/// A test deployment: the registry, plus the demo school's handle. For the
75-/// the suites that build their own `AppState` instead of using [`app_and_db`].87+/// suites that build their own `AppState` instead of using [`app_and_db`].
88+/// (The name outlived the in-memory engine; the shape is what the suites
89+/// bind to.)
76 pub async fn mem_deployment() -> (Tenants, Database) {90 pub async fn mem_deployment() -> (Tenants, Database) {
77- let tenants = database::init_mem_tenants()91+ let tenants = database::init_test_tenants().await;
78- .await
79- .expect("in-memory deployment");
80 let db = demo_db(&tenants).await;92 let db = demo_db(&tenants).await;
81 (tenants, db)93 (tenants, db)
82 }94 }
@@ -93,35 +105,22 @@ pub async fn demo_db(tenants: &Tenants) -> Database {
93 /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the105 /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the
94 /// bootstrap that makes a QUIC service's reads dispatch into a real router.106 /// bootstrap that makes a QUIC service's reads dispatch into a real router.
95 pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {107 pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
96- app_with_ai_health(ai, Default::default()).await108+ let (app, db, _) = app_parts(ai, Metrics::noop()).await;
109+ (app, db)
97 }110 }
98 111
99 /// [`app_with_ai`] plus the registry behind it, for the suites whose subject is112 /// [`app_with_ai`] plus the registry behind it, for the suites whose subject is
100 /// an AI service reading *across* schools.113 /// an AI service reading *across* schools.
101 pub async fn app_with_ai_tenants(ai: Option<AiBridge>) -> (Router, Database, Tenants) {114 pub async fn app_with_ai_tenants(ai: Option<AiBridge>) -> (Router, Database, Tenants) {
102- app_parts(ai, Default::default(), Metrics::noop()).await115+ app_parts(ai, Metrics::noop()).await
103-}
104-
105-/// [`app_with_ai`] with the liveness flag handed in, so a test can take the
106-/// database socket down under a running app — the api-read path re-checks it in
107-/// place of the HTTP db guard it bypasses.
108-pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database) {
109- let (app, db, _) = app_parts(ai, db_up, Metrics::noop()).await;
110- (app, db)
111 }116 }
112 117
113-/// The one bootstrap: an in-memory deployment (control database + the demo118+/// The one bootstrap: a fresh test deployment (control database + the demo
114 /// school), a router over it, and the demo school's handle — which is what119 /// school), a router over it, and the demo school's handle — which is what
115 /// every suite means by "the database", since that is where users and rows120 /// every suite means by "the database", since that is where users and rows
116 /// live.121 /// live.
117-async fn app_parts(122+async fn app_parts(ai: Option<AiBridge>, metrics: Metrics) -> (Router, Database, Tenants) {
118- ai: Option<AiBridge>,123+ let tenants = database::init_test_tenants().await;
119- db_up: DbHealth,
120- metrics: hezarfen_backend::telemetry::Metrics,
121-) -> (Router, Database, Tenants) {
122- let tenants = database::init_mem_tenants()
123- .await
124- .expect("in-memory deployment");
125 let db = demo_db(&tenants).await;124 let db = demo_db(&tenants).await;
126 let app = build_router(AppState {125 let app = build_router(AppState {
127 db: tenants.control().clone(),126 db: tenants.control().clone(),
@@ -134,7 +133,6 @@ async fn app_parts(
134 chatbot_limit: Default::default(),133 chatbot_limit: Default::default(),
135 exam_presence: Default::default(),134 exam_presence: Default::default(),
136 board_hub: Default::default(),135 board_hub: Default::default(),
137- db_up,
138 ai,136 ai,
139 metrics,137 metrics,
140 });138 });
@@ -144,7 +142,7 @@ async fn app_parts(
144 /// The same router with the caller's instruments, so a test can read back what142 /// The same router with the caller's instruments, so a test can read back what
145 /// the HTTP edge recorded without touching the process-global meter provider.143 /// the HTTP edge recorded without touching the process-global meter provider.
146 pub async fn app_with_metrics(metrics: Metrics) -> (Router, Database) {144 pub async fn app_with_metrics(metrics: Metrics) -> (Router, Database) {
147- let (app, db, _) = app_parts(None, Default::default(), metrics).await;145+ let (app, db, _) = app_parts(None, metrics).await;
148 (app, db)146 (app, db)
149 }147 }
150 148
@@ -180,21 +178,21 @@ pub fn is_forbidden_key(key: &str) -> bool {
180 || key.starts_with("http.response.header.")178 || key.starts_with("http.response.header.")
181 }179 }
182 180
183-/// A router backed by a fresh in-memory database.181+/// A router backed by a fresh per-test Postgres deployment.
184 pub async fn mem_app() -> Router {182 pub async fn mem_app() -> Router {
185 app_and_db().await.0183 app_and_db().await.0
186 }184 }
187 185
188-/// Force `username`'s role, mirroring the manual `UPDATE user SET role=...`186+/// Force `username`'s role, mirroring the manual `UPDATE app_user SET
189-/// bootstrap. Roles are read fresh per request, so this takes effect at once.187+/// role=...` bootstrap. Roles are read fresh per request, so this takes
188+/// effect at once.
190 pub async fn set_role(db: &Database, username: &str, role: &str) {189 pub async fn set_role(db: &Database, username: &str, role: &str) {
191- db.query("UPDATE user SET role = $role WHERE username = $u")190+ sqlx::query("UPDATE app_user SET role = $2 WHERE username = $1")
192- .bind(("role", role.to_string()))191+ .bind(username)
193- .bind(("u", username.to_string()))192+ .bind(role)
193+ .execute(db)
194 .await194 .await
195- .expect("set_role query")195+ .expect("set_role query");
196- .check()
197- .expect("set_role check");
198 }196 }
199 197
200 /// Register (password `secret1`), promote to `role`, then log in. Returns the198 /// 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) {
565 assert_eq!(res.status, StatusCode::OK, "enroll {user_id}");563 assert_eq!(res.status, StatusCode::OK, "enroll {user_id}");
566 }564 }
567 565
568-// ---- remote (production) mode -------------------------------------------566+// ---- multi-school deployments ---------------------------------------------
569 //567 //
570-// `Mode::Mem` gives every school its own embedded datastore, so cross-school568+// The probes whose subject is tenancy itself — cross-school isolation,
571-// isolation *cannot* fail there. Production is `Mode::Remote`: one server, one569+// suspension, school deletion — build a deployment with more schools than
572-// namespace, a database per school, isolation resting entirely on each570+// the demo one. Under database-per-school tenancy there is no separate
573-// connection's `use_db` pin. The isolation probes therefore run in both modes,571+// "remote" mode to exercise: production *is* this shape, and a second
574-// and the remote half needs a real server — this is it.572+// deployment is a second `database::init_test_tenants()` away. (The
575-573+// `surreal start` remote lane this section used to hold died with the
576-/// A throwaway `surreal start … memory` server. Owned by the deployments using574+// embedded engine.)
577-/// it: killed as soon as the last one drops, which is what keeps both runners575+
578-/// clean — `cargo test` (one process, many tests, one shared server) and576+/// A deployment with its own blob directory: what the tenancy probes hold.
579-/// `cargo nextest` (process per test, so the kill has to happen inside the577+pub struct TestDeployment {
580-/// test, not at some exit hook the harness never runs).
581-pub struct RemoteServer {
582- child: std::sync::Mutex<std::process::Child>,
583- pub url: String,
584-}
585-
586-impl Drop for RemoteServer {
587- fn drop(&mut self) {
588- let mut child = self.child.lock().expect("server lock");
589- let _ = child.kill();
590- let _ = child.wait();
591- }
592-}
593-
594-/// The live server, if one is still held; otherwise the next call spawns a new
595-/// one. A `Weak` and not the server itself: a `&'static` could never be
596-/// dropped, and an un-dropped child is a leaked `surreal` per test process.
597-static REMOTE: OnceLock<std::sync::Mutex<std::sync::Weak<RemoteServer>>> = OnceLock::new();
598-
599-const SURREAL_BIN: &str = ".surrealdb/surreal";
600-const SURREAL_HINT: &str = "install it with `curl -sSf https://install.surrealdb.com | sh`, \
601- or set HEZARFEN_SKIP_REMOTE=1 to skip the production-mode isolation tests";
602-
603-/// The shared server, or `None` when `HEZARFEN_SKIP_REMOTE=1` says to skip.
604-/// A missing binary is a **panic**: remote-mode isolation is the mode
605-/// production runs in, so it must never quietly not-run.
606-pub fn remote_server() -> Option<std::sync::Arc<RemoteServer>> {
607- if std::env::var("HEZARFEN_SKIP_REMOTE").as_deref() == Ok("1") {
608- eprintln!("HEZARFEN_SKIP_REMOTE=1 — remote-mode isolation NOT exercised");
609- return None;
610- }
611- let mut slot = REMOTE
612- .get_or_init(Default::default)
613- .lock()
614- .expect("remote server slot");
615- if let Some(server) = slot.upgrade() {
616- return Some(server);
617- }
618- let bin = PathBuf::from(std::env::var("HOME").expect("HOME")).join(SURREAL_BIN);
619- assert!(
620- bin.exists(),
621- "no surreal binary at {} — {SURREAL_HINT}",
622- bin.display()
623- );
624- // Pick the port by binding and releasing it: two test *processes* (nextest)
625- // each want a server of their own, and a fixed port would collide.
626- let port = std::net::TcpListener::bind("127.0.0.1:0")
627- .expect("a free port")
628- .local_addr()
629- .expect("the bound address")
630- .port();
631- let child = std::process::Command::new(&bin)
632- .args([
633- "start",
634- "--user",
635- "root",
636- "--pass",
637- "root",
638- "--bind",
639- &format!("127.0.0.1:{port}"),
640- "memory",
641- ])
642- .stdout(std::process::Stdio::null())
643- .stderr(std::process::Stdio::null())
644- .spawn()
645- .unwrap_or_else(|err| panic!("spawn {}: {err}", bin.display()));
646- let server = std::sync::Arc::new(RemoteServer {
647- child: std::sync::Mutex::new(child),
648- url: format!("ws://127.0.0.1:{port}"),
649- });
650- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
651- while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
652- assert!(
653- std::time::Instant::now() < deadline,
654- "surreal never listened on 127.0.0.1:{port}"
655- );
656- std::thread::sleep(std::time::Duration::from_millis(20));
657- }
658- *slot = std::sync::Arc::downgrade(&server);
659- Some(server)
660-}
661-
662-/// A deployment on the shared server: its own namespace, its own blob
663-/// directory, and the server handle that must outlive both.
664-pub struct RemoteDeployment {
665 pub app: Router,578 pub app: Router,
666 pub tenants: Tenants,579 pub tenants: Tenants,
667- /// The scratch namespace this deployment owns, so a test can name it.580+ /// `FILES_PATH` — this deployment's own directory, never the shared
668- pub ns: String,581+ /// [`files_dir`], so one deployment's uploads cannot be counted by
669- /// `FILES_PATH` — one per deployment, never the shared [`files_dir`], so a582+ /// another's probes.
670- /// remote run's uploads cannot be counted by a memory-mode probe.
671 pub files: PathBuf,583 pub files: PathBuf,
672 _files: TempDir,584 _files: TempDir,
673- _server: std::sync::Arc<RemoteServer>,
674 }585 }
675 586
676-/// The remote twin of [`app_and_tenants`]: a real control database in a587+/// [`app_and_tenants`] with named schools created alongside the demo — where
677-/// namespace of its own, the named schools created in it, and the same router588+/// the former `remote_deployment` probes re-point. The named schools go
678-/// over the same `AppState`. `None` when the remote lane is skipped.589+/// through the real [`Tenants::create`], since the create path is part of
679-pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option<RemoteDeployment> {590+/// what the tenancy probes examine.
680- let server = remote_server()?;591+pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment {
681 let files = tempfile::tempdir().expect("files tempdir");592 let files = tempfile::tempdir().expect("files tempdir");
682- // Unique per call: every test in a process shares one server, and a593+ let tenants = database::init_test_tenants().await;
683- // namespace collision would put two deployments on one control database.
684- static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
685- let ns = format!(
686- "t{}x{}",
687- std::process::id(),
688- NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
689- );
690- let cfg = hezarfen_backend::config::Config {
691- host: "127.0.0.1".into(),
692- port: 0,
693- db_url: server.url.clone(),
694- db_user: "root".into(),
695- db_pass: "root".into(),
696- db_ns: ns.clone(),
697- db_name: "control".into(),
698- files_path: files.path().display().to_string(),
699- cookie_secure: false,
700- rate_limit: RateLimitConfig::unlimited(),
701- chatbot_per_minute: 0,
702- builder_username: None,
703- builder_password: None,
704- ai_quic_addr: None,
705- ai_shared_token: None,
706- ai_tls_cert: None,
707- ai_tls_key: None,
708- ai_request_timeout_secs: 30,
709- };
710- let tenants = database::init(&cfg).await.expect("remote control database");
711 for (slug, name) in schools {594 for (slug, name) in schools {
712 tenants595 tenants
713 .create(596 .create(
@@ -727,16 +610,13 @@ pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option<RemoteDeploym
727 chatbot_limit: Default::default(),610 chatbot_limit: Default::default(),
728 exam_presence: Default::default(),611 exam_presence: Default::default(),
729 board_hub: Default::default(),612 board_hub: Default::default(),
730- db_up: Default::default(),
731 ai: None,613 ai: None,
732 metrics: Metrics::noop(),614 metrics: Metrics::noop(),
733 });615 });
734- Some(RemoteDeployment {616+ TestDeployment {
735 app,617 app,
736 tenants,618 tenants,
737- ns,
738 files: files.path().to_path_buf(),619 files: files.path().to_path_buf(),
739 _files: files,620 _files: files,
740- _server: server,621+ }
741- })
742 }622 }