forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

database.rs846 lines, 34.9 KiBHistoryRawDownload
1//! PostgreSQL connections (sqlx) + the two migration sets + the
2//! guarded-transaction retry loop.
3//!
4//! Two sets of migrations live side by side and never share a tracking table:
5//! `migrations/control` for the control database (schools, builders, the
6//! shared rate-limit window) and `migrations/school` for every school
7//! database. They are applied by two separate [`sqlx::migrate::Migrator`]s —
8//! the compile-time `migrate!` macro cannot be aimed at two directories, so
9//! each is constructed at runtime from its path under `CARGO_MANIFEST_DIR`.
10//! Their table names are disjoint by design, which is what lets one prepare
11//! database carry the union for the compile-time `query!` checks.
12
13use std::collections::HashSet;
14use std::path::Path;
15use std::sync::{Arc, LazyLock, Mutex};
16use std::time::Duration;
17
18use sha2::{Digest, Sha256};
19use sqlx::PgPool;
20use sqlx::migrate::{MigrateError, Migrator};
21use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};
22use uuid::Uuid;
23
24use crate::config::Config;
25use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};
26use crate::domain::timestamp::Timestamp;
27use crate::domain::user::{Password, Username};
28use crate::error::AppError;
29use crate::module::ModuleSet;
30use crate::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants, school_db_name};
31
32/// The shared database handle.
33///
34/// `PgPool` is an `Arc` around its internals, so cloning shares the one pool —
35/// axum cloning the application state per request costs an atomic increment,
36/// nothing more.
37pub type Database = sqlx::PgPool;
38
39/// Connect to the **control** database, apply the control schema, seed the
40/// builder account and ensure the school-template database. School databases
41/// are brought up separately, one per school, by [`crate::tenant::Tenants`].
42///
43/// The dial is retried forever (one-second cadence): the database is normally
44/// a sibling container booting in parallel, and a process that exits on the
45/// first refusal gets restarted by the runtime, fails again in ~100ms, and
46/// burns its whole restart budget inside a second — leaving the backend
47/// permanently down over a startup skew that would have cleared on its own.
48/// Only the *connection* is retried. Bad credentials or a broken migration
49/// still fail hard, since no amount of waiting fixes those.
50pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
51 // Validated before the connection, not after: half a credential pair is a
52 // deployment mistake, and reporting it only after a successful dial buries
53 // it under an outage that isn't one.
54 let builder = builder_credentials(cfg)?;
55
56 let (base, control_db) = parse_base(cfg)?;
57
58 let control = loop {
59 match boot_control(&base).await {
60 Ok(pool) => break pool,
61 Err(err) if boot_failure_retryable(&err) => {
62 tracing::warn!(
63 "database at postgres://{}:{} unreachable ({err}) — retrying in 1s",
64 base.get_host(),
65 base.get_port(),
66 );
67 tokio::time::sleep(Duration::from_secs(1)).await;
68 }
69 Err(err) => return Err(err.into()),
70 }
71 };
72
73 if let Some((username, password)) = builder {
74 crate::service::builder::ensure(&control, username, password).await?;
75 }
76
77 // The template every school schema is validated against at boot: created
78 // outside any transaction (`CREATE DATABASE` cannot run inside one —
79 // `Pool::execute` runs bare autocommit statements), migrated once, then
80 // closed. A first boot lost to a concurrent boot of the same deployment
81 // adopts the winner's template via the duplicate-database swallow.
82 let template = format!("{control_db}_school_template");
83 ensure_template(&control, &base, &template).await?;
84
85 Ok(Tenants::new(control, base, control_db))
86}
87
88/// Parse `DATABASE_URL` into dial options plus the control database's name —
89/// the name every school database hangs off (`{control}_school_{slug}`).
90pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> {
91 let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| {
92 AppError::Internal(format!(
93 "invalid DATABASE_URL ({}): {err}",
94 cfg.database_url
95 ))
96 })?;
97 let db = opts
98 .get_database()
99 .ok_or_else(|| {
100 AppError::Internal(
101 "DATABASE_URL names no database — the school databases are named after it".into(),
102 )
103 })?
104 .to_string();
105 Ok((opts, db))
106}
107
108/// The pool knobs. The control pool holds 10 connections; each school pool
109/// holds 4 (a school's traffic is one building's worth, and every school pool
110/// draws from the same server's connection budget).
111fn pool_options(max_connections: u32) -> PgPoolOptions {
112 PgPoolOptions::new()
113 .max_connections(max_connections)
114 .min_connections(0)
115 .acquire_timeout(Duration::from_secs(10))
116 .idle_timeout(Duration::from_secs(300))
117 .max_lifetime(Duration::from_secs(1800))
118}
119
120/// A pool over one school database with the school pool sizing. The schema is
121/// the caller's business — [`migrate_school`] for a mint, nothing for a
122/// re-dial of an existing school.
123pub(crate) async fn school_pool(
124 base: &PgConnectOptions,
125 db_name: &str,
126) -> Result<PgPool, AppError> {
127 pool_options(4)
128 .connect_with(base.clone().database(db_name))
129 .await
130 .map_err(Into::into)
131}
132
133/// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier.
134/// The names passed here are the control database's name (from
135/// `DATABASE_URL`), the template's (`{control}_school_template`) or
136/// [`crate::tenant::school_db_name`]'s output — never user input: the slug
137/// charset is `[a-z0-9-]` and an embedded quote is doubled, so the statement
138/// cannot be escaped from. That manual audit is what licenses the
139/// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal
140/// query strings without it).
141pub(crate) fn create_database_sql(statement: &str, name: &str) -> String {
142 format!("{statement} \"{}\"", name.replace('"', "\"\""))
143}
144
145async fn boot_control(base: &PgConnectOptions) -> Result<PgPool, sqlx::Error> {
146 let pool = pool_options(10).connect_with(base.clone()).await?;
147 // The migrator is built here rather than in [`migrator`]: its resolution
148 // failure must classify as a boot error (retry or abort), not skip
149 // straight to `AppError`.
150 let migrator = Migrator::new(migrations_path("control").as_path())
151 .await
152 .map_err(sqlx::Error::from)?;
153 migrator.run(&pool).await?;
154 Ok(pool)
155}
156
157/// Is this boot failure the database not being *there* yet — the only thing
158/// a second of patience can fix? Everything else (a bad migration, a bad
159/// credential, a missing migrations directory) aborts startup immediately.
160fn boot_failure_retryable(err: &sqlx::Error) -> bool {
161 match err {
162 sqlx::Error::Migrate(migrate) => match migrate.as_ref() {
163 MigrateError::Execute(e) | MigrateError::ExecuteMigration(e, _) => is_dial_error(e),
164 _ => false,
165 },
166 e => is_dial_error(e),
167 }
168}
169
170/// Connection-class errors: the server was unreachable or the pool could not
171/// hand out a connection. A migrations statement that *failed* is not here —
172/// its error is `Error::Database`, and no sleep rewrites SQL.
173fn is_dial_error(err: &sqlx::Error) -> bool {
174 matches!(
175 err,
176 sqlx::Error::Io(_)
177 | sqlx::Error::Tls(_)
178 | sqlx::Error::PoolTimedOut
179 | sqlx::Error::PoolClosed
180 // A connection that died mid-handshake can present as protocol
181 // breakage; a fresh dial either works or reports something else.
182 | sqlx::Error::Protocol(_)
183 )
184}
185
186/// The `migrations/<set>` directory under `CARGO_MANIFEST_DIR`. Two sets
187/// cannot both feed the compile-time `migrate!` macro, so both are resolved
188/// from their paths at runtime.
189fn migrations_path(set: &str) -> std::path::PathBuf {
190 Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set)
191}
192
193async fn migrator(set: &str) -> Result<Migrator, AppError> {
194 Migrator::new(migrations_path(set).as_path())
195 .await
196 .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}")))
197}
198
199/// Apply the school schema to a school database — the template at boot, every
200/// newly minted school at create — then sweep the chatbot turns the previous
201/// process owed an answer. Idempotent: an already-migrated database runs only
202/// the sweep.
203pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
204 migrator("school")
205 .await?
206 .run(pool)
207 .await
208 .map_err(|err| AppError::from(sqlx::Error::from(err)))?;
209
210 // An assistant turn is answered by a task in this process, so a restart
211 // can leave its row `pending` with nobody left to complete it. Only rows
212 // past the stale horizon (`CHATBOT_PENDING_STALE_SECS`) are certainly
213 // abandoned though: a young one may still be being answered on the other
214 // side of the AI bridge, and a deploy must not shoot down a turn
215 // dispatched seconds ago. Nothing is lost by waiting — a reader already
216 // presents an over-age `pending` row as failed, and the next boot sweeps
217 // for real whatever crossed the horizon in the meantime.
218 let now = Timestamp::now().as_millis();
219 sqlx::query(
220 "UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
221 completed_at = $1
222 WHERE status = 'pending' AND created_at < $2",
223 )
224 .bind(now)
225 .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000)
226 .execute(pool)
227 .await?;
228 Ok(())
229}
230
231/// Ensure the school-template database exists and carries the current school
232/// schema. `CREATE DATABASE` runs on the control pool outside any
233/// transaction; the loser of a race adopts the winner's database.
234async fn ensure_template(
235 control: &PgPool,
236 base: &PgConnectOptions,
237 name: &str,
238) -> Result<(), AppError> {
239 if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
240 "CREATE DATABASE",
241 name,
242 )))
243 .execute(control)
244 .await
245 {
246 if !is_duplicate_database(&err) {
247 return Err(err.into());
248 }
249 }
250 // One migrator connection, made and closed: the template is never served.
251 let pool = pool_options(1)
252 .connect_with(base.clone().database(name))
253 .await?;
254 let migrated = migrate_school(&pool).await;
255 pool.close().await;
256 migrated
257}
258
259/// `42P04` — the database already exists. The other side of every
260/// "create it unless a rival got there first" move.
261pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool {
262 err.as_database_error()
263 .is_some_and(|db| db.code().as_deref() == Some("42P04"))
264}
265
266/// The violated `UNIQUE` constraint's name, when `err` is a unique violation
267/// (`23505`). The constraint name is the stable handle call sites map
268/// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is
269/// borrowed from the error, not `'static`: the server owns the text.
270pub fn unique_violation(err: &sqlx::Error) -> Option<&str> {
271 let db = err.as_database_error()?;
272 if db.code().as_deref() == Some("23505") {
273 db.constraint()
274 } else {
275 None
276 }
277}
278
279/// A foreign-key violation (`23503`): a parent row a statement names is gone.
280pub fn foreign_key_violation(err: &sqlx::Error) -> bool {
281 err.as_database_error()
282 .is_some_and(|db| db.code().as_deref() == Some("23503"))
283}
284
285/// Is this error the transaction *contended*, rather than decided? `40001`
286/// (serialization failure) and `40P01` (deadlock) are Postgres telling two
287/// writers to take turns — the whole reason the retry loop below exists.
288pub fn is_retryable_tx(err: &sqlx::Error) -> bool {
289 err.as_database_error().is_some_and(|db| {
290 let code = db.code();
291 code.as_deref() == Some("40001") || code.as_deref() == Some("40P01")
292 })
293}
294
295/// [`is_retryable_tx`] plus the foreign-key violation. For **cascade**
296/// transactions only: a child insert whose parent vanished mid-cascade means
297/// a racing cascade is still in flight and a re-run sees the settled state —
298/// but to a plain insert a `23503` is a real refusal (the parent is simply
299/// gone), and retrying it would only burn the budget before returning the
300/// same verdict.
301pub fn is_retryable_cascade(err: &sqlx::Error) -> bool {
302 is_retryable_tx(err) || foreign_key_violation(err)
303}
304
305/// Send one guarded `BEGIN…COMMIT` transaction, re-running it while Postgres
306/// answers "contended, retry", and hand back the closure's value.
307///
308/// The closure writes through the transaction's connection (`&mut
309/// PgConnection`), returns its value, and reports refusals as ordinary `Err`s
310/// carrying exactly the `AppError` the web layer owes the caller. A refusal
311/// is a *decision*, so it outranks the retry loop — only `AppError::Db`
312/// errors that [`is_retryable_tx`] (or, when `cascade`, [`is_retryable_cascade`])
313/// recognise are re-sent; everything else comes straight back.
314///
315/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
316/// that span rows are enforced by single-statement CTEs or row locks
317/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
318/// isolation.
319/// The closure is an [`AsyncFnMut`] (edition-2024 async closure, or a plain
320/// closure whose async block the compiler infers as such) because every real
321/// call site's future borrows the connection — a named `Fut` generic cannot
322/// express that lifetime relationship.
323///
324/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
325/// that span rows are enforced by single-statement CTEs or row locks
326/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
327/// isolation; if a transaction genuinely cannot be row-locked, escalate that
328/// one to `SERIALIZABLE` (the retry loop already covers the `40001` it can
329/// then raise) and record the reason in its own call site's comment.
330///
331/// The budget and backoff are the guard layer's usual: `CAP_WRITE_TRIES`
332/// rounds, `backoff`'s exponential-with-jitter wait, attempt zero waiting
333/// not at all.
334pub async fn tx_with_retry<T, F>(pool: &PgPool, cascade: bool, mut f: F) -> Result<T, AppError>
335where
336 F: AsyncFnMut(&mut PgConnection) -> Result<T, AppError>,
337{
338 let mut last: Option<sqlx::Error> = None;
339 for attempt in 0..CAP_WRITE_TRIES {
340 backoff(attempt).await;
341 let mut tx = pool.begin().await?;
342 match f(&mut tx).await {
343 Ok(value) => {
344 // A commit can itself lose the race — `40001` fires at COMMIT
345 // in Postgres — so the commit sits inside the classification.
346 match tx.commit().await {
347 Ok(()) => return Ok(value),
348 Err(err) if is_retryable(&err, cascade) => last = Some(err),
349 Err(err) => return Err(err.into()),
350 }
351 }
352 Err(AppError::Db(err)) if is_retryable(&err, cascade) => {
353 // The losing round wrote nothing durable, which is what makes
354 // re-sending the whole of the recovery. Settle the abort
355 // before the wait, so a connection is not left
356 // idle-in-transaction across the backoff.
357 let _ = tx.rollback().await;
358 last = Some(err);
359 }
360 // A refusal is a decision. Same shape for a `Db` error the
361 // classifier does not recognise: it failed for a reason waiting
362 // cannot fix.
363 Err(err) => return Err(err),
364 }
365 }
366 Err(last
367 .map(AppError::Db)
368 .unwrap_or_else(|| AppError::Internal("a guarded transaction never ran".into())))
369}
370
371fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool {
372 if cascade {
373 is_retryable_cascade(err)
374 } else {
375 is_retryable_tx(err)
376 }
377}
378
379/// Wait out one lost round. Exponential with jitter, because racers arrive in
380/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
381/// Attempt zero waits not at all.
382pub(crate) async fn backoff(attempt: usize) {
383 if attempt == 0 {
384 return;
385 }
386 let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
387 let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
388 tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
389}
390
391/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured.
392/// Both-or-neither: half a pair aborts startup rather than silently running
393/// without the seed — and without a builder, a fresh deployment has nobody who
394/// can create the first school.
395fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
396 match (&cfg.builder_username, &cfg.builder_password) {
397 (Some(username), Some(password)) => Ok(Some((
398 Username::try_new(username)
399 .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?,
400 Password::try_new(password)
401 .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?,
402 ))),
403 (None, None) => Ok(None),
404 _ => Err(AppError::Internal(
405 "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(),
406 )),
407 }
408}
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).
436const TEST_DATABASE_URL_ENV: &str = "HEZARFEN_TEST_DATABASE_URL";
437const 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.
441const 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.
446const 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.
451const 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)]
461pub struct TestDatabases(Arc<TestLease>);
462
463struct 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
472impl 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
494impl 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
502impl 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)]
561pub 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)]
614pub 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.
641async 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.
694fn 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.
719async 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).
749fn 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.
763fn 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.
775async 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.
791fn 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.
804async 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
816#[cfg(test)]
817mod builder_seed_tests {
818 use super::builder_credentials;
819 use crate::config::Config;
820
821 fn cfg(username: Option<&str>, password: Option<&str>) -> Config {
822 let mut cfg = Config::from_env();
823 cfg.builder_username = username.map(str::to_string);
824 cfg.builder_password = password.map(str::to_string);
825 cfg
826 }
827
828 #[tokio::test]
829 async fn the_builder_seed_is_both_or_neither() {
830 assert!(builder_credentials(&cfg(None, None)).unwrap().is_none());
831 assert!(
832 builder_credentials(&cfg(Some("builder"), Some("secret1")))
833 .unwrap()
834 .is_some()
835 );
836 // Half a pair aborts startup: a deployment with no builder has nobody
837 // who can create the first school, and a silent run would hide that.
838 assert!(builder_credentials(&cfg(Some("builder"), None)).is_err());
839 assert!(builder_credentials(&cfg(None, Some("secret1"))).is_err());
840 // A pair that is set but invalid aborts too, naming the variable.
841 match builder_credentials(&cfg(Some("!"), Some("secret1"))) {
842 Err(err) => assert!(err.to_string().contains("BUILDER_USERNAME"), "{err}"),
843 Ok(_) => panic!("an invalid BUILDER_USERNAME must abort startup"),
844 }
845 }
846}