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

tenant.rs892 lines, 37.4 KiBHistoryRawDownload
1//! Multi-school tenancy: one PostgreSQL **database** per school on one
2//! server, plus a **control** database holding the school registry, the
3//! builder accounts that manage it, and the deployment-wide rate-limit
4//! window.
5//!
6//! Isolation is the server's, not ours. A school database sees only its own
7//! rows, so no handler needs a `WHERE school = …` it could forget: the school
8//! is chosen once, at the edge (`crate::web::tenant_state::State`), and every
9//! query underneath runs against that handle.
10//!
11//! # One pool per school, cached
12//!
13//! `crate::database::Database` is a `PgPool`, and a school's pool is its own
14//! dial — switching databases on a shared connection is not a thing the pool
15//! API offers, which is just as well: a cache miss dials a fresh pool
16//! (`max_connections(4)`) pinned to the school's database for its lifetime,
17//! and the cache is the only thing that finds it again.
18
19use std::collections::HashMap;
20use std::sync::{Arc, RwLock};
21
22use serde::Serialize;
23use sqlx::postgres::PgConnectOptions;
24
25use uuid::Uuid;
26
27use crate::database::{
28 Database, applied_versions, create_database_sql, ensure_database, migrate_school,
29 pending_school_migrations, school_pool,
30};
31use crate::domain::monotonic_id::next_uuid;
32use crate::domain::timestamp::Timestamp;
33use crate::error::{AppError, ValidationError};
34use crate::module::ModuleSet;
35use crate::telemetry::Metrics;
36
37/// The school [`crate::database::init_test_tenants`] registers. Suites name
38/// it by this constant — the hyphenated uuid the cookie prefix and every
39/// frame carry — rather than a second copy of the literal.
40#[doc(hidden)]
41pub const DEMO_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
42
43/// The second school the tenancy suites create beside [`DEMO_SCHOOL_ID`].
44#[doc(hidden)]
45pub const BETA_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000beef";
46
47/// A school database's name: `{control_db}_school_{uuid hex}` — the uuid's
48/// lowercase hex without dashes (the contract's example:
49/// `019732e3-7b00-7000-8000-00000000dead` →
50/// `…_school_019732e37b007000800000000000dead`). Fixed-width and injective:
51/// two uuids never share a database, and no label appears in it, so a rename
52/// can never orphan one. The server's 63-byte identifier cap can clip
53/// the name's tail on deployments with a long control-database name — uuid
54/// v7's random tail still separates schools far past any realistic registry
55/// size, and creator and dialler truncate identically.
56pub fn school_db_name(control_db: &str, id: Uuid) -> String {
57 format!("{}_school_{}", control_db, id.simple())
58}
59
60/// Whether a school may be reached at all. Suspension is immediate and total:
61/// [`Tenants::get`] refuses before any handler runs, and login is no exception.
62///
63/// [`SchoolStatus::Provisioning`] is the boot's bookkeeping, not the vendor's:
64/// it marks the window between the registry row committing and the school's
65/// database carrying the schema (the two cannot be one write). A client can
66/// never ask for it — [`SchoolStatus::try_from_str`] refuses the word — and a
67/// boot closes the window by finishing the provisioning or leaving the row for
68/// the next one.
69///
70/// Stored as a bare lowercase string, like [`crate::domain::role::Role`].
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)]
72#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
73#[serde(rename_all = "lowercase")]
74pub enum SchoolStatus {
75 Active,
76 Suspended,
77 Provisioning,
78}
79
80impl SchoolStatus {
81 pub fn as_str(self) -> &'static str {
82 match self {
83 SchoolStatus::Active => "active",
84 SchoolStatus::Suspended => "suspended",
85 SchoolStatus::Provisioning => "provisioning",
86 }
87 }
88
89 /// The statuses a *client* may name. `provisioning` is deliberately absent:
90 /// it is the boot's word for a school that is being made, so a PATCH that
91 /// asks for it is a validation error rather than a state anyone can enter.
92 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
93 match value {
94 "active" => Ok(SchoolStatus::Active),
95 "suspended" => Ok(SchoolStatus::Suspended),
96 _ => Err(ValidationError::Invalid {
97 field: "status",
98 reason: "must be one of: active, suspended",
99 }),
100 }
101 }
102}
103
104/// A school's identity: the registry row's uuid primary key, app-minted
105/// uuid v7. The cookie prefix, the builder path, the blob directory and the
106/// hab/2 frame `school` value are this id's hyphenated form — nothing else
107/// names a school.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]
109#[sqlx(transparent)]
110pub struct SchoolId(Uuid);
111
112impl SchoolId {
113 /// Wrap a uuid read off a registry row — naming a school that already
114 /// exists (a test evicting the demo pool, say) rather than minting one.
115 pub fn from_uuid(id: Uuid) -> Self {
116 Self(id)
117 }
118
119 /// The next id in write order — see
120 /// [`crate::domain::monotonic_id::next_uuid`].
121 pub fn generate() -> Self {
122 Self(next_uuid())
123 }
124
125 pub fn uuid(self) -> Uuid {
126 self.0
127 }
128
129 /// The canonical wire string: lowercase hyphenated uuid, the same form
130 /// `GET /school` publishes. 36 characters, dashes included.
131 pub fn as_str(self) -> String {
132 self.0.as_hyphenated().to_string()
133 }
134
135 /// Parse the wire form. Hyphenated only — the simple, URN and braced
136 /// spellings `Uuid::try_parse` would accept are not a school id. A frame
137 /// or cookie prefix that fails this is not a school, not a shape error.
138 pub fn try_parse(value: &str) -> Result<Self, ValidationError> {
139 if !is_hyphenated_uuid(value) {
140 return Err(ValidationError::Invalid {
141 field: "school",
142 reason: "must be a hyphenated uuid",
143 });
144 }
145 Uuid::try_parse(value)
146 .map(Self)
147 .map_err(|_| ValidationError::Invalid {
148 field: "school",
149 reason: "must be a hyphenated uuid",
150 })
151 }
152}
153
154/// `8-4-4-4-12` hex with dashes. Case is accepted; [`SchoolId::as_str`]
155/// always emits lowercase.
156fn is_hyphenated_uuid(value: &str) -> bool {
157 let b = value.as_bytes();
158 if b.len() != 36 {
159 return false;
160 }
161 for (i, c) in b.iter().enumerate() {
162 let dash = matches!(i, 8 | 13 | 18 | 23);
163 if dash {
164 if *c != b'-' {
165 return false;
166 }
167 } else if !c.is_ascii_hexdigit() {
168 return false;
169 }
170 }
171 true
172}
173
174impl std::fmt::Display for SchoolId {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 f.write_str(&self.as_str())
177 }
178}
179
180#[derive(Debug, Clone, sqlx::FromRow)]
181pub struct School {
182 id: Uuid,
183 name: String,
184 status: SchoolStatus,
185 created_at: Timestamp,
186 /// Which product modules this school has bought, as their stored names —
187 /// joined in from `school_module` by every read below, never a column of
188 /// `school`. Kept as strings rather than a [`ModuleSet`] so a name this
189 /// binary does not know (an older deploy reading a newer row) is data to
190 /// ignore, not a deserialization failure that would lock the school out
191 /// entirely.
192 modules: Vec<String>,
193}
194
195impl School {
196 /// The row's uuid — the identity the database name, the cookie prefix
197 /// and every structural reference mint from.
198 pub fn get_id(&self) -> SchoolId {
199 SchoolId(self.id)
200 }
201
202 pub fn name(&self) -> &str {
203 &self.name
204 }
205
206 pub fn status(&self) -> SchoolStatus {
207 self.status
208 }
209
210 pub fn created_at(&self) -> Timestamp {
211 self.created_at
212 }
213
214 /// The stored names as modules. An unknown name is dropped with a warning
215 /// — see the field's comment: a school must never become unreachable
216 /// because of a word this binary has not heard of.
217 pub fn modules(&self) -> ModuleSet {
218 let mut set = ModuleSet::empty();
219 for name in &self.modules {
220 match crate::module::Module::try_from_str(name) {
221 Ok(module) => set.insert(module),
222 Err(_) => tracing::warn!(
223 "school {} has an unknown module `{name}` — ignoring it",
224 self.id
225 ),
226 }
227 }
228 set
229 }
230
231 pub async fn read(id: &SchoolId, control: &Database) -> Result<Option<School>, AppError> {
232 sqlx::query_as::<_, School>(
233 "SELECT s.id, s.name, s.status, s.created_at,
234 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
235 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
236 WHERE s.id = $1
237 GROUP BY s.id",
238 )
239 .bind(id.uuid())
240 .fetch_optional(control)
241 .await
242 .map_err(Into::into)
243 }
244
245 /// One page of the registry, newest first. Same `(rows, total)` shape every
246 /// other list domain returns, so the builder API can wrap it in the usual
247 /// [`crate::web::Page`] envelope. `None` limits to every row.
248 pub async fn list(
249 limit: Option<i64>,
250 offset: i64,
251 control: &Database,
252 ) -> Result<(Vec<School>, i64), AppError> {
253 let rows = sqlx::query_as::<_, School>(
254 "SELECT s.id, s.name, s.status, s.created_at,
255 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
256 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
257 GROUP BY s.id
258 ORDER BY s.created_at DESC, s.id DESC
259 LIMIT $1 OFFSET $2",
260 )
261 .bind(limit)
262 .bind(offset)
263 .fetch_all(control)
264 .await?;
265 let (total,): (i64,) = sqlx::query_as("SELECT count(*) FROM school")
266 .fetch_one(control)
267 .await?;
268 Ok((rows, total))
269 }
270
271 /// Rename a school and/or flip its status. The id is the identity and
272 /// is not a field a patch can move.
273 ///
274 /// Both fields land in **one** statement, so a patch that carries both can
275 /// never leave half of itself behind, and an omitted field is kept by
276 /// `COALESCE` over the row being written — never over a snapshot the caller
277 /// read, so a concurrent patch of the other field cannot be reverted
278 /// either.
279 pub async fn update(
280 id: &SchoolId,
281 name: Option<&str>,
282 status: Option<SchoolStatus>,
283 control: &Database,
284 ) -> Result<School, AppError> {
285 sqlx::query_as::<_, School>(
286 "WITH updated AS (
287 UPDATE school
288 SET name = COALESCE($1, name), status = COALESCE($2, status)
289 WHERE id = $3
290 RETURNING id, name, status, created_at
291 )
292 SELECT u.id, u.name, u.status, u.created_at,
293 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
294 FROM updated u
295 LEFT JOIN school_module sm ON sm.school = u.id
296 GROUP BY u.id, u.name, u.status, u.created_at",
297 )
298 .bind(name)
299 .bind(status)
300 .bind(id.uuid())
301 .fetch_optional(control)
302 .await?
303 .ok_or(AppError::NotFound)
304 }
305}
306
307/// The school registry plus its live pools.
308#[derive(Clone)]
309pub struct Tenants {
310 control: Database,
311 /// Live school pools, keyed by the school's uuid hex (no dashes — the
312 /// same form [`school_db_name`] spells). The label never keys it: a pool
313 /// belongs to a school's identity, not to its display name.
314 cache: Arc<RwLock<HashMap<String, Database>>>,
315 /// Dial options for the Postgres server the control pool came from — a
316 /// school pool is the same dial with only the database swapped.
317 base: PgConnectOptions,
318 /// The control database's name; every school database is
319 /// [`school_db_name`] of it.
320 control_db: String,
321 /// Databases a test deployment minted, adopted via
322 /// [`Tenants::new_test_adopting`]; dropped with this registry's last
323 /// handle. `None` in production, where databases outlive the process.
324 leases: Option<crate::database::TestDatabases>,
325}
326
327/// Everything one registry read tells us about the school behind a request:
328/// its handle and what it has bought. Cached in the request's extensions by
329/// [`crate::web::tenant_state::resolve_tenant`], so a request that needs the
330/// school twice (the shadow [`crate::web::tenant_state::State`] *and*
331/// [`crate::web::CurrentUser`], which is most of them) reads the registry once.
332#[derive(Clone)]
333pub struct ResolvedTenant {
334 pub id: SchoolId,
335 pub db: Database,
336 pub modules: ModuleSet,
337}
338
339impl Tenants {
340 /// Wrap an already-connected, already-migrated control pool. Production
341 /// constructor — [`crate::database::init`] calls it once at boot.
342 pub fn new(control: Database, base: PgConnectOptions, control_db: String) -> Tenants {
343 Tenants {
344 control,
345 cache: Arc::new(RwLock::new(HashMap::new())),
346 base,
347 control_db,
348 leases: None,
349 }
350 }
351
352 /// Test constructor: wrap already-created databases and adopt their
353 /// [`crate::database::TestDatabases`] lease, so everything the harness
354 /// minted dies with this registry's last handle. `prewarmed` pools enter
355 /// the cache directly — for a template clone there is no re-dial to win.
356 #[doc(hidden)]
357 pub fn new_test_adopting(
358 control: Database,
359 base: PgConnectOptions,
360 control_db: String,
361 leases: crate::database::TestDatabases,
362 prewarmed: impl IntoIterator<Item = (SchoolId, Database)>,
363 ) -> Tenants {
364 let cache: HashMap<String, Database> = prewarmed
365 .into_iter()
366 .map(|(id, db)| (id.uuid().simple().to_string(), db))
367 .collect();
368 Tenants {
369 control,
370 cache: Arc::new(RwLock::new(cache)),
371 base,
372 control_db,
373 leases: Some(leases),
374 }
375 }
376
377 /// The databases this deployment minted, when it is a test deployment —
378 /// for a suite that wants to name what will die with it. `None` in
379 /// production.
380 #[doc(hidden)]
381 pub fn test_leases(&self) -> Option<&crate::database::TestDatabases> {
382 self.leases.as_ref()
383 }
384
385 /// The control database: schools, builders, the shared rate-limit window.
386 /// It is never re-purposed for a school's rows — see this module's header.
387 pub fn control(&self) -> &Database {
388 &self.control
389 }
390
391 /// The handle for a school a request may use, or the refusal a request
392 /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404`
393 /// would enumerate the customer list), suspended → `403`, still being
394 /// provisioned → `403` as well (its database has no schema to serve yet).
395 ///
396 /// corner-cut: the registry row is read on every request, so a suspension
397 /// takes effect on the next call with no invalidation protocol. That is one
398 /// extra control-db round trip per request; cache the row with a short TTL
399 /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`]
400 /// is already there to make a cached decision safe.
401 pub async fn get(&self, id: &SchoolId) -> Result<Database, AppError> {
402 Ok(self.resolve(id).await?.db)
403 }
404
405 /// [`Tenants::get`] plus what that one registry read already knew: the
406 /// school's module entitlements. Same verdicts, same single read — a
407 /// caller that needs both must never pay for two.
408 pub async fn resolve(&self, id: &SchoolId) -> Result<ResolvedTenant, AppError> {
409 match School::read(id, &self.control).await? {
410 None => Err(AppError::Unauthorized),
411 Some(school) if school.status == SchoolStatus::Suspended => {
412 self.evict(school.get_id()).await;
413 Err(AppError::Forbidden("school is suspended"))
414 }
415 Some(school) if school.status == SchoolStatus::Provisioning => {
416 self.evict(school.get_id()).await;
417 Err(AppError::Forbidden("school is still being provisioned"))
418 }
419 Some(school) => Ok(ResolvedTenant {
420 id: school.get_id(),
421 db: self.handle(school.get_id()).await?,
422 modules: school.modules(),
423 }),
424 }
425 }
426
427 /// [`Tenants::get`] for builder tooling, which must still reach a suspended
428 /// school to un-suspend or inspect it. Unknown → `404`, because a builder is
429 /// authenticated and there is nothing to hide from them. A school that is
430 /// still being provisioned is a `409`: the two routes that come through
431 /// here (`enter`, `reset_admin_password`) need its database to answer, and a
432 /// table-less one would surface as a `500` instead of "not ready yet".
433 pub async fn get_any_status(
434 &self,
435 id: &SchoolId,
436 ) -> Result<(Database, SchoolStatus), AppError> {
437 let school = School::read(id, &self.control)
438 .await?
439 .ok_or(AppError::NotFound)?;
440 if school.status == SchoolStatus::Provisioning {
441 return Err(AppError::Conflict("school is still being provisioned"));
442 }
443 Ok((self.handle(school.get_id()).await?, school.status))
444 }
445
446 /// Register a school and bring its database into being: registry row first
447 /// (so a lost race is a `409` and not a half-made database), then
448 /// `CREATE DATABASE`, then the school schema. The caller mints the id —
449 /// the web create path is the one minter — and it becomes the row's PK,
450 /// the database name's source and the pool cache key.
451 pub async fn create(
452 &self,
453 id: SchoolId,
454 name: &str,
455 modules: ModuleSet,
456 ) -> Result<Database, AppError> {
457 // Defense in depth: the builder API validates first (its message names
458 // every violation at once), but the registry refuses an unsatisfiable
459 // set too, so no future caller can persist one.
460 modules.validate()?;
461 // The registry row and its entitlements land as one transaction: a
462 // school row never stands without the modules its creation asked for.
463 let mut tx = self.control.begin().await?;
464 let inserted = sqlx::query(
465 "INSERT INTO school (id, name, status, created_at)
466 VALUES ($1, $2, $3, $4)",
467 )
468 .bind(id.uuid())
469 .bind(name)
470 .bind(SchoolStatus::Provisioning)
471 .bind(Timestamp::now().as_millis())
472 .execute(&mut *tx)
473 .await;
474 if let Err(err) = inserted {
475 // A fresh uuid v7 does not repeat. A unique violation here is an
476 // internal fault (the primary key), not a name the caller can
477 // change and retry.
478 return Err(err.into());
479 }
480 for name in modules.names() {
481 sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
482 .bind(id.uuid())
483 .bind(name)
484 .execute(&mut *tx)
485 .await?;
486 }
487 tx.commit().await?;
488
489 // Everything past the registry row rolls that row back on failure.
490 // (A database
491 // created before the failure is not a wedge: the adopt branch in
492 // [`Self::bring_up`] picks it up, migrations being idempotent.)
493 let db = match self.bring_up(id).await {
494 Ok(db) => db,
495 Err(err) => {
496 let _ = sqlx::query("DELETE FROM school_module WHERE school = $1")
497 .bind(id.uuid())
498 .execute(&self.control)
499 .await;
500 let _ = sqlx::query("DELETE FROM school WHERE id = $1")
501 .bind(id.uuid())
502 .execute(&self.control)
503 .await;
504 // The rows go first, then the database, which is the
505 // expensive half and whose name nothing will ever reuse (the id
506 // is minted per create, never replayed). Best-effort, but not
507 // silent: a failure here is a half-provisioned database nobody
508 // can see or reach, so it earns the one log line this path has.
509 if let Err(leak) = sqlx::query(sqlx::AssertSqlSafe(
510 create_database_sql(
511 "DROP DATABASE IF EXISTS",
512 &school_db_name(&self.control_db, id.uuid()),
513 ) + " WITH (FORCE)",
514 ))
515 .execute(&self.control)
516 .await
517 {
518 tracing::warn!(
519 "failed to drop the database of a school whose create failed: {leak}"
520 );
521 }
522 return Err(err);
523 }
524 };
525 let size = {
526 let mut cache = self.cache.write().expect("tenant cache lock");
527 cache.insert(id.uuid().simple().to_string(), db.clone());
528 cache.len()
529 };
530 Self::report_size(size);
531 // A test deployment's lease learns every school the deployment
532 // mints, so a school created mid-test dies with the deployment.
533 if let Some(leases) = &self.leases {
534 leases.track(&school_db_name(&self.control_db, id.uuid()));
535 }
536 Ok(db)
537 }
538
539 /// Create (or adopt) the school's database and apply the school schema to
540 /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled
541 /// back as a unit.
542 async fn bring_up(&self, id: SchoolId) -> Result<Database, AppError> {
543 let db_name = school_db_name(&self.control_db, id.uuid());
544 // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute`
545 // sends it as a bare autocommit statement. A name left over by a
546 // create that died before its rollback is adopted, not fought.
547 ensure_database(&self.control, &db_name).await?;
548 let pool = school_pool(&self.base, &db_name).await?;
549 let migrated = migrate_school(&pool).await;
550 if migrated.is_err() {
551 pool.close().await;
552 migrated?;
553 }
554 // The schema is there, so the school stops saying it is being made
555 // (see [`SchoolStatus::Provisioning`]). Both callers want exactly this:
556 // the create that minted the row a moment ago, and the boot that is
557 // finishing one a previous boot left behind.
558 sqlx::query("UPDATE school SET status = $1 WHERE id = $2")
559 .bind(SchoolStatus::Active)
560 .bind(id.uuid())
561 .execute(&self.control)
562 .await?;
563 Ok(pool)
564 }
565
566 /// Flip a school between `active` and `suspended` — the one-field form of
567 /// [`School::update`], which is where the write itself lives. Suspending
568 /// also drops the cached pool, so nothing that already resolved keeps
569 /// serving.
570 pub async fn set_status(&self, id: &SchoolId, status: SchoolStatus) -> Result<(), AppError> {
571 let school = School::update(id, None, Some(status), &self.control).await?;
572 if status == SchoolStatus::Suspended {
573 self.evict(school.get_id()).await;
574 }
575 Ok(())
576 }
577
578 /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the
579 /// eviction: entitlements are read off the registry row on every request,
580 /// so a change takes effect on the next call and no cached pool carries a
581 /// stale answer.
582 pub async fn set_modules(&self, id: &SchoolId, modules: &ModuleSet) -> Result<(), AppError> {
583 modules.validate()?;
584 // The swap is parent + children in one transaction: take the registry
585 // row's lock so racing sellers serialize, then replace the whole shelf.
586 let mut tx = self.control.begin().await?;
587 let locked: Option<Uuid> =
588 sqlx::query_scalar("SELECT id FROM school WHERE id = $1 FOR UPDATE")
589 .bind(id.uuid())
590 .fetch_optional(&mut *tx)
591 .await?;
592 let Some(row_id) = locked else {
593 return Err(AppError::NotFound);
594 };
595 sqlx::query("DELETE FROM school_module WHERE school = $1")
596 .bind(row_id)
597 .execute(&mut *tx)
598 .await?;
599 for name in modules.names() {
600 sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
601 .bind(row_id)
602 .bind(name)
603 .execute(&mut *tx)
604 .await?;
605 }
606 tx.commit().await?;
607 Ok(())
608 }
609
610 /// Delete a school outright: its data, then its registry row, then its
611 /// pool. Irreversible on purpose — there is no soft-delete state, that is
612 /// what [`SchoolStatus::Suspended`] is for.
613 pub async fn drop(&self, id: &SchoolId) -> Result<(), AppError> {
614 // A row already gone means the goal state stands. The database name
615 // is derived from the id, but a missing row is `Ok(())`.
616 let Some(school) = School::read(id, &self.control).await? else {
617 return Ok(());
618 };
619 let id = school.get_id();
620 // Close the pool first: nothing should be dialling a school whose
621 // database is about to go away, and `WITH (FORCE)` should never find
622 // one of our connections to kill.
623 self.evict(id).await;
624 // The database goes first — it is the half that can fail on its own
625 // (`DROP DATABASE` cannot join a transaction) — and everything after it
626 // is one transaction. A failure can then only leave "database gone,
627 // registry rows intact", which re-running this same call completes,
628 // rather than a destroyed membership set on a school that still stands
629 // (every one of its people locked out, nothing able to put them back).
630 let db_name = school_db_name(&self.control_db, id.uuid());
631 sqlx::query(sqlx::AssertSqlSafe(
632 create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)",
633 ))
634 .execute(&self.control)
635 .await?;
636 // The control-plane rows pointing at the school by uuid — membership
637 // and entitlement alike — go as one write: `ON DELETE NO ACTION` would
638 // refuse the registry delete while any stand. Person sessions carry no
639 // school, so only memberships go — the persons themselves survive (a
640 // person is a global account, not the school's).
641 let mut tx = self.control.begin().await?;
642 crate::db::person::delete_memberships_by_school(&mut *tx, &id).await?;
643 sqlx::query("DELETE FROM school_module WHERE school = $1")
644 .bind(id.uuid())
645 .execute(&mut *tx)
646 .await?;
647 sqlx::query("DELETE FROM school WHERE id = $1")
648 .bind(id.uuid())
649 .execute(&mut *tx)
650 .await?;
651 tx.commit().await?;
652
653 Ok(())
654 }
655
656 /// Finish the schools a previous boot left half-made.
657 ///
658 /// A school's registry row commits before its database exists — the two
659 /// cannot be one write, `CREATE DATABASE` being the one statement Postgres
660 /// refuses inside a transaction — so a boot that dies in between leaves a
661 /// row marked [`SchoolStatus::Provisioning`] and no schema behind it. This
662 /// runs the half that boot could not: create the database, migrate it, and
663 /// take the row to `active` (all of it [`Tenants::bring_up`]). A school that
664 /// fails again stays `provisioning` and is retried on the next boot, and the
665 /// builder can always `DELETE` it.
666 ///
667 /// What it cannot do is seed a first admin — that only ever lived in the web
668 /// create path, after this point — so a finished school may have no account
669 /// anybody can log into. The builder sees it in the list and either
670 /// `DELETE`s it and creates it again, or uses an account it already has.
671 pub async fn reconcile_provisioning(&self) -> Result<(), AppError> {
672 let rows: Vec<(Uuid,)> =
673 sqlx::query_as("SELECT id FROM school WHERE status = $1 ORDER BY created_at")
674 .bind(SchoolStatus::Provisioning)
675 .fetch_all(&self.control)
676 .await?;
677 for (id,) in rows {
678 let id = SchoolId(id);
679 match self.bring_up(id).await {
680 Ok(pool) => {
681 // Nothing has dialled it: this boot's pool is the cache's
682 // only candidate and no request exists yet, so closing it
683 // costs nothing and keeps the gauge honest.
684 pool.close().await;
685 tracing::info!(
686 school = %id.uuid(),
687 "finished provisioning a school the previous boot left half-made — \
688 its first admin was never seeded, so DELETE and re-create it if nobody can enter"
689 );
690 }
691 Err(err) => tracing::warn!(
692 school = %id.uuid(),
693 "a school is still provisioning after a retry ({err}) — the next boot tries again"
694 ),
695 }
696 }
697 Ok(())
698 }
699
700 /// Apply the school schema to every school database in the registry.
701 ///
702 /// The invariant this restores: **every school database in the control
703 /// database is at the school-schema head after boot**, because a school
704 /// database is only ever migrated at mint or at boot. A school is minted
705 /// through `bring_up` — the create path and
706 /// [`Tenants::reconcile_provisioning`] both — with whatever schema head
707 /// the process that minted it carried, and nothing afterwards ever touches
708 /// its schema: a re-dial applies no migrations (see
709 /// `crate::database::school_pool`), and `reconcile_provisioning` only
710 /// reaches rows still marked `provisioning`. A school minted before a
711 /// migration landed therefore keeps yesterday's tables for good, and its
712 /// routes answer `500` on whatever that migration added — the live
713 /// deployment served `relation "podcast_job" does not exist` on
714 /// `POST /podcast/jobs` for exactly this reason.
715 ///
716 /// Failure policy: **one school must never take the boot down.** A school
717 /// that fails to migrate is logged at ERROR with its id and left
718 /// exactly as it stood — no registry row and no status is written here, so
719 /// a failed school stays as usable (or unusable) as it was before the
720 /// sweep, and the next boot retries it. sqlx's tracking table is what
721 /// makes the retry safe: a migration that died mid-flight is re-run, not
722 /// half-believed.
723 pub async fn sweep_school_schemas(&self) {
724 let rows: Vec<(Uuid,)> =
725 match sqlx::query_as("SELECT id FROM school ORDER BY created_at")
726 .fetch_all(&self.control)
727 .await
728 {
729 Ok(rows) => rows,
730 // The control database was migrated moments ago in this same
731 // boot, so this is a surprise and not a state — but a boot
732 // that refuses to serve over it would be down for every school
733 // at once, which the failure policy above will not have.
734 Err(err) => {
735 tracing::error!("school schema sweep could not list the registry: {err}");
736 return;
737 }
738 };
739 let total = rows.len();
740 let mut migrated = 0usize;
741 for (id,) in rows {
742 let id = SchoolId(id);
743 match self.sweep_school(id).await {
744 Ok(pending) if pending > 0 => {
745 migrated += 1;
746 tracing::info!(
747 school = %id,
748 "school schema sweep applied {pending} migration(s) to a school behind the head"
749 );
750 }
751 Ok(_) => {}
752 Err(err) => tracing::error!(
753 school = %id,
754 "school schema sweep failed — this school is left as it was and the next boot \
755 retries it: {err}"
756 ),
757 }
758 }
759 tracing::info!("school schema sweep: {total} schools, {migrated} migrated");
760 }
761
762 /// One school's step of [`Tenants::sweep_school_schemas`]: dial it, bring
763 /// it to head, close the pool. The pool is made and closed inside this
764 /// call — a school this boot never serves must not leave one behind (the
765 /// cache is what keeps a served school's pool, and the sweep is not a
766 /// serve), and the close has to sit outside [`Tenants::bring_to_head`] so
767 /// no `?` on its error path can skip it.
768 async fn sweep_school(&self, id: SchoolId) -> Result<usize, AppError> {
769 let db_name = school_db_name(&self.control_db, id.uuid());
770 let pool = school_pool(&self.base, &db_name).await?;
771 let swept = Self::bring_to_head(&pool).await;
772 pool.close().await;
773 swept
774 }
775
776 /// Apply whatever the school schema has that `pool` has not — idempotent,
777 /// so a school already at head costs one `_sqlx_migrations` read and a
778 /// no-op migrator run. Returns how many migrations were pending, which is
779 /// what the sweep's per-school line reports.
780 ///
781 /// [`crate::database::migrate_school`], not the bare migrator: it also
782 /// sweeps the chatbot and RAG turns the previous process owed an answer,
783 /// which is exactly as due on a school being swept as on one being minted.
784 async fn bring_to_head(pool: &Database) -> Result<usize, AppError> {
785 let applied = applied_versions(pool).await?;
786 let pending = pending_school_migrations(&applied).await?;
787 migrate_school(pool).await?;
788 Ok(pending)
789 }
790
791 /// Forget a school's pool and close it. The next request dials a fresh
792 /// one.
793 ///
794 /// Nothing depends on eviction for correctness — [`Tenants::get`]
795 /// re-reads the registry row on every request, so a suspension is refused
796 /// whether or not a pool survived it. [`Tenants::drop`], which does mean
797 /// to destroy the store, evicts unconditionally.
798 pub async fn evict(&self, id: SchoolId) {
799 if let Some(pool) = self.forget(id) {
800 pool.close().await;
801 }
802 }
803
804 fn forget(&self, id: SchoolId) -> Option<Database> {
805 let key = id.uuid().simple().to_string();
806 let (removed, size) = {
807 let mut cache = self.cache.write().expect("tenant cache lock");
808 (cache.remove(&key), cache.len())
809 };
810 if removed.is_some() {
811 tracing::info!(school = %id.uuid(), "tenant pool evicted");
812 Self::report_size(size);
813 }
814 removed
815 }
816
817 /// The cached pool, or a freshly dialled one.
818 async fn handle(&self, id: SchoolId) -> Result<Database, AppError> {
819 let key = id.uuid().simple().to_string();
820 if let Some(db) = self.cache.read().expect("tenant cache lock").get(&key) {
821 return Ok(db.clone());
822 }
823 let db = school_pool(&self.base, &school_db_name(&self.control_db, id.uuid())).await?;
824 // Losing the race here is harmless — both pools are equivalent — but
825 // the winner is kept so two requests never diverge onto two pools.
826 let (db, size) = {
827 let mut cache = self.cache.write().expect("tenant cache lock");
828 let db = cache.entry(key).or_insert(db).clone();
829 (db, cache.len())
830 };
831 tracing::info!(school = %id.uuid(), "tenant pool opened");
832 Self::report_size(size);
833 Ok(db)
834 }
835
836 /// Publish how many schools the cache holds. Called after every insert and
837 /// every eviction, which are the only two things that move it — a gauge
838 /// sampled anywhere else would report a number nobody can act on.
839 fn report_size(size: usize) {
840 Metrics::global().tenant_cache_size.record(size as u64, &[]);
841 }
842}
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847
848 #[test]
849 fn a_school_id_is_a_hyphenated_uuid_and_nothing_else() {
850 let good = "019732e3-7b00-7000-8000-00000000dead";
851 let id = SchoolId::try_parse(good).expect("hyphenated");
852 assert_eq!(id.as_str(), good);
853 for bad in [
854 "019732e37b007000800000000000dead",
855 "urn:uuid:019732e3-7b00-7000-8000-00000000dead",
856 "{019732e3-7b00-7000-8000-00000000dead}",
857 "demo",
858 "builder",
859 "",
860 ] {
861 assert!(SchoolId::try_parse(bad).is_err(), "{bad:?} must not parse");
862 }
863 }
864
865 /// The database-per-school model lives or dies by this mapping: two
866 /// schools sharing a database name would share every row in it. The name
867 /// now mints from the school's uuid — lowercase hex without dashes, fixed
868 /// width — so it is injective by construction, and no label appears
869 /// in it: a rename can never orphan a database.
870 #[test]
871 fn school_db_names_are_injective() {
872 let control = "hezarfen_control";
873 // The contract's example, pinned byte for byte.
874 let id = Uuid::try_parse("019732e3-7b00-7000-8000-00000000dead").unwrap();
875 assert_eq!(
876 school_db_name(control, id),
877 "hezarfen_control_school_019732e37b007000800000000000dead"
878 );
879 // Two uuids never collide onto one database, and no label is in the
880 // name.
881 let other = Uuid::try_parse("019732e3-7b00-7000-8000-00000000beef").unwrap();
882 assert_ne!(
883 school_db_name(control, id),
884 school_db_name(control, other),
885 "two uuids must not share a database"
886 );
887 assert!(!school_db_name(control, id).contains("demo"));
888 // The control database's own name is never a school's name: the
889 // suffix keeps the namespaces apart.
890 assert_ne!(school_db_name(control, id), control);
891 }
892}