forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBebffd41Ahmet Kaan Gümüş2 months ago509 commits

database.rs993 lines, 41.7 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 resolved at runtime from the checkout's `CARGO_MANIFEST_DIR` or,
10//! for a deployed binary, from beside the executable (see [`migrations_path`]).
11//! Their table names are disjoint by design, which is what lets one prepare
12//! database carry the union for the compile-time `query!` checks.
13
14use std::collections::HashSet;
15use std::path::Path;
16use std::sync::{Arc, LazyLock, Mutex};
17use std::time::Duration;
18
19use sha2::{Digest, Sha256};
20use sqlx::PgPool;
21use sqlx::migrate::{MigrateError, Migrator};
22use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};
23
24use crate::config::Config;
25use crate::constant::{
26 CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS, RAG_PENDING_STALE_SECS,
27};
28use crate::domain::timestamp::Timestamp;
29use crate::domain::user::{Password, Username};
30use crate::error::AppError;
31use crate::module::ModuleSet;
32use crate::tenant::{DEMO_SLUG, SchoolId, SchoolStatus, Tenants, school_db_name};
33
34/// The shared database handle.
35///
36/// `PgPool` is an `Arc` around its internals, so cloning shares the one pool —
37/// axum cloning the application state per request costs an atomic increment,
38/// nothing more.
39pub type Database = sqlx::PgPool;
40
41/// Connect to the **control** database, apply the control schema, seed the
42/// builder account and ensure the school-template database. School databases
43/// are brought up separately, one per school, by [`crate::tenant::Tenants`].
44///
45/// The dial is retried forever (one-second cadence): the database is normally
46/// a sibling container booting in parallel, and a process that exits on the
47/// first refusal gets restarted by the runtime, fails again in ~100ms, and
48/// burns its whole restart budget inside a second — leaving the backend
49/// permanently down over a startup skew that would have cleared on its own.
50/// Only the *connection* is retried. Bad credentials or a broken migration
51/// still fail hard, since no amount of waiting fixes those.
52pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
53 // Validated before the connection, not after: half a credential pair is a
54 // deployment mistake, and reporting it only after a successful dial buries
55 // it under an outage that isn't one.
56 let builder = builder_credentials(cfg)?;
57
58 let (base, control_db) = parse_base(cfg)?;
59
60 let control = loop {
61 match boot_control(&base).await {
62 Ok(pool) => break pool,
63 Err(err) if boot_failure_retryable(&err) => {
64 tracing::warn!(
65 "database at postgres://{}:{} unreachable ({err}) — retrying in 1s",
66 base.get_host(),
67 base.get_port(),
68 );
69 tokio::time::sleep(Duration::from_secs(1)).await;
70 }
71 Err(err) => return Err(err.into()),
72 }
73 };
74
75 if let Some((username, password)) = builder {
76 crate::service::builder::ensure(&control, username, password).await?;
77 }
78
79 // The template every school schema is validated against at boot: created
80 // outside any transaction (`CREATE DATABASE` cannot run inside one —
81 // `Pool::execute` runs bare autocommit statements), migrated once, then
82 // closed. A first boot lost to a concurrent boot of the same deployment
83 // adopts the winner's template — see [`ensure_database`].
84 let template = format!("{control_db}_school_template");
85 ensure_template(&control, &base, &template).await?;
86
87 let tenants = Tenants::new(control, base, control_db);
88 // Schools a previous boot left half-made (its registry row committed, its
89 // database not yet there) are finished before this one serves anything.
90 tenants.reconcile_provisioning().await?;
91
92 Ok(tenants)
93}
94
95/// Parse `DATABASE_URL` into dial options plus the control database's name —
96/// the name every school database hangs off (`{control}_school_{slug}`).
97pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> {
98 let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| {
99 AppError::Internal(format!(
100 "invalid DATABASE_URL ({}): {err}",
101 cfg.database_url
102 ))
103 })?;
104 let db = opts
105 .get_database()
106 .ok_or_else(|| {
107 AppError::Internal(
108 "DATABASE_URL names no database — the school databases are named after it".into(),
109 )
110 })?
111 .to_string();
112 Ok((opts, db))
113}
114
115/// The pool knobs. The control pool holds 10 connections; each school pool
116/// holds 4 (a school's traffic is one building's worth, and every school pool
117/// draws from the same server's connection budget).
118fn pool_options(max_connections: u32) -> PgPoolOptions {
119 PgPoolOptions::new()
120 .max_connections(max_connections)
121 .min_connections(0)
122 .acquire_timeout(Duration::from_secs(10))
123 .idle_timeout(Duration::from_secs(300))
124 .max_lifetime(Duration::from_secs(1800))
125}
126
127/// A pool over one school database with the school pool sizing. The schema is
128/// the caller's business — [`migrate_school`] for a mint, nothing for a
129/// re-dial of an existing school.
130pub(crate) async fn school_pool(
131 base: &PgConnectOptions,
132 db_name: &str,
133) -> Result<PgPool, AppError> {
134 pool_options(4)
135 .connect_with(base.clone().database(db_name))
136 .await
137 .map_err(Into::into)
138}
139
140/// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier.
141/// The names passed here are the control database's name (from
142/// `DATABASE_URL`), the template's (`{control}_school_template`) or
143/// [`crate::tenant::school_db_name`]'s output — never user input: the control
144/// and template names come from configuration, the school name from a uuid's
145/// hex (fixed `[0-9a-f]`), and an embedded quote is doubled besides, so the
146/// statement cannot be escaped from. That manual audit is what licenses the
147/// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal
148/// query strings without it).
149pub(crate) fn create_database_sql(statement: &str, name: &str) -> String {
150 format!("{statement} \"{}\"", name.replace('"', "\"\""))
151}
152
153/// Create `name` unless the server already has it.
154///
155/// Postgres has no `IF NOT EXISTS` for `CREATE DATABASE` — the clause is a
156/// syntax error there — so the "already there" case can only be settled by a
157/// probe or by swallowing the refusal. Swallowing alone is not enough: a
158/// refused create is *not* quiet, the server logs it as
159/// `ERROR: database "…" already exists`, and a boot that finds its template in
160/// place would print that line on every restart. The probe handles the common
161/// case; the [`is_database_exists`] swallow stays as the backstop for the
162/// window between probe and create, where rival boots win the race and the
163/// statement is issued anyway.
164pub(crate) async fn ensure_database(pool: &PgPool, name: &str) -> Result<(), sqlx::Error> {
165 let present =
166 sqlx::query_scalar::<_, i64>("SELECT count(*) FROM pg_database WHERE datname = $1")
167 .bind(name)
168 .fetch_one(pool)
169 .await?;
170 if present > 0 {
171 tracing::debug!("database {name} already exists — adopting it");
172 return Ok(());
173 }
174 match sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
175 "CREATE DATABASE",
176 name,
177 )))
178 .execute(pool)
179 .await
180 {
181 Ok(_) => Ok(()),
182 Err(err) if is_database_exists(&err) => {
183 tracing::debug!("database {name} was created by a rival boot — adopting it");
184 Ok(())
185 }
186 Err(err) => Err(err),
187 }
188}
189
190async fn boot_control(base: &PgConnectOptions) -> Result<PgPool, sqlx::Error> {
191 let pool = pool_options(10).connect_with(base.clone()).await?;
192 // The migrator is built here rather than in [`migrator`]: its resolution
193 // failure must classify as a boot error (retry or abort), not skip
194 // straight to `AppError`.
195 let migrator = Migrator::new(migrations_path("control").as_path())
196 .await
197 .map_err(sqlx::Error::from)?;
198 migrator.run(&pool).await?;
199 Ok(pool)
200}
201
202/// Is this boot failure the database not being *there* yet — the only thing
203/// a second of patience can fix? Everything else (a bad migration, a bad
204/// credential, a missing migrations directory) aborts startup immediately.
205fn boot_failure_retryable(err: &sqlx::Error) -> bool {
206 match err {
207 sqlx::Error::Migrate(migrate) => match migrate.as_ref() {
208 MigrateError::Execute(e) | MigrateError::ExecuteMigration(e, _) => is_dial_error(e),
209 _ => false,
210 },
211 e => is_dial_error(e),
212 }
213}
214
215/// Connection-class errors: the server was unreachable or the pool could not
216/// hand out a connection. A migrations statement that *failed* is not here —
217/// its error is `Error::Database`, and no sleep rewrites SQL.
218fn is_dial_error(err: &sqlx::Error) -> bool {
219 matches!(
220 err,
221 sqlx::Error::Io(_)
222 | sqlx::Error::Tls(_)
223 | sqlx::Error::PoolTimedOut
224 | sqlx::Error::PoolClosed
225 // A connection that died mid-handshake can present as protocol
226 // breakage; a fresh dial either works or reports something else.
227 | sqlx::Error::Protocol(_)
228 )
229}
230
231/// The `migrations/<set>` directory: the one under `CARGO_MANIFEST_DIR` (the
232/// dev/CI checkout) when that exists, else the one beside the executable.
233/// Two sets cannot both feed the compile-time `migrate!` macro, so both are
234/// resolved from their paths at runtime — and the compile-time path is baked
235/// on the build machine, so a binary deployed outside a checkout (the release
236/// layout ships `migrations/` next to the binary) must fall back to its own
237/// directory or look for the schema where it was compiled.
238fn migrations_path(set: &str) -> std::path::PathBuf {
239 let manifest = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set);
240 if manifest.is_dir() {
241 return manifest;
242 }
243 if let Ok(exe) = std::env::current_exe()
244 && let Some(dir) = exe.parent()
245 {
246 let beside = dir.join("migrations").join(set);
247 if beside.is_dir() {
248 return beside;
249 }
250 }
251 manifest
252}
253
254async fn migrator(set: &str) -> Result<Migrator, AppError> {
255 Migrator::new(migrations_path(set).as_path())
256 .await
257 .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}")))
258}
259
260/// Apply the control schema (schools, builders, the shared rate-limit
261/// window) to a control database. Idempotent: an already-migrated database
262/// runs nothing. The boot path folds this into [`boot_control`]; suites that
263/// re-boot an existing control database call it directly.
264pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> {
265 migrator("control")
266 .await?
267 .run(pool)
268 .await
269 .map_err(|err| AppError::from(sqlx::Error::from(err)))?;
270 Ok(())
271}
272
273/// Apply the school schema to a school database — the template at boot, every
274/// newly minted school at create — then sweep the chatbot and RAG turns the
275/// previous process owed an answer. Idempotent: an already-migrated database
276/// runs only the sweep.
277pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
278 migrator("school")
279 .await?
280 .run(pool)
281 .await
282 .map_err(|err| AppError::from(sqlx::Error::from(err)))?;
283
284 // An assistant turn is answered by a task in this process, so a restart
285 // can leave its row `pending` with nobody left to complete it. Only rows
286 // past the stale horizon (`CHATBOT_PENDING_STALE_SECS`) are certainly
287 // abandoned though: a young one may still be being answered on the other
288 // side of the AI bridge, and a deploy must not shoot down a turn
289 // dispatched seconds ago. Nothing is lost by waiting — a reader already
290 // presents an over-age `pending` row as failed, and the next boot sweeps
291 // for real whatever crossed the horizon in the meantime.
292 let now = Timestamp::now().as_millis();
293 sqlx::query(
294 "UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
295 completed_at = $1
296 WHERE status = 'pending' AND created_at < $2",
297 )
298 .bind(now)
299 .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000)
300 .execute(pool)
301 .await?;
302 // The RAG nest mirrors the chatbot's asynchronous send, so it owes the
303 // same sweep with its own horizon (`RAG_PENDING_STALE_SECS`): a `rag_message`
304 // left `pending` by the dead process presents as failed to any reader
305 // either way, and the same `interrupted` code records why.
306 sqlx::query(
307 "UPDATE rag_message SET status = 'failed', error_code = 'interrupted',
308 completed_at = $1
309 WHERE status = 'pending' AND created_at < $2",
310 )
311 .bind(now)
312 .bind(now - RAG_PENDING_STALE_SECS * 1_000)
313 .execute(pool)
314 .await?;
315 Ok(())
316}
317
318/// The advisory-lock key [`ensure_template`] holds while it creates and
319/// migrates the template: one name for one control database, contended only
320/// by concurrent boots of the same deployment. Distinct from
321/// [`TEST_TEMPLATE_LOCK_KEY`], which guards a different database.
322const TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6D70_0001;
323
324/// Ensure the school-template database exists and carries the current school
325/// schema. `CREATE DATABASE` runs on the control pool outside any
326/// transaction; a template another boot already made is adopted.
327///
328/// Boots of one deployment can overlap (a rolling restart, two replicas), and
329/// this pair is a critical section across processes for the same reasons the
330/// test harness's is (see [`ensure_test_template`]): unsynchronized, the
331/// creates collide — the loser's `pg_database_datname_index` violation is
332/// logged as a server-side `ERROR` even though [`ensure_database`] swallows
333/// it — and two migrators interleave their DDL on the same fresh database and
334/// kill each other on a duplicate table.
335async fn ensure_template(
336 control: &PgPool,
337 base: &PgConnectOptions,
338 name: &str,
339) -> Result<(), AppError> {
340 // A connection of its own, held for the section: an advisory lock is a
341 // server-wide name, so which connection issues the `CREATE` and the
342 // migrations inside the section does not matter — only that every boot
343 // takes the lock first.
344 let mut session = control.acquire().await?;
345 sqlx::query("SELECT pg_advisory_lock($1)")
346 .bind(TEMPLATE_LOCK_KEY)
347 .execute(&mut *session)
348 .await?;
349 let ensured = ensure_template_locked(control, base, name).await;
350 // Unlocked before anything is returned: the lock is session-scoped and the
351 // connection goes back to the pool, so skipping this on the error path
352 // would wedge every later boot.
353 sqlx::query("SELECT pg_advisory_unlock($1)")
354 .bind(TEMPLATE_LOCK_KEY)
355 .execute(&mut *session)
356 .await?;
357 ensured
358}
359
360/// The template's create-and-migrate, under [`ensure_template`]'s lock.
361async fn ensure_template_locked(
362 control: &PgPool,
363 base: &PgConnectOptions,
364 name: &str,
365) -> Result<(), AppError> {
366 ensure_database(control, name).await?;
367 // One migrator connection, made and closed: the template is never served.
368 let pool = pool_options(1)
369 .connect_with(base.clone().database(name))
370 .await?;
371 let migrated = migrate_school(&pool).await;
372 pool.close().await;
373 migrated
374}
375
376/// `42P04` — the database already exists. The other side of every
377/// "create it unless a rival got there first" move.
378pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool {
379 err.as_database_error()
380 .is_some_and(|db| db.code().as_deref() == Some("42P04"))
381}
382
383/// Is this error "the database is already there"? Two SQLSTATEs say yes:
384/// `42P04`, the duplicate-database check `CREATE DATABASE` runs against the
385/// catalog, and `23505` on `pg_database_datname_index` — how Postgres reports
386/// the *losing* side of two concurrent creates, the name check and the
387/// catalog insert not being one atomic step. Measured on 18.6: four boots
388/// racing on an absent template, three of them got `23505` and died, so a
389/// `42P04`-only guard is too narrow for the very race it exists for.
390pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool {
391 is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index")
392}
393
394/// The violated `UNIQUE` constraint's name, when `err` is a unique violation
395/// (`23505`). The constraint name is the stable handle call sites map
396/// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is
397/// borrowed from the error, not `'static`: the server owns the text.
398pub fn unique_violation(err: &sqlx::Error) -> Option<&str> {
399 let db = err.as_database_error()?;
400 if db.code().as_deref() == Some("23505") {
401 db.constraint()
402 } else {
403 None
404 }
405}
406
407/// The violated `EXCLUDE` constraint's name, when `err` is an exclusion
408/// violation (`23P01`) — the SQLSTATE an exclusion constraint raises, as
409/// distinct from a plain `UNIQUE` (`23505`).
410pub fn exclusion_violation(err: &sqlx::Error) -> Option<&str> {
411 let db = err.as_database_error()?;
412 if db.code().as_deref() == Some("23P01") {
413 db.constraint()
414 } else {
415 None
416 }
417}
418
419/// A foreign-key violation (`23503`): a parent row a statement names is gone.
420pub fn foreign_key_violation(err: &sqlx::Error) -> bool {
421 err.as_database_error()
422 .is_some_and(|db| db.code().as_deref() == Some("23503"))
423}
424
425/// Is this error the transaction *contended*, rather than decided? `40001`
426/// (serialization failure) and `40P01` (deadlock) are Postgres telling two
427/// writers to take turns — the whole reason the retry loop below exists.
428pub fn is_retryable_tx(err: &sqlx::Error) -> bool {
429 err.as_database_error().is_some_and(|db| {
430 let code = db.code();
431 code.as_deref() == Some("40001") || code.as_deref() == Some("40P01")
432 })
433}
434
435/// [`is_retryable_tx`] plus the foreign-key violation. For **cascade**
436/// transactions only: a child insert whose parent vanished mid-cascade means
437/// a racing cascade is still in flight and a re-run sees the settled state —
438/// but to a plain insert a `23503` is a real refusal (the parent is simply
439/// gone), and retrying it would only burn the budget before returning the
440/// same verdict.
441pub fn is_retryable_cascade(err: &sqlx::Error) -> bool {
442 is_retryable_tx(err) || foreign_key_violation(err)
443}
444
445/// Send one guarded `BEGIN…COMMIT` transaction, re-running it while Postgres
446/// answers "contended, retry", and hand back the closure's value.
447///
448/// The closure writes through the transaction's connection (`&mut
449/// PgConnection`), returns its value, and reports refusals as ordinary `Err`s
450/// carrying exactly the `AppError` the web layer owes the caller. A refusal
451/// is a *decision*, so it outranks the retry loop — only `AppError::Db`
452/// errors that [`is_retryable_tx`] (or, when `cascade`, [`is_retryable_cascade`])
453/// recognise are re-sent; everything else comes straight back.
454///
455/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
456/// that span rows are enforced by single-statement CTEs or row locks
457/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
458/// isolation.
459/// The closure is an [`AsyncFnMut`] (edition-2024 async closure, or a plain
460/// closure whose async block the compiler infers as such) because every real
461/// call site's future borrows the connection — a named `Fut` generic cannot
462/// express that lifetime relationship.
463///
464/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
465/// that span rows are enforced by single-statement CTEs or row locks
466/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
467/// isolation; if a transaction genuinely cannot be row-locked, escalate that
468/// one to `SERIALIZABLE` (the retry loop already covers the `40001` it can
469/// then raise) and record the reason in its own call site's comment.
470///
471/// The budget and backoff are the guard layer's usual: `CAP_WRITE_TRIES`
472/// rounds, `backoff`'s exponential-with-jitter wait, attempt zero waiting
473/// not at all.
474pub async fn tx_with_retry<T, F>(pool: &PgPool, cascade: bool, mut f: F) -> Result<T, AppError>
475where
476 F: AsyncFnMut(&mut PgConnection) -> Result<T, AppError>,
477{
478 let mut last: Option<sqlx::Error> = None;
479 for attempt in 0..CAP_WRITE_TRIES {
480 backoff(attempt).await;
481 let mut tx = pool.begin().await?;
482 match f(&mut tx).await {
483 Ok(value) => {
484 // A commit can itself lose the race — `40001` fires at COMMIT
485 // in Postgres — so the commit sits inside the classification.
486 match tx.commit().await {
487 Ok(()) => return Ok(value),
488 Err(err) if is_retryable(&err, cascade) => last = Some(err),
489 Err(err) => return Err(err.into()),
490 }
491 }
492 Err(AppError::Db(err)) if is_retryable(&err, cascade) => {
493 // The losing round wrote nothing durable, which is what makes
494 // re-sending the whole of the recovery. Settle the abort
495 // before the wait, so a connection is not left
496 // idle-in-transaction across the backoff.
497 let _ = tx.rollback().await;
498 last = Some(err);
499 }
500 // A refusal is a decision. Same shape for a `Db` error the
501 // classifier does not recognise: it failed for a reason waiting
502 // cannot fix.
503 Err(err) => return Err(err),
504 }
505 }
506 Err(last
507 .map(AppError::Db)
508 .unwrap_or_else(|| AppError::Internal("a guarded transaction never ran".into())))
509}
510
511fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool {
512 if cascade {
513 is_retryable_cascade(err)
514 } else {
515 is_retryable_tx(err)
516 }
517}
518
519/// Wait out one lost round. Exponential with jitter, because racers arrive in
520/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
521/// Attempt zero waits not at all.
522pub(crate) async fn backoff(attempt: usize) {
523 if attempt == 0 {
524 return;
525 }
526 let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
527 let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
528 tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
529}
530
531/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured.
532/// Both-or-neither: half a pair aborts startup rather than silently running
533/// without the seed — and without a builder, a fresh deployment has nobody who
534/// can create the first school.
535fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
536 match (&cfg.builder_username, &cfg.builder_password) {
537 (Some(username), Some(password)) => Ok(Some((
538 Username::try_new(username)
539 .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?,
540 Password::try_new(password)
541 .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?,
542 ))),
543 (None, None) => Ok(None),
544 _ => Err(AppError::Internal(
545 "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(),
546 )),
547 }
548}
549
550// ---- per-test databases -----------------------------------------------------
551//
552// Every test run gets a **private pair of databases** on the compose Postgres:
553// a control database and the demo school's database, both named after one
554// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_<uuid hex>` — so
555// nextest's parallel processes neither collide nor see each other's rows. The
556// school schema is not migrated per test: it is cloned from a shared template
557// database whose name carries a hash of `migrations/school`, so a schema edit
558// mints a fresh template exactly once and every test after that pays only a
559// cheap `CREATE DATABASE … TEMPLATE`.
560//
561// Cleanup is a lease: every database a deployment minted is recorded in a
562// [`TestDatabases`], and its `Drop` — fired when the deployment's last handle
563// dies — sends `DROP DATABASE … WITH (FORCE)`. A best-effort janitor at first
564// use per process sweeps what a crashed run left behind: only databases past
565// a minimum age are candidates, and their `DROP` carries no `WITH (FORCE)`,
566// so a live parallel test's databases (connected backends, young name) are
567// never touched.
568//
569// These functions are `pub` rather than `#[cfg(test)]` because the
570// integration tests live outside the crate, and `#[doc(hidden)]` because they
571// are not part of the API. Their SQL is runtime-checked — the query-style
572// rule exempts all test-side SQL from the macros.
573
574/// The Postgres server the test databases are minted on. The default is the
575/// compose stack's maintenance database (`.env.example` documents it).
576const TEST_DATABASE_URL_ENV: &str = "HEZARFEN_TEST_DATABASE_URL";
577const TEST_DATABASE_URL_DEFAULT: &str = "postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres";
578
579/// Every test database carries this prefix; the janitor only ever drops
580/// databases it names.
581const TEST_DB_PREFIX: &str = "heztest_";
582
583/// How old a `heztest_%` database must be before the janitor will touch it.
584/// Anything younger belongs to a test in a parallel process — nextest mints
585/// them by the dozen in overlapping seconds.
586const TEST_DB_LEFTOVER_MIN_AGE_MS: i64 = 5 * 60 * 1000;
587
588/// The advisory-lock key the template's create-and-migrate critical section
589/// holds (see [`ensure_test_template`]). An arbitrary constant — it only has
590/// to be one nobody else on the server uses.
591const TEST_TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6500_0001;
592
593/// The databases one test deployment minted, and the promise to drop them.
594///
595/// Cloning shares the lease; the `DROP` statements fire when the **last**
596/// copy drops — which is why a [`Tenants`] can carry one: the databases die
597/// exactly when the test deployment does, even though the `Router` and the
598/// test body hold separate clones of the registry.
599#[doc(hidden)]
600#[derive(Clone)]
601pub struct TestDatabases(Arc<TestLease>);
602
603struct TestLease {
604 /// How to reach the maintenance database when the drops run. Dial options,
605 /// not a pool: the pools a test built belong to the test's runtime and
606 /// cannot be borrowed from the drop thread after that runtime dies — the
607 /// drop dials its own one-connection pool instead.
608 maintenance: PgConnectOptions,
609 names: Mutex<Vec<String>>,
610}
611
612impl TestDatabases {
613 fn new(maintenance: PgConnectOptions) -> Self {
614 Self(Arc::new(TestLease {
615 maintenance,
616 names: Mutex::new(Vec::new()),
617 }))
618 }
619
620 pub(crate) fn track(&self, name: &str) {
621 self.0
622 .names
623 .lock()
624 .expect("test lease names")
625 .push(name.to_owned());
626 }
627
628 /// The database names this lease still owes a drop. Diagnostics only.
629 pub fn names(&self) -> Vec<String> {
630 self.0.names.lock().expect("test lease names").clone()
631 }
632}
633
634impl std::fmt::Debug for TestDatabases {
635 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
636 f.debug_struct("TestDatabases")
637 .field("names", &self.names())
638 .finish()
639 }
640}
641
642impl Drop for TestLease {
643 fn drop(&mut self) {
644 let names = std::mem::take(&mut *self.names.lock().expect("test lease names"));
645 let maintenance = self.maintenance.clone();
646 if names.is_empty() {
647 return;
648 }
649 let run = move || {
650 let runtime = tokio::runtime::Builder::new_current_thread()
651 .enable_all()
652 .build()
653 .expect("test-lease drop runtime");
654 runtime.block_on(async move {
655 let Ok(maintenance) = pool_options(1).connect_with(maintenance).await else {
656 eprintln!(
657 "test lease: cannot reach the maintenance database to drop {names:?}"
658 );
659 return;
660 };
661 for name in &names {
662 let sql =
663 create_database_sql("DROP DATABASE IF EXISTS", name) + " WITH (FORCE)";
664 if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
665 .execute(&maintenance)
666 .await
667 {
668 eprintln!("test lease: dropping {name} failed: {err}");
669 }
670 }
671 maintenance.close().await;
672 });
673 };
674 // A lease usually dies inside the test's runtime (the last registry
675 // handle drops at the end of the test future), and a runtime may not
676 // be built inside another — so the drops always run on a dedicated
677 // thread. The wait is bounded: a wedged server cannot hang the test's
678 // teardown forever, and the janitor is the backstop for whatever
679 // outlives it.
680 match tokio::runtime::Handle::try_current() {
681 Ok(_) => {
682 let (done, done_rx) = std::sync::mpsc::channel();
683 std::thread::spawn(move || {
684 run();
685 let _ = done.send(());
686 });
687 let _ = done_rx.recv_timeout(Duration::from_secs(10));
688 }
689 Err(_) => run(),
690 }
691 }
692}
693
694/// A complete test deployment: a fresh control database plus the demo school,
695/// whose database is cloned from the shared school template and registered in
696/// the control registry under the slug every suite names ([`DEMO_SLUG`]).
697///
698/// The databases die with the returned registry's last handle (see
699/// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind.
700#[doc(hidden)]
701pub async fn init_test_tenants() -> Tenants {
702 let maintenance = maintenance_pool().await;
703 janitor(&maintenance).await;
704 let base = test_base();
705 let lease = TestDatabases::new(base.clone());
706
707 let control_db = format!("{TEST_DB_PREFIX}{}", test_suffix());
708 create_database(&maintenance, &control_db, None).await;
709 lease.track(&control_db);
710 let control = boot_control(&base.clone().database(&control_db))
711 .await
712 .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));
713
714 let template = ensure_test_template(&maintenance, &base).await;
715 let demo_id = SchoolId::generate();
716 let school_db = school_db_name(&control_db, demo_id.uuid());
717 create_database(&maintenance, &school_db, Some(&template)).await;
718 lease.track(&school_db);
719 let school = school_pool(&base, &school_db)
720 .await
721 .unwrap_or_else(|err| panic!("dial the test demo school {school_db}: {err}"));
722
723 // The registry row, exactly as [`Tenants::create`] would write it — but
724 // without the per-school migration its `bring_up` runs, which the
725 // template clone has just replaced.
726 sqlx::query(
727 "INSERT INTO school (id, slug, name, status, created_at)
728 VALUES ($1, $2, $3, $4, $5)",
729 )
730 .bind(demo_id.uuid())
731 .bind(DEMO_SLUG)
732 .bind("Demo School")
733 .bind(SchoolStatus::Active)
734 .bind(Timestamp::now().as_millis())
735 .execute(&control)
736 .await
737 .expect("register the test demo school");
738 for module in ModuleSet::all().names() {
739 sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
740 .bind(demo_id.uuid())
741 .bind(module)
742 .execute(&control)
743 .await
744 .expect("register the test demo school's modules");
745 }
746
747 Tenants::new_test_adopting(
748 control,
749 base.database(&control_db),
750 control_db,
751 lease,
752 [(demo_id, school)],
753 )
754}
755
756/// One school database cloned from the template, for the src-side unit tests
757/// that exercise a single store with no tenancy around it. Keep the lease
758/// alive for the database's lifetime (`let (db, _leases) = …` binds it to the
759/// test's scope); dropping it early drops the database.
760#[doc(hidden)]
761pub async fn init_test_db() -> (Database, TestDatabases) {
762 let maintenance = maintenance_pool().await;
763 janitor(&maintenance).await;
764 let base = test_base();
765 let lease = TestDatabases::new(base.clone());
766 let template = ensure_test_template(&maintenance, &base).await;
767 let name = format!("{TEST_DB_PREFIX}{}", test_suffix());
768 create_database(&maintenance, &name, Some(&template)).await;
769 lease.track(&name);
770 let db = school_pool(&base, &name)
771 .await
772 .unwrap_or_else(|err| panic!("dial the test school database {name}: {err}"));
773 (db, lease)
774}
775
776/// The school template's name, and as a side effect its existence: created
777/// and migrated on first use, adopted when something else already made it.
778/// The name carries a hash of `migrations/school`, so a schema edit mints a
779/// fresh template and every process converges on the same new one.
780///
781/// Competing first uses are real: nextest mints tests in parallel processes
782/// and in parallel test threads, all overlapping on the same millisecond.
783/// One server-wide advisory lock makes the create-and-migrate a critical
784/// section — without it, two migrators interleave their DDL on the same
785/// fresh database and one dies on a duplicate table mid-flight (observed).
786/// The probe + `42P04` swallow are the belt to that brace: a template made
787/// before the lock was ever taken is adopted, not fought.
788async fn ensure_test_template(maintenance: &PgPool, base: &PgConnectOptions) -> String {
789 static ENSURED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
790 let name = template_name();
791 let ensured = &*ENSURED;
792 if ensured.lock().expect("template set").contains(&name) {
793 return name;
794 }
795 let mut session = maintenance
796 .acquire()
797 .await
798 .unwrap_or_else(|err| panic!("lease a maintenance connection: {err}"));
799 sqlx::query("SELECT pg_advisory_lock($1)")
800 .bind(TEST_TEMPLATE_LOCK_KEY)
801 .execute(&mut *session)
802 .await
803 .unwrap_or_else(|err| panic!("lock the school template: {err}"));
804 let exists = sqlx::query_as::<_, (i64,)>("SELECT count(*) FROM pg_database WHERE datname = $1")
805 .bind(&name)
806 .fetch_one(&mut *session)
807 .await
808 .map(|(count,)| count > 0)
809 .unwrap_or_else(|err| panic!("probe for the school template {name}: {err}"));
810 if !exists
811 && let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
812 "CREATE DATABASE",
813 &name,
814 )))
815 .execute(&mut *session)
816 .await
817 && !is_duplicate_database(&err)
818 {
819 panic!("create the school template {name}: {err}");
820 }
821 let pool = pool_options(1)
822 .connect_with(base.clone().database(&name))
823 .await
824 .unwrap_or_else(|err| panic!("dial the school template {name}: {err}"));
825 let migrated = migrate_school(&pool).await;
826 pool.close().await;
827 sqlx::query("SELECT pg_advisory_unlock($1)")
828 .bind(TEST_TEMPLATE_LOCK_KEY)
829 .execute(&mut *session)
830 .await
831 .unwrap_or_else(|err| panic!("unlock the school template: {err}"));
832 migrated.unwrap_or_else(|err| panic!("migrate the school template {name}: {err:?}"));
833 ensured.lock().expect("template set").insert(name.clone());
834 name
835}
836
837/// `heztest_tpl_school_<hash>` — the hash is over `migrations/school`'s file
838/// names and bytes, sorted, so any schema edit changes it.
839fn template_name() -> String {
840 let mut migrations: Vec<std::path::PathBuf> = std::fs::read_dir(migrations_path("school"))
841 .expect("read the school migrations directory")
842 .map(|entry| entry.expect("migration directory entry").path())
843 .collect();
844 migrations.sort();
845 let mut hasher = Sha256::new();
846 for path in migrations {
847 hasher.update(
848 path.file_name()
849 .expect("file name")
850 .to_string_lossy()
851 .as_bytes(),
852 );
853 hasher.update(std::fs::read(&path).expect("read a school migration"));
854 }
855 format!(
856 "{TEST_DB_PREFIX}tpl_school_{}",
857 &hex::encode(hasher.finalize())[..8]
858 )
859}
860
861/// One sweep per process, at the first mint: `heztest_%` databases a crashed
862/// run left behind. See the section header for why a candidate must be old
863/// *and* unconnected before it is dropped.
864async fn janitor(maintenance: &PgPool) {
865 static SWEPT: LazyLock<()> = LazyLock::new(|| {});
866 LazyLock::force(&SWEPT);
867 let template = template_name();
868 let leftovers = sqlx::query_as::<_, (String,)>(
869 "SELECT datname FROM pg_database WHERE datname LIKE 'heztest\\_%' ESCAPE '\\'",
870 )
871 .fetch_all(maintenance)
872 .await
873 .unwrap_or_else(|err| panic!("list leftover test databases: {err}"));
874 for (name,) in leftovers {
875 if name == template || !sweep_candidate(&name) {
876 continue;
877 }
878 // No `WITH (FORCE)`: a database with live backends belongs to a
879 // running test in a parallel process, and the failed drop *is* the
880 // skip.
881 let _ = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
882 "DROP DATABASE IF EXISTS",
883 &name,
884 )))
885 .execute(maintenance)
886 .await;
887 }
888}
889
890/// Should this `heztest_%` database be swept? The suffix's leading eleven hex
891/// digits are the mint time in unix milliseconds; anything that cannot be
892/// read that way is either a template of an older schema hash (swept) or
893/// junk (swept too).
894fn sweep_candidate(name: &str) -> bool {
895 let Some(minted_hex) = name.get(TEST_DB_PREFIX.len()..TEST_DB_PREFIX.len() + 11) else {
896 return true;
897 };
898 match i64::from_str_radix(minted_hex, 16) {
899 Ok(minted_ms) => Timestamp::now().as_millis() - minted_ms > TEST_DB_LEFTOVER_MIN_AGE_MS,
900 Err(_) => name.starts_with(&format!("{TEST_DB_PREFIX}tpl_")),
901 }
902}
903
904/// `<11 hex of unix-ms><5 hex random>`: the mint time, so the janitor can
905/// tell a crashed run's leftovers from a parallel test's fresh databases,
906/// plus just enough randomness that two processes minting in the same
907/// millisecond never collide. The tail is not an id and is drawn straight from
908/// the OS rng: the leading hex digits of a v7 uuid *are* the mint time, which
909/// is exactly what two processes minting in one millisecond share.
910fn test_suffix() -> String {
911 let minted_ms = Timestamp::now().as_millis() as u64;
912 let mut tail = [0_u8; 3];
913 getrandom::fill(&mut tail).expect("the OS rng");
914 let hex = format!("{:02x}{:02x}{:02x}", tail[0], tail[1], tail[2]);
915 format!("{minted_ms:011x}{}", &hex[..5])
916}
917
918/// `CREATE DATABASE` for a harness-minted name, optionally `TEMPLATE`-cloned.
919/// Both names are generated here (prefix + hex suffix), never user input —
920/// the same audit that licenses [`create_database_sql`]'s `AssertSqlSafe`
921/// callers.
922async fn create_database(maintenance: &PgPool, name: &str, template: Option<&str>) {
923 let mut sql = create_database_sql("CREATE DATABASE", name);
924 if let Some(template) = template {
925 sql.push_str(&format!(" TEMPLATE \"{}\"", template.replace('"', "\"\"")));
926 }
927 if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
928 .execute(maintenance)
929 .await
930 {
931 panic!("create the test database {name}: {err}");
932 }
933}
934
935/// Dial options for the test Postgres — `HEZARFEN_TEST_DATABASE_URL` or the
936/// compose default. The URL's database is the *maintenance* database the
937/// `CREATE DATABASE`s run against; the harness names every database itself.
938fn test_base() -> PgConnectOptions {
939 let url = std::env::var(TEST_DATABASE_URL_ENV)
940 .ok()
941 .filter(|url| !url.trim().is_empty())
942 .unwrap_or_else(|| TEST_DATABASE_URL_DEFAULT.to_owned());
943 url.parse().unwrap_or_else(|err| {
944 panic!("{TEST_DATABASE_URL_ENV}={url:?} is not a Postgres URL: {err}")
945 })
946}
947
948/// A small pool over the maintenance database: the janitor's listing and
949/// every `CREATE DATABASE` (DDL — not usable inside a transaction) go
950/// through it, and each lease keeps a clone for its drops.
951async fn maintenance_pool() -> PgPool {
952 pool_options(2)
953 .connect_with(test_base())
954 .await
955 .unwrap_or_else(|err| {
956 panic!(
957 "cannot reach the test Postgres (set {TEST_DATABASE_URL_ENV}, default \
958 {TEST_DATABASE_URL_DEFAULT}): {err} — is the compose stack up?"
959 )
960 })
961}
962
963#[cfg(test)]
964mod builder_seed_tests {
965 use super::builder_credentials;
966 use crate::config::Config;
967
968 fn cfg(username: Option<&str>, password: Option<&str>) -> Config {
969 let mut cfg = Config::from_env();
970 cfg.builder_username = username.map(str::to_string);
971 cfg.builder_password = password.map(str::to_string);
972 cfg
973 }
974
975 #[tokio::test]
976 async fn the_builder_seed_is_both_or_neither() {
977 assert!(builder_credentials(&cfg(None, None)).unwrap().is_none());
978 assert!(
979 builder_credentials(&cfg(Some("builder"), Some("secret1")))
980 .unwrap()
981 .is_some()
982 );
983 // Half a pair aborts startup: a deployment with no builder has nobody
984 // who can create the first school, and a silent run would hide that.
985 assert!(builder_credentials(&cfg(Some("builder"), None)).is_err());
986 assert!(builder_credentials(&cfg(None, Some("secret1"))).is_err());
987 // A pair that is set but invalid aborts too, naming the variable.
988 match builder_credentials(&cfg(Some("!"), Some("secret1"))) {
989 Err(err) => assert!(err.to_string().contains("BUILDER_USERNAME"), "{err}"),
990 Ok(_) => panic!("an invalid BUILDER_USERNAME must abort startup"),
991 }
992 }
993}