forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

database.rs1040 lines, 44.0 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/// 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_{slug}`).
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/// A foreign-key violation (`23503`): a parent row a statement names is gone.
467pub fn foreign_key_violation(err: &sqlx::Error) -> bool {
468 err.as_database_error()
469 .is_some_and(|db| db.code().as_deref() == Some("23503"))
470}
471
472/// Is this error the transaction *contended*, rather than decided? `40001`
473/// (serialization failure) and `40P01` (deadlock) are Postgres telling two
474/// writers to take turns — the whole reason the retry loop below exists.
475pub fn is_retryable_tx(err: &sqlx::Error) -> bool {
476 err.as_database_error().is_some_and(|db| {
477 let code = db.code();
478 code.as_deref() == Some("40001") || code.as_deref() == Some("40P01")
479 })
480}
481
482/// [`is_retryable_tx`] plus the foreign-key violation. For **cascade**
483/// transactions only: a child insert whose parent vanished mid-cascade means
484/// a racing cascade is still in flight and a re-run sees the settled state —
485/// but to a plain insert a `23503` is a real refusal (the parent is simply
486/// gone), and retrying it would only burn the budget before returning the
487/// same verdict.
488pub fn is_retryable_cascade(err: &sqlx::Error) -> bool {
489 is_retryable_tx(err) || foreign_key_violation(err)
490}
491
492/// Send one guarded `BEGIN…COMMIT` transaction, re-running it while Postgres
493/// answers "contended, retry", and hand back the closure's value.
494///
495/// The closure writes through the transaction's connection (`&mut
496/// PgConnection`), returns its value, and reports refusals as ordinary `Err`s
497/// carrying exactly the `AppError` the web layer owes the caller. A refusal
498/// is a *decision*, so it outranks the retry loop — only `AppError::Db`
499/// errors that [`is_retryable_tx`] (or, when `cascade`, [`is_retryable_cascade`])
500/// recognise are re-sent; everything else comes straight back.
501///
502/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
503/// that span rows are enforced by single-statement CTEs or row locks
504/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
505/// isolation.
506/// The closure is an [`AsyncFnMut`] (edition-2024 async closure, or a plain
507/// closure whose async block the compiler infers as such) because every real
508/// call site's future borrows the connection — a named `Fut` generic cannot
509/// express that lifetime relationship.
510///
511/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants
512/// that span rows are enforced by single-statement CTEs or row locks
513/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger
514/// isolation; if a transaction genuinely cannot be row-locked, escalate that
515/// one to `SERIALIZABLE` (the retry loop already covers the `40001` it can
516/// then raise) and record the reason in its own call site's comment.
517///
518/// The budget and backoff are the guard layer's usual: `CAP_WRITE_TRIES`
519/// rounds, `backoff`'s exponential-with-jitter wait, attempt zero waiting
520/// not at all.
521pub async fn tx_with_retry<T, F>(pool: &PgPool, cascade: bool, mut f: F) -> Result<T, AppError>
522where
523 F: AsyncFnMut(&mut PgConnection) -> Result<T, AppError>,
524{
525 let mut last: Option<sqlx::Error> = None;
526 for attempt in 0..CAP_WRITE_TRIES {
527 backoff(attempt).await;
528 let mut tx = pool.begin().await?;
529 match f(&mut tx).await {
530 Ok(value) => {
531 // A commit can itself lose the race — `40001` fires at COMMIT
532 // in Postgres — so the commit sits inside the classification.
533 match tx.commit().await {
534 Ok(()) => return Ok(value),
535 Err(err) if is_retryable(&err, cascade) => last = Some(err),
536 Err(err) => return Err(err.into()),
537 }
538 }
539 Err(AppError::Db(err)) if is_retryable(&err, cascade) => {
540 // The losing round wrote nothing durable, which is what makes
541 // re-sending the whole of the recovery. Settle the abort
542 // before the wait, so a connection is not left
543 // idle-in-transaction across the backoff.
544 let _ = tx.rollback().await;
545 last = Some(err);
546 }
547 // A refusal is a decision. Same shape for a `Db` error the
548 // classifier does not recognise: it failed for a reason waiting
549 // cannot fix.
550 Err(err) => return Err(err),
551 }
552 }
553 Err(last
554 .map(AppError::Db)
555 .unwrap_or_else(|| AppError::Internal("a guarded transaction never ran".into())))
556}
557
558fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool {
559 if cascade {
560 is_retryable_cascade(err)
561 } else {
562 is_retryable_tx(err)
563 }
564}
565
566/// Wait out one lost round. Exponential with jitter, because racers arrive in
567/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
568/// Attempt zero waits not at all.
569pub(crate) async fn backoff(attempt: usize) {
570 if attempt == 0 {
571 return;
572 }
573 let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
574 let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
575 tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
576}
577
578/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured.
579/// Both-or-neither: half a pair aborts startup rather than silently running
580/// without the seed — and without a builder, a fresh deployment has nobody who
581/// can create the first school.
582fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
583 match (&cfg.builder_username, &cfg.builder_password) {
584 (Some(username), Some(password)) => Ok(Some((
585 Username::try_new(username)
586 .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?,
587 Password::try_new(password)
588 .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?,
589 ))),
590 (None, None) => Ok(None),
591 _ => Err(AppError::Internal(
592 "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(),
593 )),
594 }
595}
596
597// ---- per-test databases -----------------------------------------------------
598//
599// Every test run gets a **private pair of databases** on the compose Postgres:
600// a control database and the demo school's database, both named after one
601// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_<uuid hex>` — so
602// nextest's parallel processes neither collide nor see each other's rows. The
603// school schema is not migrated per test: it is cloned from a shared template
604// database whose name carries a hash of `migrations/school`, so a schema edit
605// mints a fresh template exactly once and every test after that pays only a
606// cheap `CREATE DATABASE … TEMPLATE`.
607//
608// Cleanup is a lease: every database a deployment minted is recorded in a
609// [`TestDatabases`], and its `Drop` — fired when the deployment's last handle
610// dies — sends `DROP DATABASE … WITH (FORCE)`. A best-effort janitor at first
611// use per process sweeps what a crashed run left behind: only databases past
612// a minimum age are candidates, and their `DROP` carries no `WITH (FORCE)`,
613// so a live parallel test's databases (connected backends, young name) are
614// never touched.
615//
616// These functions are `pub` rather than `#[cfg(test)]` because the
617// integration tests live outside the crate, and `#[doc(hidden)]` because they
618// are not part of the API. Their SQL is runtime-checked — the query-style
619// rule exempts all test-side SQL from the macros.
620
621/// The Postgres server the test databases are minted on. The default is the
622/// compose stack's maintenance database (`.env.example` documents it).
623const TEST_DATABASE_URL_ENV: &str = "HEZARFEN_TEST_DATABASE_URL";
624const TEST_DATABASE_URL_DEFAULT: &str = "postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres";
625
626/// Every test database carries this prefix; the janitor only ever drops
627/// databases it names.
628const TEST_DB_PREFIX: &str = "heztest_";
629
630/// How old a `heztest_%` database must be before the janitor will touch it.
631/// Anything younger belongs to a test in a parallel process — nextest mints
632/// them by the dozen in overlapping seconds.
633const TEST_DB_LEFTOVER_MIN_AGE_MS: i64 = 5 * 60 * 1000;
634
635/// The advisory-lock key the template's create-and-migrate critical section
636/// holds (see [`ensure_test_template`]). An arbitrary constant — it only has
637/// to be one nobody else on the server uses.
638const TEST_TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6500_0001;
639
640/// The databases one test deployment minted, and the promise to drop them.
641///
642/// Cloning shares the lease; the `DROP` statements fire when the **last**
643/// copy drops — which is why a [`Tenants`] can carry one: the databases die
644/// exactly when the test deployment does, even though the `Router` and the
645/// test body hold separate clones of the registry.
646#[doc(hidden)]
647#[derive(Clone)]
648pub struct TestDatabases(Arc<TestLease>);
649
650struct TestLease {
651 /// How to reach the maintenance database when the drops run. Dial options,
652 /// not a pool: the pools a test built belong to the test's runtime and
653 /// cannot be borrowed from the drop thread after that runtime dies — the
654 /// drop dials its own one-connection pool instead.
655 maintenance: PgConnectOptions,
656 names: Mutex<Vec<String>>,
657}
658
659impl TestDatabases {
660 fn new(maintenance: PgConnectOptions) -> Self {
661 Self(Arc::new(TestLease {
662 maintenance,
663 names: Mutex::new(Vec::new()),
664 }))
665 }
666
667 pub(crate) fn track(&self, name: &str) {
668 self.0
669 .names
670 .lock()
671 .expect("test lease names")
672 .push(name.to_owned());
673 }
674
675 /// The database names this lease still owes a drop. Diagnostics only.
676 pub fn names(&self) -> Vec<String> {
677 self.0.names.lock().expect("test lease names").clone()
678 }
679}
680
681impl std::fmt::Debug for TestDatabases {
682 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683 f.debug_struct("TestDatabases")
684 .field("names", &self.names())
685 .finish()
686 }
687}
688
689impl Drop for TestLease {
690 fn drop(&mut self) {
691 let names = std::mem::take(&mut *self.names.lock().expect("test lease names"));
692 let maintenance = self.maintenance.clone();
693 if names.is_empty() {
694 return;
695 }
696 let run = move || {
697 let runtime = tokio::runtime::Builder::new_current_thread()
698 .enable_all()
699 .build()
700 .expect("test-lease drop runtime");
701 runtime.block_on(async move {
702 let Ok(maintenance) = pool_options(1).connect_with(maintenance).await else {
703 eprintln!(
704 "test lease: cannot reach the maintenance database to drop {names:?}"
705 );
706 return;
707 };
708 for name in &names {
709 let sql =
710 create_database_sql("DROP DATABASE IF EXISTS", name) + " WITH (FORCE)";
711 if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
712 .execute(&maintenance)
713 .await
714 {
715 eprintln!("test lease: dropping {name} failed: {err}");
716 }
717 }
718 maintenance.close().await;
719 });
720 };
721 // A lease usually dies inside the test's runtime (the last registry
722 // handle drops at the end of the test future), and a runtime may not
723 // be built inside another — so the drops always run on a dedicated
724 // thread. The wait is bounded: a wedged server cannot hang the test's
725 // teardown forever, and the janitor is the backstop for whatever
726 // outlives it.
727 match tokio::runtime::Handle::try_current() {
728 Ok(_) => {
729 let (done, done_rx) = std::sync::mpsc::channel();
730 std::thread::spawn(move || {
731 run();
732 let _ = done.send(());
733 });
734 let _ = done_rx.recv_timeout(Duration::from_secs(10));
735 }
736 Err(_) => run(),
737 }
738 }
739}
740
741/// A complete test deployment: a fresh control database plus the demo school,
742/// whose database is cloned from the shared school template and registered in
743/// the control registry under the slug every suite names ([`DEMO_SLUG`]).
744///
745/// The databases die with the returned registry's last handle (see
746/// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind.
747#[doc(hidden)]
748pub async fn init_test_tenants() -> Tenants {
749 let maintenance = maintenance_pool().await;
750 janitor(&maintenance).await;
751 let base = test_base();
752 let lease = TestDatabases::new(base.clone());
753
754 let control_db = format!("{TEST_DB_PREFIX}{}", test_suffix());
755 create_database(&maintenance, &control_db, None).await;
756 lease.track(&control_db);
757 let control = boot_control(&base.clone().database(&control_db))
758 .await
759 .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));
760
761 let template = ensure_test_template(&maintenance, &base).await;
762 let demo_id = SchoolId::generate();
763 let school_db = school_db_name(&control_db, demo_id.uuid());
764 create_database(&maintenance, &school_db, Some(&template)).await;
765 lease.track(&school_db);
766 let school = school_pool(&base, &school_db)
767 .await
768 .unwrap_or_else(|err| panic!("dial the test demo school {school_db}: {err}"));
769
770 // The registry row, exactly as [`Tenants::create`] would write it — but
771 // without the per-school migration its `bring_up` runs, which the
772 // template clone has just replaced.
773 sqlx::query(
774 "INSERT INTO school (id, slug, name, status, created_at)
775 VALUES ($1, $2, $3, $4, $5)",
776 )
777 .bind(demo_id.uuid())
778 .bind(DEMO_SLUG)
779 .bind("Demo School")
780 .bind(SchoolStatus::Active)
781 .bind(Timestamp::now().as_millis())
782 .execute(&control)
783 .await
784 .expect("register the test demo school");
785 for module in ModuleSet::all().names() {
786 sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
787 .bind(demo_id.uuid())
788 .bind(module)
789 .execute(&control)
790 .await
791 .expect("register the test demo school's modules");
792 }
793
794 Tenants::new_test_adopting(
795 control,
796 base.database(&control_db),
797 control_db,
798 lease,
799 [(demo_id, school)],
800 )
801}
802
803/// One school database cloned from the template, for the src-side unit tests
804/// that exercise a single store with no tenancy around it. Keep the lease
805/// alive for the database's lifetime (`let (db, _leases) = …` binds it to the
806/// test's scope); dropping it early drops the database.
807#[doc(hidden)]
808pub async fn init_test_db() -> (Database, TestDatabases) {
809 let maintenance = maintenance_pool().await;
810 janitor(&maintenance).await;
811 let base = test_base();
812 let lease = TestDatabases::new(base.clone());
813 let template = ensure_test_template(&maintenance, &base).await;
814 let name = format!("{TEST_DB_PREFIX}{}", test_suffix());
815 create_database(&maintenance, &name, Some(&template)).await;
816 lease.track(&name);
817 let db = school_pool(&base, &name)
818 .await
819 .unwrap_or_else(|err| panic!("dial the test school database {name}: {err}"));
820 (db, lease)
821}
822
823/// The school template's name, and as a side effect its existence: created
824/// and migrated on first use, adopted when something else already made it.
825/// The name carries a hash of `migrations/school`, so a schema edit mints a
826/// fresh template and every process converges on the same new one.
827///
828/// Competing first uses are real: nextest mints tests in parallel processes
829/// and in parallel test threads, all overlapping on the same millisecond.
830/// One server-wide advisory lock makes the create-and-migrate a critical
831/// section — without it, two migrators interleave their DDL on the same
832/// fresh database and one dies on a duplicate table mid-flight (observed).
833/// The probe + `42P04` swallow are the belt to that brace: a template made
834/// before the lock was ever taken is adopted, not fought.
835async fn ensure_test_template(maintenance: &PgPool, base: &PgConnectOptions) -> String {
836 static ENSURED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
837 let name = template_name();
838 let ensured = &*ENSURED;
839 if ensured.lock().expect("template set").contains(&name) {
840 return name;
841 }
842 let mut session = maintenance
843 .acquire()
844 .await
845 .unwrap_or_else(|err| panic!("lease a maintenance connection: {err}"));
846 sqlx::query("SELECT pg_advisory_lock($1)")
847 .bind(TEST_TEMPLATE_LOCK_KEY)
848 .execute(&mut *session)
849 .await
850 .unwrap_or_else(|err| panic!("lock the school template: {err}"));
851 let exists = sqlx::query_as::<_, (i64,)>("SELECT count(*) FROM pg_database WHERE datname = $1")
852 .bind(&name)
853 .fetch_one(&mut *session)
854 .await
855 .map(|(count,)| count > 0)
856 .unwrap_or_else(|err| panic!("probe for the school template {name}: {err}"));
857 if !exists
858 && let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
859 "CREATE DATABASE",
860 &name,
861 )))
862 .execute(&mut *session)
863 .await
864 && !is_duplicate_database(&err)
865 {
866 panic!("create the school template {name}: {err}");
867 }
868 let pool = pool_options(1)
869 .connect_with(base.clone().database(&name))
870 .await
871 .unwrap_or_else(|err| panic!("dial the school template {name}: {err}"));
872 let migrated = migrate_school(&pool).await;
873 pool.close().await;
874 sqlx::query("SELECT pg_advisory_unlock($1)")
875 .bind(TEST_TEMPLATE_LOCK_KEY)
876 .execute(&mut *session)
877 .await
878 .unwrap_or_else(|err| panic!("unlock the school template: {err}"));
879 migrated.unwrap_or_else(|err| panic!("migrate the school template {name}: {err:?}"));
880 ensured.lock().expect("template set").insert(name.clone());
881 name
882}
883
884/// `heztest_tpl_school_<hash>` — the hash is over `migrations/school`'s file
885/// names and bytes, sorted, so any schema edit changes it.
886fn template_name() -> String {
887 let mut migrations: Vec<std::path::PathBuf> = std::fs::read_dir(migrations_path("school"))
888 .expect("read the school migrations directory")
889 .map(|entry| entry.expect("migration directory entry").path())
890 .collect();
891 migrations.sort();
892 let mut hasher = Sha256::new();
893 for path in migrations {
894 hasher.update(
895 path.file_name()
896 .expect("file name")
897 .to_string_lossy()
898 .as_bytes(),
899 );
900 hasher.update(std::fs::read(&path).expect("read a school migration"));
901 }
902 format!(
903 "{TEST_DB_PREFIX}tpl_school_{}",
904 &hex::encode(hasher.finalize())[..8]
905 )
906}
907
908/// One sweep per process, at the first mint: `heztest_%` databases a crashed
909/// run left behind. See the section header for why a candidate must be old
910/// *and* unconnected before it is dropped.
911async fn janitor(maintenance: &PgPool) {
912 static SWEPT: LazyLock<()> = LazyLock::new(|| {});
913 LazyLock::force(&SWEPT);
914 let template = template_name();
915 let leftovers = sqlx::query_as::<_, (String,)>(
916 "SELECT datname FROM pg_database WHERE datname LIKE 'heztest\\_%' ESCAPE '\\'",
917 )
918 .fetch_all(maintenance)
919 .await
920 .unwrap_or_else(|err| panic!("list leftover test databases: {err}"));
921 for (name,) in leftovers {
922 if name == template || !sweep_candidate(&name) {
923 continue;
924 }
925 // No `WITH (FORCE)`: a database with live backends belongs to a
926 // running test in a parallel process, and the failed drop *is* the
927 // skip.
928 let _ = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
929 "DROP DATABASE IF EXISTS",
930 &name,
931 )))
932 .execute(maintenance)
933 .await;
934 }
935}
936
937/// Should this `heztest_%` database be swept? The suffix's leading eleven hex
938/// digits are the mint time in unix milliseconds; anything that cannot be
939/// read that way is either a template of an older schema hash (swept) or
940/// junk (swept too).
941fn sweep_candidate(name: &str) -> bool {
942 let Some(minted_hex) = name.get(TEST_DB_PREFIX.len()..TEST_DB_PREFIX.len() + 11) else {
943 return true;
944 };
945 match i64::from_str_radix(minted_hex, 16) {
946 Ok(minted_ms) => Timestamp::now().as_millis() - minted_ms > TEST_DB_LEFTOVER_MIN_AGE_MS,
947 Err(_) => name.starts_with(&format!("{TEST_DB_PREFIX}tpl_")),
948 }
949}
950
951/// `<11 hex of unix-ms><5 hex random>`: the mint time, so the janitor can
952/// tell a crashed run's leftovers from a parallel test's fresh databases,
953/// plus just enough randomness that two processes minting in the same
954/// millisecond never collide. The tail is not an id and is drawn straight from
955/// the OS rng: the leading hex digits of a v7 uuid *are* the mint time, which
956/// is exactly what two processes minting in one millisecond share.
957fn test_suffix() -> String {
958 let minted_ms = Timestamp::now().as_millis() as u64;
959 let mut tail = [0_u8; 3];
960 getrandom::fill(&mut tail).expect("the OS rng");
961 let hex = format!("{:02x}{:02x}{:02x}", tail[0], tail[1], tail[2]);
962 format!("{minted_ms:011x}{}", &hex[..5])
963}
964
965/// `CREATE DATABASE` for a harness-minted name, optionally `TEMPLATE`-cloned.
966/// Both names are generated here (prefix + hex suffix), never user input —
967/// the same audit that licenses [`create_database_sql`]'s `AssertSqlSafe`
968/// callers.
969async fn create_database(maintenance: &PgPool, name: &str, template: Option<&str>) {
970 let mut sql = create_database_sql("CREATE DATABASE", name);
971 if let Some(template) = template {
972 sql.push_str(&format!(" TEMPLATE \"{}\"", template.replace('"', "\"\"")));
973 }
974 if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(sql))
975 .execute(maintenance)
976 .await
977 {
978 panic!("create the test database {name}: {err}");
979 }
980}
981
982/// Dial options for the test Postgres — `HEZARFEN_TEST_DATABASE_URL` or the
983/// compose default. The URL's database is the *maintenance* database the
984/// `CREATE DATABASE`s run against; the harness names every database itself.
985fn test_base() -> PgConnectOptions {
986 let url = std::env::var(TEST_DATABASE_URL_ENV)
987 .ok()
988 .filter(|url| !url.trim().is_empty())
989 .unwrap_or_else(|| TEST_DATABASE_URL_DEFAULT.to_owned());
990 url.parse().unwrap_or_else(|err| {
991 panic!("{TEST_DATABASE_URL_ENV}={url:?} is not a Postgres URL: {err}")
992 })
993}
994
995/// A small pool over the maintenance database: the janitor's listing and
996/// every `CREATE DATABASE` (DDL — not usable inside a transaction) go
997/// through it, and each lease keeps a clone for its drops.
998async fn maintenance_pool() -> PgPool {
999 pool_options(2)
1000 .connect_with(test_base())
1001 .await
1002 .unwrap_or_else(|err| {
1003 panic!(
1004 "cannot reach the test Postgres (set {TEST_DATABASE_URL_ENV}, default \
1005 {TEST_DATABASE_URL_DEFAULT}): {err} — is the compose stack up?"
1006 )
1007 })
1008}
1009
1010#[cfg(test)]
1011mod builder_seed_tests {
1012 use super::builder_credentials;
1013 use crate::config::Config;
1014
1015 fn cfg(username: Option<&str>, password: Option<&str>) -> Config {
1016 let mut cfg = Config::from_env();
1017 cfg.builder_username = username.map(str::to_string);
1018 cfg.builder_password = password.map(str::to_string);
1019 cfg
1020 }
1021
1022 #[tokio::test]
1023 async fn the_builder_seed_is_both_or_neither() {
1024 assert!(builder_credentials(&cfg(None, None)).unwrap().is_none());
1025 assert!(
1026 builder_credentials(&cfg(Some("builder"), Some("secret1")))
1027 .unwrap()
1028 .is_some()
1029 );
1030 // Half a pair aborts startup: a deployment with no builder has nobody
1031 // who can create the first school, and a silent run would hide that.
1032 assert!(builder_credentials(&cfg(Some("builder"), None)).is_err());
1033 assert!(builder_credentials(&cfg(None, Some("secret1"))).is_err());
1034 // A pair that is set but invalid aborts too, naming the variable.
1035 match builder_credentials(&cfg(Some("!"), Some("secret1"))) {
1036 Err(err) => assert!(err.to_string().contains("BUILDER_USERNAME"), "{err}"),
1037 Ok(_) => panic!("an invalid BUILDER_USERNAME must abort startup"),
1038 }
1039 }
1040}