forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

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