| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use std::collections::HashMap; |
| 20 | use std::sync::{Arc, RwLock}; |
| 21 | |
| 22 | use serde::Serialize; |
| 23 | use sqlx::postgres::PgConnectOptions; |
| 24 | |
| 25 | use uuid::Uuid; |
| 26 | |
| 27 | use crate::database::{ |
| 28 | Database, applied_versions, create_database_sql, ensure_database, migrate_school, |
| 29 | pending_school_migrations, school_pool, |
| 30 | }; |
| 31 | use crate::domain::monotonic_id::next_uuid; |
| 32 | use crate::domain::timestamp::Timestamp; |
| 33 | use crate::error::{AppError, ValidationError}; |
| 34 | use crate::module::ModuleSet; |
| 35 | use crate::telemetry::Metrics; |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | #[doc(hidden)] |
| 41 | pub const DEMO_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000dead"; |
| 42 | |
| 43 | |
| 44 | #[doc(hidden)] |
| 45 | pub const BETA_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000beef"; |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | pub fn school_db_name(control_db: &str, id: Uuid) -> String { |
| 57 | format!("{}_school_{}", control_db, id.simple()) |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)] |
| 72 | #[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 73 | #[serde(rename_all = "lowercase")] |
| 74 | pub enum SchoolStatus { |
| 75 | Active, |
| 76 | Suspended, |
| 77 | Provisioning, |
| 78 | } |
| 79 | |
| 80 | impl 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 | |
| 90 | |
| 91 | |
| 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 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)] |
| 109 | #[sqlx(transparent)] |
| 110 | pub struct SchoolId(Uuid); |
| 111 | |
| 112 | impl SchoolId { |
| 113 | |
| 114 | |
| 115 | pub fn from_uuid(id: Uuid) -> Self { |
| 116 | Self(id) |
| 117 | } |
| 118 | |
| 119 | |
| 120 | |
| 121 | pub fn generate() -> Self { |
| 122 | Self(next_uuid()) |
| 123 | } |
| 124 | |
| 125 | pub fn uuid(self) -> Uuid { |
| 126 | self.0 |
| 127 | } |
| 128 | |
| 129 | |
| 130 | |
| 131 | pub fn as_str(self) -> String { |
| 132 | self.0.as_hyphenated().to_string() |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 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 | |
| 155 | |
| 156 | fn 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 | |
| 174 | impl 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)] |
| 181 | pub struct School { |
| 182 | id: Uuid, |
| 183 | name: String, |
| 184 | status: SchoolStatus, |
| 185 | created_at: Timestamp, |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | modules: Vec<String>, |
| 193 | } |
| 194 | |
| 195 | impl School { |
| 196 | |
| 197 | |
| 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 | |
| 215 | |
| 216 | |
| 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 | |
| 246 | |
| 247 | |
| 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 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 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 | |
| 308 | #[derive(Clone)] |
| 309 | pub struct Tenants { |
| 310 | control: Database, |
| 311 | |
| 312 | |
| 313 | |
| 314 | cache: Arc<RwLock<HashMap<String, Database>>>, |
| 315 | |
| 316 | |
| 317 | base: PgConnectOptions, |
| 318 | |
| 319 | |
| 320 | control_db: String, |
| 321 | |
| 322 | |
| 323 | |
| 324 | leases: Option<crate::database::TestDatabases>, |
| 325 | } |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | #[derive(Clone)] |
| 333 | pub struct ResolvedTenant { |
| 334 | pub id: SchoolId, |
| 335 | pub db: Database, |
| 336 | pub modules: ModuleSet, |
| 337 | } |
| 338 | |
| 339 | impl Tenants { |
| 340 | |
| 341 | |
| 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 | |
| 353 | |
| 354 | |
| 355 | |
| 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 | |
| 378 | |
| 379 | |
| 380 | #[doc(hidden)] |
| 381 | pub fn test_leases(&self) -> Option<&crate::database::TestDatabases> { |
| 382 | self.leases.as_ref() |
| 383 | } |
| 384 | |
| 385 | |
| 386 | |
| 387 | pub fn control(&self) -> &Database { |
| 388 | &self.control |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | pub async fn get(&self, id: &SchoolId) -> Result<Database, AppError> { |
| 402 | Ok(self.resolve(id).await?.db) |
| 403 | } |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 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 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 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 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | pub async fn create( |
| 452 | &self, |
| 453 | id: SchoolId, |
| 454 | name: &str, |
| 455 | modules: ModuleSet, |
| 456 | ) -> Result<Database, AppError> { |
| 457 | |
| 458 | |
| 459 | |
| 460 | modules.validate()?; |
| 461 | |
| 462 | |
| 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 | |
| 476 | |
| 477 | |
| 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 | |
| 490 | |
| 491 | |
| 492 | |
| 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 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 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 | |
| 532 | |
| 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 | |
| 540 | |
| 541 | |
| 542 | async fn bring_up(&self, id: SchoolId) -> Result<Database, AppError> { |
| 543 | let db_name = school_db_name(&self.control_db, id.uuid()); |
| 544 | |
| 545 | |
| 546 | |
| 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 | |
| 555 | |
| 556 | |
| 557 | |
| 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 | |
| 567 | |
| 568 | |
| 569 | |
| 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 | |
| 579 | |
| 580 | |
| 581 | |
| 582 | pub async fn set_modules(&self, id: &SchoolId, modules: &ModuleSet) -> Result<(), AppError> { |
| 583 | modules.validate()?; |
| 584 | |
| 585 | |
| 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 | |
| 611 | |
| 612 | |
| 613 | pub async fn drop(&self, id: &SchoolId) -> Result<(), AppError> { |
| 614 | |
| 615 | |
| 616 | let Some(school) = School::read(id, &self.control).await? else { |
| 617 | return Ok(()); |
| 618 | }; |
| 619 | let id = school.get_id(); |
| 620 | |
| 621 | |
| 622 | |
| 623 | self.evict(id).await; |
| 624 | |
| 625 | |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 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 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 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 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 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 | |
| 682 | |
| 683 | |
| 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 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 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 | |
| 731 | |
| 732 | |
| 733 | |
| 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 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 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 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 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 | |
| 792 | |
| 793 | |
| 794 | |
| 795 | |
| 796 | |
| 797 | |
| 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 | |
| 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 | |
| 825 | |
| 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 | |
| 837 | |
| 838 | |
| 839 | fn report_size(size: usize) { |
| 840 | Metrics::global().tenant_cache_size.record(size as u64, &[]); |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | #[cfg(test)] |
| 845 | mod 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 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | #[test] |
| 871 | fn school_db_names_are_injective() { |
| 872 | let control = "hezarfen_control"; |
| 873 | |
| 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 | |
| 880 | |
| 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 | |
| 889 | |
| 890 | assert_ne!(school_db_name(control, id), control); |
| 891 | } |
| 892 | } |