diff --git a/scripts/boot_race.sh b/scripts/boot_race.sh new file mode 100755 index 0000000..76c27d7 --- /dev/null +++ b/scripts/boot_race.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Boot N copies of the backend at once against a Postgres whose school +# template has just been dropped, and report what each boot did. +# +# This is the reproduction for the concurrent-boot class. Two things are being +# watched: +# * every boot must reach `listening` — overlapping `CREATE DATABASE`s used +# to kill the losers, because Postgres reports the losing side as a +# `pg_database_datname_index` unique violation (`23505`) rather than the +# `42P04` duplicate-database error, and the swallow only matched `42P04`; +# * the server log must stay clean *of create refusals* — a create that is +# issued and refused is logged by the server even when the client swallows +# the error, which is why the create now runs behind a probe and under an +# advisory lock. The assertion is scoped to those lines so that a test +# suite sharing the server (its deliberate foreign-key violations) does +# not read as a boot failure. +# Exit status is non-zero if any boot failed or the server logged a create +# refusal. +# +# The template of the control database is dropped first; the next boot (this +# script, or your usual `podman compose up -d backend`) rebuilds and migrates +# it, so a dev database is the only thing this may disturb. +# +# Needs the compose Postgres up (`podman compose up -d postgres`) and a built +# binary (`cargo build`). +set -euo pipefail + +CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen_backend_postgres}" +CONTROL_DB="${HEZARFEN_CONTROL_DB:-hezarfen_control}" +N="${N:-8}" +BASE_PORT="${BASE_PORT:-7800}" +OUT="${OUT:-$(mktemp -d)}" +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BIN="${BIN:-$HERE/target/debug/hezarfen_backend}" + +psql() { podman exec -i "$CONTAINER" psql -U hezarfen -v ON_ERROR_STOP=1 "$@"; } + +echo "== dropping ${CONTROL_DB}_school_template (the next boot rebuilds it)" +psql -d postgres -q -c "DROP DATABASE IF EXISTS \"${CONTROL_DB}_school_template\"" +before=$(podman logs "$CONTAINER" 2>&1 | wc -l) + +echo "== racing $N boots on ports $BASE_PORT..$((BASE_PORT + N - 1))" +for i in $(seq 0 $((N - 1))); do + ( + HOST=127.0.0.1 PORT=$((BASE_PORT + i)) \ + DATABASE_URL="postgres://hezarfen:hezarfen@127.0.0.1:5432/${CONTROL_DB}" \ + FILES_PATH="${FILES_PATH:-/tmp/hez-files}" RUST_LOG=info \ + timeout 30 "$BIN" >"$OUT/boot$i.log" 2>&1 + ) & +done +wait + +fail=0 +for i in $(seq 0 $((N - 1))); do + if grep -q "listening on" "$OUT/boot$i.log"; then + echo " boot$i (port $((BASE_PORT + i))): up" + else + echo " boot$i (port $((BASE_PORT + i))): FAILED" + tail -3 "$OUT/boot$i.log" + fail=1 + fi +done + +errors=$(podman logs "$CONTAINER" 2>&1 | tail -n +$((before + 1)) | + grep -E 'pg_database_datname_index|already exists' | grep -cE 'ERROR|FATAL' || true) +echo "== server log since the race: $errors create-refusal line(s)" +[ "$errors" -eq 0 ] || fail=1 + +echo "== templates now on the server" +psql -d postgres -Atc "SELECT datname FROM pg_database WHERE datname LIKE '%_school_template'" +echo "== boot logs: $OUT" +exit "$fail" diff --git a/src/database.rs b/src/database.rs index 86795ae..765aec6 100644 --- a/src/database.rs +++ b/src/database.rs @@ -79,7 +79,7 @@ pub async fn init(cfg: &Config) -> Result { // outside any transaction (`CREATE DATABASE` cannot run inside one — // `Pool::execute` runs bare autocommit statements), migrated once, then // closed. A first boot lost to a concurrent boot of the same deployment - // adopts the winner's template via the duplicate-database swallow. + // adopts the winner's template — see [`ensure_database`]. let template = format!("{control_db}_school_template"); ensure_template(&control, &base, &template).await?; @@ -144,6 +144,43 @@ pub(crate) fn create_database_sql(statement: &str, name: &str) -> String { format!("{statement} \"{}\"", name.replace('"', "\"\"")) } +/// Create `name` unless the server already has it. +/// +/// Postgres has no `IF NOT EXISTS` for `CREATE DATABASE` — the clause is a +/// syntax error there — so the "already there" case can only be settled by a +/// probe or by swallowing the refusal. Swallowing alone is not enough: a +/// refused create is *not* quiet, the server logs it as +/// `ERROR: database "…" already exists`, and a boot that finds its template in +/// place would print that line on every restart. The probe handles the common +/// case; the [`is_database_exists`] swallow stays as the backstop for the +/// window between probe and create, where rival boots win the race and the +/// statement is issued anyway. +pub(crate) async fn ensure_database(pool: &PgPool, name: &str) -> Result<(), sqlx::Error> { + let present = + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM pg_database WHERE datname = $1") + .bind(name) + .fetch_one(pool) + .await?; + if present > 0 { + tracing::debug!("database {name} already exists — adopting it"); + return Ok(()); + } + match sqlx::query(sqlx::AssertSqlSafe(create_database_sql( + "CREATE DATABASE", + name, + ))) + .execute(pool) + .await + { + Ok(_) => Ok(()), + Err(err) if is_database_exists(&err) => { + tracing::debug!("database {name} was created by a rival boot — adopting it"); + Ok(()) + } + Err(err) => Err(err), + } +} + async fn boot_control(base: &PgConnectOptions) -> Result { let pool = pool_options(10).connect_with(base.clone()).await?; // The migrator is built here rather than in [`migrator`]: its resolution @@ -259,23 +296,55 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { Ok(()) } +/// The advisory-lock key [`ensure_template`] holds while it creates and +/// migrates the template: one name for one control database, contended only +/// by concurrent boots of the same deployment. Distinct from +/// [`TEST_TEMPLATE_LOCK_KEY`], which guards a different database. +const TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6D70_0001; + /// Ensure the school-template database exists and carries the current school /// schema. `CREATE DATABASE` runs on the control pool outside any -/// transaction; the loser of a race adopts the winner's database. +/// transaction; a template another boot already made is adopted. +/// +/// Boots of one deployment can overlap (a rolling restart, two replicas), and +/// this pair is a critical section across processes for the same reasons the +/// test harness's is (see [`ensure_test_template`]): unsynchronized, the +/// creates collide — the loser's `pg_database_datname_index` violation is +/// logged as a server-side `ERROR` even though [`ensure_database`] swallows +/// it — and two migrators interleave their DDL on the same fresh database and +/// kill each other on a duplicate table. async fn ensure_template( control: &PgPool, base: &PgConnectOptions, name: &str, ) -> Result<(), AppError> { - if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( - "CREATE DATABASE", - name, - ))) - .execute(control) - .await - && !is_duplicate_database(&err) { - return Err(err.into()); - } + // A connection of its own, held for the section: an advisory lock is a + // server-wide name, so which connection issues the `CREATE` and the + // migrations inside the section does not matter — only that every boot + // takes the lock first. + let mut session = control.acquire().await?; + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(TEMPLATE_LOCK_KEY) + .execute(&mut *session) + .await?; + let ensured = ensure_template_locked(control, base, name).await; + // Unlocked before anything is returned: the lock is session-scoped and the + // connection goes back to the pool, so skipping this on the error path + // would wedge every later boot. + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(TEMPLATE_LOCK_KEY) + .execute(&mut *session) + .await?; + ensured +} + +/// The template's create-and-migrate, under [`ensure_template`]'s lock. +async fn ensure_template_locked( + control: &PgPool, + base: &PgConnectOptions, + name: &str, +) -> Result<(), AppError> { + ensure_database(control, name).await?; // One migrator connection, made and closed: the template is never served. let pool = pool_options(1) .connect_with(base.clone().database(name)) @@ -292,6 +361,17 @@ pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool { .is_some_and(|db| db.code().as_deref() == Some("42P04")) } +/// Is this error "the database is already there"? Two SQLSTATEs say yes: +/// `42P04`, the duplicate-database check `CREATE DATABASE` runs against the +/// catalog, and `23505` on `pg_database_datname_index` — how Postgres reports +/// the *losing* side of two concurrent creates, the name check and the +/// catalog insert not being one atomic step. Measured on 18.6: four boots +/// racing on an absent template, three of them got `23505` and died, so a +/// `42P04`-only guard is too narrow for the very race it exists for. +pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool { + is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index") +} + /// The violated `UNIQUE` constraint's name, when `err` is a unique violation /// (`23505`). The constraint name is the stable handle call sites map /// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is diff --git a/src/tenant.rs b/src/tenant.rs index b36f6fc..4bc08da 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -26,8 +26,7 @@ use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; use uuid::Uuid; use crate::database::{ - Database, create_database_sql, is_duplicate_database, migrate_school, school_pool, - unique_violation, + Database, create_database_sql, ensure_database, migrate_school, school_pool, unique_violation, }; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; @@ -496,15 +495,7 @@ impl Tenants { // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute` // sends it as a bare autocommit statement. A name left over by a // create that died before its rollback is adopted, not fought. - if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( - "CREATE DATABASE", - &db_name, - ))) - .execute(&self.control) - .await - && !is_duplicate_database(&err) { - return Err(err.into()); - } + ensure_database(&self.control, &db_name).await?; let pool = school_pool(&self.base, &db_name).await?; let migrated = migrate_school(&pool).await; if migrated.is_err() {