The boot seed survives a rival boot
Browse files at this commitf8d7a2d222460bda7261ddf117c760129ae26968Parent: 331ae93- fix
- the boot seed survives a rival boot
- a failed create drops its database
4 changed files +81 -16
- .sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json → .sqlx/query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.json +2 -2
- src/db/builder.rs +15 -9
- src/service/builder.rs +45 -4
- src/tenant.rs +19 -1
.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json → .sqlx/query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.jsonrenamed+2 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", | 3 | + "query": "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)\n ON CONFLICT (username) DO NOTHING", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [], | 5 | "columns": [], |
| 6 | "parameters": { | 6 | "parameters": { |
| @@ -13,5 +13,5 @@ | |||
| 13 | }, | 13 | }, |
| 14 | "nullable": [] | 14 | "nullable": [] |
| 15 | }, | 15 | }, |
| 16 | - "hash": "f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583" | 16 | + "hash": "82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64" |
| 17 | } | 17 | } |
src/db/builder.rsmodified+15 -9
| @@ -39,14 +39,20 @@ pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppE | |||
| 39 | Ok(builder) | 39 | Ok(builder) |
| 40 | } | 40 | } |
| 41 | 41 | ||
| 42 | -/// The raw account insert behind [`crate::service::builder::ensure`]'s seed. | 42 | +/// Seed one builder account: the insert that leaves an existing row alone. |
| 43 | -/// The unique index on `username` is the whole availability check: a racing | 43 | +/// `true` when this call created it, `false` when the username was already |
| 44 | -/// second seed is a `23505` on `builder_username`, and the seed's | 44 | +/// taken. |
| 45 | -/// find-then-insert order makes that unreachable in practice — but the | 45 | +/// |
| 46 | -/// constraint stands guard regardless. | 46 | +/// `ON CONFLICT DO NOTHING` rather than find-then-insert-then-catch: the seed |
| 47 | -pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { | 47 | +/// runs on every boot, two boots of a fresh deployment collide on it, and an |
| 48 | - sqlx::query!( | 48 | +/// insert that is *refused* is logged by the server as an `ERROR` line even |
| 49 | - "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", | 49 | +/// when the client handles it (measured: four boots racing a fresh control |
| 50 | +/// database, three of them lost the race). The conflict target is the | ||
| 51 | +/// username index alone, so every other insert failure still surfaces. | ||
| 52 | +pub async fn create(db: &Database, builder: Builder) -> Result<bool, AppError> { | ||
| 53 | + let result = sqlx::query!( | ||
| 54 | + "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4) | ||
| 55 | + ON CONFLICT (username) DO NOTHING", | ||
| 50 | builder.id.uuid(), | 56 | builder.id.uuid(), |
| 51 | builder.username.as_str(), | 57 | builder.username.as_str(), |
| 52 | builder.password_hash.as_str(), | 58 | builder.password_hash.as_str(), |
| @@ -54,7 +60,7 @@ pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { | |||
| 54 | ) | 60 | ) |
| 55 | .execute(db) | 61 | .execute(db) |
| 56 | .await?; | 62 | .await?; |
| 57 | - Ok(()) | 63 | + Ok(result.rows_affected() == 1) |
| 58 | } | 64 | } |
| 59 | 65 | ||
| 60 | /// Mint and store one builder login session. | 66 | /// Mint and store one builder login session. |
src/service/builder.rsmodified+45 -4
| @@ -28,10 +28,15 @@ pub async fn ensure(db: &Database, username: Username, password: Password) -> Re | |||
| 28 | password_hash: password.hash_async().await?, | 28 | password_hash: password.hash_async().await?, |
| 29 | username, | 29 | username, |
| 30 | }; | 30 | }; |
| 31 | - builder::create(db, builder).await?; | 31 | + // A rival boot that seeded the same username between the read above and |
| 32 | - // The account name stays out of the event: exported log records must | 32 | + // this insert loses the race silently — `create` reports "already there" |
| 33 | - // name no person (see `telemetry`). | 33 | + // instead of raising, so the second container of a fresh deployment boots |
| 34 | - tracing::info!("seeded the builder account named by BUILDER_USERNAME"); | 34 | + // instead of dying on a duplicate key. The winner's credential stands. |
| 35 | + if builder::create(db, builder).await? { | ||
| 36 | + // The account name stays out of the event: exported log records must | ||
| 37 | + // name no person (see `telemetry`). | ||
| 38 | + tracing::info!("seeded the builder account named by BUILDER_USERNAME"); | ||
| 39 | + } | ||
| 35 | Ok(()) | 40 | Ok(()) |
| 36 | } | 41 | } |
| 37 | 42 | ||
| @@ -92,4 +97,40 @@ mod tests { | |||
| 92 | first.get_password_hash().as_str() | 97 | first.get_password_hash().as_str() |
| 93 | ); | 98 | ); |
| 94 | } | 99 | } |
| 100 | + | ||
| 101 | + /// Two boots of one deployment seed the same username in the same instant. | ||
| 102 | + /// The loser must adopt the winner's row instead of dying on its own | ||
| 103 | + /// insert — measured on a fresh control database: four boots racing, three | ||
| 104 | + /// died on `23505 builder_username` and only the winner stayed up. | ||
| 105 | + #[tokio::test] | ||
| 106 | + async fn a_racing_seed_adopts_the_row_it_lost_to() { | ||
| 107 | + let tenants = crate::database::init_test_tenants().await; | ||
| 108 | + let control = tenants.control(); | ||
| 109 | + let name = Username::try_new("builder_race").unwrap(); | ||
| 110 | + let (first, second) = tokio::join!( | ||
| 111 | + ensure(control, name.clone(), Password::try_new("secret1").unwrap()), | ||
| 112 | + ensure(control, name.clone(), Password::try_new("secret2").unwrap()), | ||
| 113 | + ); | ||
| 114 | + first.expect("the first seed"); | ||
| 115 | + second.expect("the racing seed adopts the account the winner seeded"); | ||
| 116 | + | ||
| 117 | + // One account, and the credential is whichever writer won the insert — | ||
| 118 | + // neither seed rewrites the other's row. | ||
| 119 | + let row = find_by_username(control, "builder_race") | ||
| 120 | + .await | ||
| 121 | + .unwrap() | ||
| 122 | + .expect("seeded"); | ||
| 123 | + let matches_offered = row | ||
| 124 | + .get_password_hash() | ||
| 125 | + .verify_async(&Password::try_new("secret1").unwrap()) | ||
| 126 | + .await | ||
| 127 | + || row | ||
| 128 | + .get_password_hash() | ||
| 129 | + .verify_async(&Password::try_new("secret2").unwrap()) | ||
| 130 | + .await; | ||
| 131 | + assert!( | ||
| 132 | + matches_offered, | ||
| 133 | + "the stored hash belongs to no offered password" | ||
| 134 | + ); | ||
| 135 | + } | ||
| 95 | } | 136 | } |
src/tenant.rsmodified+19 -1
| @@ -470,6 +470,25 @@ impl Tenants { | |||
| 470 | .bind(id.uuid()) | 470 | .bind(id.uuid()) |
| 471 | .execute(&self.control) | 471 | .execute(&self.control) |
| 472 | .await; | 472 | .await; |
| 473 | + // The rows go first — a slug taken by a school that never came | ||
| 474 | + // to exist is wedged for good — then the database, which is the | ||
| 475 | + // expensive half and whose name nothing will ever reuse (the id | ||
| 476 | + // is minted per create, never replayed). Best-effort, but not | ||
| 477 | + // silent: a failure here is a half-provisioned database nobody | ||
| 478 | + // can see or reach, so it earns the one log line this path has. | ||
| 479 | + if let Err(leak) = sqlx::query(sqlx::AssertSqlSafe( | ||
| 480 | + create_database_sql( | ||
| 481 | + "DROP DATABASE IF EXISTS", | ||
| 482 | + &school_db_name(&self.control_db, id.uuid()), | ||
| 483 | + ) + " WITH (FORCE)", | ||
| 484 | + )) | ||
| 485 | + .execute(&self.control) | ||
| 486 | + .await | ||
| 487 | + { | ||
| 488 | + tracing::warn!( | ||
| 489 | + "failed to drop the database of a school whose create failed: {leak}" | ||
| 490 | + ); | ||
| 491 | + } | ||
| 473 | return Err(err); | 492 | return Err(err); |
| 474 | } | 493 | } |
| 475 | }; | 494 | }; |
| @@ -651,7 +670,6 @@ impl Tenants { | |||
| 651 | mod tests { | 670 | mod tests { |
| 652 | use super::*; | 671 | use super::*; |
| 653 | 672 | ||
| 654 | - | ||
| 655 | #[test] | 673 | #[test] |
| 656 | fn a_slug_names_a_school_and_nothing_reserved() { | 674 | fn a_slug_names_a_school_and_nothing_reserved() { |
| 657 | for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { | 675 | for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { |