π§ freeze a fee plan the moment it is assigned
Browse files at this commitac70cc0fa4b98d28d6873a4660556b3497b61edbParent: a9cfe7b- fix
- π§ freeze a fee plan the moment it is assigned
11 changed files +618 -116
- README.md +27 -2
- src/constant.rs +13 -0
- src/database.rs +155 -1
- src/domain/cap.rs +12 -20
- src/domain/fee_plan.rs +42 -20
- src/domain/fee_plan_assignment.rs +262 -38
- src/domain/field_update.rs +46 -14
- src/lib.rs +1 -1
- src/migration_sql.rs +26 -0
- src/web/payments.rs +28 -20
- tests/limits_completeness.rs +6 -0
README.mdmodified+27 -2
| @@ -1485,6 +1485,27 @@ A plan that has been assigned to anyone can no longer be edited or deleted | |||
| 1485 | an edit would only make the plan and the money tell different stories β write | 1485 | an edit would only make the plan and the money tell different stories β write |
| 1486 | a new plan instead. | 1486 | a new plan instead. |
| 1487 | 1487 | ||
| 1488 | +That freeze is a **counter on the plan row** (`assignment_count`), incremented | ||
| 1489 | +in the *same transaction* as the assignment row it counts, and the edit and the | ||
| 1490 | +delete are single-record conditional writes against it β the same shape as a | ||
| 1491 | +term's `course_count`. It used to be a `SELECT` taken before the write, which a | ||
| 1492 | +concurrent assign could land behind, leaving a plan edited *and* assigned, or | ||
| 1493 | +deleted with a live assignment naming it. Now the two contend on one record: an | ||
| 1494 | +assign either freezes the plan first (and the edit or delete is a `409`) or | ||
| 1495 | +arrives after it (and bills the edited plan β the installments a first | ||
| 1496 | +assignment charges are re-read from the *stored* plan at the instant it | ||
| 1497 | +freezes, never from the copy the request first looked at). A plan deleted out | ||
| 1498 | +from under a running batch is `rejected` for that student on, in the same | ||
| 1499 | +per-student report as every other outcome β the students it already billed are | ||
| 1500 | +never dropped from the answer. A `PATCH` | ||
| 1501 | +carrying no field at all writes nothing, so it is not refused. | ||
| 1502 | + | ||
| 1503 | +Because an assignment is never removed, the counter is only ever claimed and | ||
| 1504 | +never released: once assigned, a plan stays frozen for good. Plans written | ||
| 1505 | +before the counter existed are seeded from their assignment rows at boot, | ||
| 1506 | +before the server accepts a request β an absent counter reads as zero, and a | ||
| 1507 | +zero would have re-opened every already-assigned plan on an existing volume. | ||
| 1508 | + | ||
| 1488 | ### The ledger | 1509 | ### The ledger |
| 1489 | 1510 | ||
| 1490 | The money is an **append-only ledger** (`payment_ledger`), exactly like the | 1511 | The money is an **append-only ledger** (`payment_ledger`), exactly like the |
| @@ -2475,9 +2496,13 @@ database itself decides the winner. Three tiers: | |||
| 2475 | row being deleted rather than a `SELECT` over the children: a course is | 2496 | row being deleted rather than a `SELECT` over the children: a course is |
| 2476 | deletable while its `enrollment_count` is zero, a term while its | 2497 | deletable while its `enrollment_count` is zero, a term while its |
| 2477 | `course_count` is (courses claim that reference *before* they write the | 2498 | `course_count` is (courses claim that reference *before* they write the |
| 2478 | - link, and give it back when the link moves or the course is deleted). | 2499 | + link, and give it back when the link moves or the course is deleted). A fee |
| 2500 | + plan reads the same way β editable *and* deletable while its | ||
| 2501 | + `assignment_count` is zero, and frozen for good once it is not, since an | ||
| 2502 | + assignment is never taken back. | ||
| 2479 | Where the child also carries a deterministic id β one enrollment per | 2503 | Where the child also carries a deterministic id β one enrollment per |
| 2480 | - (course, user), one registration per (event, user) β the seat and the row | 2504 | + (course, user), one registration per (event, user), one fee-plan assignment |
| 2505 | + per (plan, student) β the seat and the row | ||
| 2481 | are claimed in one transaction (`cap::claim_and_create`), so a duplicate | 2506 | are claimed in one transaction (`cap::claim_and_create`), so a duplicate |
| 2482 | `CREATE` rolls its own seat back instead of costing a stranger their place. | 2507 | `CREATE` rolls its own seat back instead of costing a stranger their place. |
| 2483 | 3. **Two accepted races**, reviewed and deliberately left open: | 2508 | 3. **Two accepted races**, reviewed and deliberately left open: |
src/constant.rsmodified+13 -0
| @@ -686,6 +686,19 @@ pub const REGISTRATION_COUNT_FIELD: &str = "registration_count"; | |||
| 686 | /// is claimed before a course's link is written, so the two decisions contend | 686 | /// is claimed before a course's link is written, so the two decisions contend |
| 687 | /// on the term row instead of on a cross-table `SELECT` no transaction orders. | 687 | /// on the term row instead of on a cross-table `SELECT` no transaction orders. |
| 688 | pub const COURSE_COUNT_FIELD: &str = "course_count"; | 688 | pub const COURSE_COUNT_FIELD: &str = "course_count"; |
| 689 | +/// A refcount too, and the whole of the fee-plan edit *and* delete guard: how | ||
| 690 | +/// many students are on this plan. A plan may only be edited or deleted at | ||
| 691 | +/// zero, and the count is claimed in the same transaction as the assignment | ||
| 692 | +/// row, so a manager's edit and a concurrent assign contend on the plan row | ||
| 693 | +/// rather than on a `SELECT` the edit had already outrun. Nothing ever | ||
| 694 | +/// releases it β an assignment is never unassigned, because the charges it | ||
| 695 | +/// raised are history. | ||
| 696 | +pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count"; | ||
| 697 | +/// The condition itself, spelled once: a plan is editable and deletable | ||
| 698 | +/// exactly while nobody is on it. The `??` is parenthesized on purpose β | ||
| 699 | +/// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* | ||
| 700 | +/// row and would license editing a plan a family is already being billed for. | ||
| 701 | +pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; | ||
| 689 | pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; | 702 | pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; |
| 690 | pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; | 703 | pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; |
| 691 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; | 704 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; |
src/database.rsmodified+155 -1
| @@ -5,7 +5,8 @@ use surrealdb::engine::any::Any; | |||
| 5 | use surrealdb::opt::auth::Root; | 5 | use surrealdb::opt::auth::Root; |
| 6 | 6 | ||
| 7 | use crate::config::Config; | 7 | use crate::config::Config; |
| 8 | -use crate::constant::CHATBOT_PENDING_STALE_SECS; | 8 | +use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; |
| 9 | +use crate::domain::timestamp::Timestamp; | ||
| 9 | use crate::domain::user::{Password, User, Username}; | 10 | use crate::domain::user::{Password, User, Username}; |
| 10 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 11 | use crate::migration_sql::MIGRATION_BATCHES; | 12 | use crate::migration_sql::MIGRATION_BATCHES; |
| @@ -102,6 +103,51 @@ pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { | |||
| 102 | message.contains("already exists") || message.contains("can be retried") | 103 | message.contains("already exists") || message.contains("can be retried") |
| 103 | } | 104 | } |
| 104 | 105 | ||
| 106 | +/// Send one guarded single-statement write, re-sending it while the store | ||
| 107 | +/// answers "conflict, retry", and hand back the rows it returned. | ||
| 108 | +/// | ||
| 109 | +/// The guard on such a statement reads a column a rival writes, so the two | ||
| 110 | +/// contend on one record *by design* β that contention is what makes the guard | ||
| 111 | +/// atomic. Losing a round writes nothing at all, which makes re-sending the | ||
| 112 | +/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE` | ||
| 113 | +/// answers 500 instead of the 404 or 409 it owes. Only for statements that | ||
| 114 | +/// cannot produce "already exists" (the other thing [`lost_the_race`] matches), | ||
| 115 | +/// so `UPDATE` and `DELETE` and not `CREATE`. | ||
| 116 | +pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>( | ||
| 117 | + db: &Database, | ||
| 118 | + sql: &str, | ||
| 119 | + bindings: &[(String, surrealdb::types::Value)], | ||
| 120 | +) -> Result<Vec<T>, AppError> { | ||
| 121 | + let mut last = None; | ||
| 122 | + for attempt in 0..CAP_WRITE_TRIES { | ||
| 123 | + backoff(attempt).await; | ||
| 124 | + let mut query = db.query(sql); | ||
| 125 | + for (name, value) in bindings { | ||
| 126 | + query = query.bind((name.clone(), value.clone())); | ||
| 127 | + } | ||
| 128 | + match async { query.await?.check()?.take::<Vec<T>>(0) }.await { | ||
| 129 | + Ok(rows) => return Ok(rows), | ||
| 130 | + Err(err) if lost_the_race(&err) => last = Some(err), | ||
| 131 | + Err(err) => return Err(err.into()), | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + Err(last | ||
| 135 | + .map(AppError::from) | ||
| 136 | + .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into()))) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Wait out one lost round. Exponential with jitter, because racers arrive in | ||
| 140 | +/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. | ||
| 141 | +/// Attempt zero waits not at all. | ||
| 142 | +pub(crate) async fn backoff(attempt: usize) { | ||
| 143 | + if attempt == 0 { | ||
| 144 | + return; | ||
| 145 | + } | ||
| 146 | + let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); | ||
| 147 | + let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); | ||
| 148 | + tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; | ||
| 149 | +} | ||
| 150 | + | ||
| 105 | /// Dial the database, retrying until it answers. | 151 | /// Dial the database, retrying until it answers. |
| 106 | /// | 152 | /// |
| 107 | /// Never gives up, because giving up is worse than waiting: the database is | 153 | /// Never gives up, because giving up is worse than waiting: the database is |
| @@ -137,6 +183,42 @@ pub async fn init_mem() -> Result<Database, AppError> { | |||
| 137 | Ok(std::sync::Arc::new(db)) | 183 | Ok(std::sync::Arc::new(db)) |
| 138 | } | 184 | } |
| 139 | 185 | ||
| 186 | +/// A handle on a **real** SurrealDB server, in a scratch namespace of its own | ||
| 187 | +/// that is dropped and re-made on every call. For the tests whose subject is | ||
| 188 | +/// the store's own conflict detection, which [`init_mem`]'s embedded engine | ||
| 189 | +/// does not have: it drops one of two concurrent writes to a record and answers | ||
| 190 | +/// `Ok` to both (see [`crate::domain::cap`]), which *forges* the very | ||
| 191 | +/// integrity failure those tests exist to catch β measured 2026-07-30 at 2 | ||
| 192 | +/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here. | ||
| 193 | +/// | ||
| 194 | +/// Every caller is `#[ignore]`d, so a machine with no server prints them as | ||
| 195 | +/// `ignored` rather than passing: this is not a test that may quietly skip. | ||
| 196 | +/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s. | ||
| 197 | +#[cfg(test)] | ||
| 198 | +pub(crate) async fn init_test_server(scratch: &str) -> Database { | ||
| 199 | + let url = | ||
| 200 | + std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); | ||
| 201 | + let db = surrealdb::engine::any::connect(url.clone()) | ||
| 202 | + .await | ||
| 203 | + .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})")); | ||
| 204 | + db.signin(Root { | ||
| 205 | + username: "root".into(), | ||
| 206 | + password: "root".into(), | ||
| 207 | + }) | ||
| 208 | + .await | ||
| 209 | + .expect("sign in to the test server"); | ||
| 210 | + let ns = format!("test_{scratch}"); | ||
| 211 | + db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}")) | ||
| 212 | + .await | ||
| 213 | + .expect("clear the scratch namespace") | ||
| 214 | + .check() | ||
| 215 | + .expect("clear the scratch namespace"); | ||
| 216 | + db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); | ||
| 217 | + let db = std::sync::Arc::new(db); | ||
| 218 | + migrate(&db).await.expect("migrate the scratch namespace"); | ||
| 219 | + db | ||
| 220 | +} | ||
| 221 | + | ||
| 140 | /// Apply the schema + backfills. Idempotent β `init` runs it on every boot, | 222 | /// Apply the schema + backfills. Idempotent β `init` runs it on every boot, |
| 141 | /// and tests re-run it on a live handle to simulate a second boot. | 223 | /// and tests re-run it on a live handle to simulate a second boot. |
| 142 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | 224 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { |
| @@ -221,6 +303,78 @@ mod tests { | |||
| 221 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); | 303 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); |
| 222 | } | 304 | } |
| 223 | 305 | ||
| 306 | + /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume | ||
| 307 | + /// carries plans and assignments written before the counter column existed, | ||
| 308 | + /// and an absent counter reads as **zero** β which is exactly the value | ||
| 309 | + /// that licenses an edit and a delete. Unseeded, every already-assigned | ||
| 310 | + /// plan on every existing volume would go editable and deletable again, so | ||
| 311 | + /// the backfill is the whole of the stale-data story, not a nicety. | ||
| 312 | + #[tokio::test] | ||
| 313 | + async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { | ||
| 314 | + use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName}; | ||
| 315 | + use crate::error::AppError; | ||
| 316 | + | ||
| 317 | + let db = super::init_mem().await.unwrap(); | ||
| 318 | + // The old shape: rows stating every column the older binary knew, and | ||
| 319 | + // no `assignment_count` at all. `used` carries an assignment, `free` | ||
| 320 | + // does not β a plan nobody is on must stay editable. | ||
| 321 | + db.query( | ||
| 322 | + "CREATE user:m SET username = 'm', password_hash = 'x'; | ||
| 323 | + CREATE user:s SET username = 's', password_hash = 'x'; | ||
| 324 | + CREATE fee_plan:used SET name = 'Yearly', | ||
| 325 | + installments = [{ amount_minor: 100, due_at: 1 }], | ||
| 326 | + created_by = user:m, created_at = 1; | ||
| 327 | + CREATE fee_plan:free SET name = 'Unused', | ||
| 328 | + installments = [{ amount_minor: 100, due_at: 1 }], | ||
| 329 | + created_by = user:m, created_at = 1; | ||
| 330 | + CREATE fee_plan_assignment:used_s SET plan = fee_plan:used, | ||
| 331 | + student = user:s, assigned_by = user:m, created_at = 1;", | ||
| 332 | + ) | ||
| 333 | + .await | ||
| 334 | + .unwrap() | ||
| 335 | + .check() | ||
| 336 | + .unwrap(); | ||
| 337 | + | ||
| 338 | + // Twice: every boot runs the backfill, and a second pass must not | ||
| 339 | + // double a counter it already seeded. | ||
| 340 | + super::migrate(&db).await.unwrap(); | ||
| 341 | + super::migrate(&db).await.unwrap(); | ||
| 342 | + | ||
| 343 | + let mut counts = db | ||
| 344 | + .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id") | ||
| 345 | + .await | ||
| 346 | + .unwrap(); | ||
| 347 | + let counts: Vec<Option<i64>> = counts.take(0).unwrap(); | ||
| 348 | + // `free` before `used` by id; the unused plan is deliberately left | ||
| 349 | + // absent, which already reads as zero in the guard. | ||
| 350 | + assert_eq!(counts, vec![None, Some(1)]); | ||
| 351 | + | ||
| 352 | + // The load-bearing half: the seeded plan is frozen, and the untouched | ||
| 353 | + // one is not. | ||
| 354 | + let used = FeePlan::read(&FeePlanId::from_key("used"), &db) | ||
| 355 | + .await | ||
| 356 | + .unwrap() | ||
| 357 | + .unwrap(); | ||
| 358 | + assert!(matches!( | ||
| 359 | + used.clone() | ||
| 360 | + .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) | ||
| 361 | + .await, | ||
| 362 | + Err(AppError::Conflict(_)) | ||
| 363 | + )); | ||
| 364 | + assert!(!used.delete(&db).await.unwrap()); | ||
| 365 | + let free = FeePlan::read(&FeePlanId::from_key("free"), &db) | ||
| 366 | + .await | ||
| 367 | + .unwrap() | ||
| 368 | + .unwrap(); | ||
| 369 | + assert!( | ||
| 370 | + free.clone() | ||
| 371 | + .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) | ||
| 372 | + .await | ||
| 373 | + .is_ok() | ||
| 374 | + ); | ||
| 375 | + assert!(free.delete(&db).await.unwrap()); | ||
| 376 | + } | ||
| 377 | + | ||
| 224 | #[tokio::test] | 378 | #[tokio::test] |
| 225 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { | 379 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { |
| 226 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. | 380 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. |
src/domain/cap.rsmodified+12 -20
| @@ -29,9 +29,8 @@ | |||
| 29 | use surrealdb::types::{RecordId, SurrealValue}; | 29 | use surrealdb::types::{RecordId, SurrealValue}; |
| 30 | use tokio::sync::Mutex; | 30 | use tokio::sync::Mutex; |
| 31 | 31 | ||
| 32 | -use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD}; | 32 | +use crate::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD}; |
| 33 | -use crate::database::{Database, lost_the_race}; | 33 | +use crate::database::{Database, backoff, lost_the_race}; |
| 34 | -use crate::domain::timestamp::Timestamp; | ||
| 35 | use crate::error::AppError; | 34 | use crate::error::AppError; |
| 36 | 35 | ||
| 37 | /// One counter writer at a time, over every counter. | 36 | /// One counter writer at a time, over every counter. |
| @@ -196,13 +195,18 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | |||
| 196 | { | 195 | { |
| 197 | return Ok(Claimed::Full); | 196 | return Ok(Claimed::Full); |
| 198 | } | 197 | } |
| 199 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 198 | + // A conflict in *any* slot is the whole batch's verdict, and it is read |
| 200 | - if !lost_the_race(&error) { | 199 | + // before the arbitrary pick below: the siblings say only "not executed", |
| 201 | - return Err(error.into()); | 200 | + // which is the *consequence* of this abort and never a reason of its |
| 202 | - } | 201 | + // own. Picking one of those out of a `HashMap` β unordered, so it wins |
| 203 | - last = Some(error); | 202 | + // most rounds β retired a retryable round as a 500. |
| 203 | + if errors.values().any(lost_the_race) { | ||
| 204 | + last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 204 | continue; | 205 | continue; |
| 205 | } | 206 | } |
| 207 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 208 | + return Err(error.into()); | ||
| 209 | + } | ||
| 206 | // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. | 210 | // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. |
| 207 | return result | 211 | return result |
| 208 | .take::<Vec<T>>(5)? | 212 | .take::<Vec<T>>(5)? |
| @@ -216,18 +220,6 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | |||
| 216 | .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | 220 | .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) |
| 217 | } | 221 | } |
| 218 | 222 | ||
| 219 | -/// Wait out one lost round. Exponential with jitter, because racers arrive in | ||
| 220 | -/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. | ||
| 221 | -/// Attempt zero waits not at all. | ||
| 222 | -async fn backoff(attempt: usize) { | ||
| 223 | - if attempt == 0 { | ||
| 224 | - return; | ||
| 225 | - } | ||
| 226 | - let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); | ||
| 227 | - let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); | ||
| 228 | - tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; | ||
| 229 | -} | ||
| 230 | - | ||
| 231 | /// Move `parent` to its next revision. A revision column is not a cap: it is | 223 | /// Move `parent` to its next revision. A revision column is not a cap: it is |
| 232 | /// what a reader pins a value it took off the parent to, so that a write which | 224 | /// what a reader pins a value it took off the parent to, so that a write which |
| 233 | /// invalidates that value (a menu's price) can refuse the claim carrying the old | 225 | /// invalidates that value (a menu's price) can refuse the claim carrying the old |
src/domain/fee_plan.rsmodified+42 -20
| @@ -16,8 +16,10 @@ | |||
| 16 | 16 | ||
| 17 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 17 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 18 | 18 | ||
| 19 | -use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; | 19 | +use crate::constant::{ |
| 20 | -use crate::database::Database; | 20 | + FEE_PLAN_TABLE, FEE_PLAN_UNASSIGNED_GUARD, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN, |
| 21 | +}; | ||
| 22 | +use crate::database::{Database, write_with_retry}; | ||
| 21 | use crate::domain::field_update::FieldUpdate; | 23 | use crate::domain::field_update::FieldUpdate; |
| 22 | use crate::domain::monotonic_id::next_ulid; | 24 | use crate::domain::monotonic_id::next_ulid; |
| 23 | use crate::domain::page::PagedList; | 25 | use crate::domain::page::PagedList; |
| @@ -169,13 +171,19 @@ impl FeePlan { | |||
| 169 | 171 | ||
| 170 | /// Write only the fields the PATCH carried β `None` means the request | 172 | /// Write only the fields the PATCH carried β `None` means the request |
| 171 | /// omitted it, so the column is left alone rather than re-stated from the | 173 | /// omitted it, so the column is left alone rather than re-stated from the |
| 172 | - /// snapshot this struct was read into. | 174 | + /// snapshot this struct was read into. `Err(Conflict)` = refused, nothing |
| 175 | + /// was written: somebody is already on the plan. | ||
| 173 | /// | 176 | /// |
| 174 | /// Editing a plan never moves money: charges are frozen copies of the | 177 | /// Editing a plan never moves money: charges are frozen copies of the |
| 175 | - /// installments as they stood when the plan was assigned. The web layer | 178 | + /// installments as they stood when the plan was assigned. That is exactly |
| 176 | - /// refuses the edit outright once [`FeePlan::has_assignments`] holds, so a | 179 | + /// why an assigned plan may not be edited at all β the plan and the charges |
| 177 | - /// plan and the charges raised from it cannot drift apart in the first | 180 | + /// raised from it would tell different stories. The roster is the plan's own |
| 178 | - /// place. | 181 | + /// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same |
| 182 | + /// transaction as the assignment row, so the check and the write are one | ||
| 183 | + /// conditional `UPDATE` on one record: an assign racing this either claims | ||
| 184 | + /// first (and the edit is refused) or claims after (and bills the edited | ||
| 185 | + /// plan, which it re-reads). A `SELECT`-then-write could be, and was, | ||
| 186 | + /// stepped over in the gap between the two. | ||
| 179 | pub async fn update( | 187 | pub async fn update( |
| 180 | self, | 188 | self, |
| 181 | name: Option<FeePlanName>, | 189 | name: Option<FeePlanName>, |
| @@ -188,24 +196,38 @@ impl FeePlan { | |||
| 188 | FieldUpdate::new(self.id.record()) | 196 | FieldUpdate::new(self.id.record()) |
| 189 | .set("name", name) | 197 | .set("name", name) |
| 190 | .set("installments", installments) | 198 | .set("installments", installments) |
| 199 | + .guard( | ||
| 200 | + FEE_PLAN_UNASSIGNED_GUARD, | ||
| 201 | + AppError::Conflict("an assigned plan cannot be edited"), | ||
| 202 | + ) | ||
| 191 | .run::<FeePlan>(db) | 203 | .run::<FeePlan>(db) |
| 192 | .await | 204 | .await |
| 193 | } | 205 | } |
| 194 | 206 | ||
| 195 | - pub async fn delete(self, db: &Database) -> Result<(), AppError> { | 207 | + /// Delete the plan, but only while nobody is on it. `false` = refused, |
| 196 | - let _: Option<FeePlan> = db.delete(self.id.record()).await?; | 208 | + /// nothing was written; `Err(NotFound)` keeps the answer a concurrent |
| 197 | - Ok(()) | 209 | + /// *delete* gives. Same one-record guard as [`FeePlan::update`], and the |
| 198 | - } | 210 | + /// same reason β the charges an assignment raised name this plan, and a |
| 199 | - | 211 | + /// school's financial history keeps its references. |
| 200 | - /// Has this plan ever been assigned? The 409 guard on edit and delete. | ||
| 201 | /// | 212 | /// |
| 202 | - /// A scan, and deliberately so: it races an assign landing in the gap | 213 | + /// Retried while the store answers "conflict, retry": the guard reads a |
| 203 | - /// between this read and the edit it licenses, which can leave a plan edited | 214 | + /// counter an assign *writes*, so the two contend on this one record by |
| 204 | - /// *and* assigned. Accepted β both versions of the plan were manager-approved, | 215 | + /// design β and a delete that loses that round has written nothing, so |
| 205 | - /// and the charges the assign raised are frozen copies either way, so no | 216 | + /// re-sending it is the whole of the recovery. Without the retry an |
| 206 | - /// money moves behind anyone's back. | 217 | + /// ordinary raced delete answers 500 instead of the 404 or 409 it owes. |
| 207 | - pub async fn has_assignments(id: &FeePlanId, db: &Database) -> Result<bool, AppError> { | 218 | + pub async fn delete(self, db: &Database) -> Result<bool, AppError> { |
| 208 | - crate::domain::fee_plan_assignment::FeePlanAssignment::exists_for_plan(id, db).await | 219 | + let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE"); |
| 220 | + let deleted: Vec<FeePlan> = | ||
| 221 | + write_with_retry(db, &sql, &[("plan".into(), self.id.record().into_value())]).await?; | ||
| 222 | + if !deleted.is_empty() { | ||
| 223 | + return Ok(true); | ||
| 224 | + } | ||
| 225 | + // Still assigned or already gone: the one statement cannot tell those | ||
| 226 | + // apart, and only the refusal path pays for the read that can. | ||
| 227 | + match Self::read(&self.id, db).await? { | ||
| 228 | + Some(_) => Ok(false), | ||
| 229 | + None => Err(AppError::NotFound), | ||
| 230 | + } | ||
| 209 | } | 231 | } |
| 210 | } | 232 | } |
| 211 | 233 | ||
src/domain/fee_plan_assignment.rsmodified+262 -38
| @@ -12,12 +12,14 @@ | |||
| 12 | //! | 12 | //! |
| 13 | //! Nothing is ever edited or deleted: unassigning is not a thing, because the | 13 | //! Nothing is ever edited or deleted: unassigning is not a thing, because the |
| 14 | //! charges are already history. A plan raised in error is undone by reversing | 14 | //! charges are already history. A plan raised in error is undone by reversing |
| 15 | -//! its charges. | 15 | +//! its charges. That is also why the plan's assignment refcount is only ever |
| 16 | +//! claimed and never released β a plan, once assigned, stays frozen for good. | ||
| 16 | 17 | ||
| 17 | -use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; | 18 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 18 | 19 | ||
| 19 | -use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE; | 20 | +use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE}; |
| 20 | -use crate::database::{Database, lost_the_race}; | 21 | +use crate::database::Database; |
| 22 | +use crate::domain::cap::{self, Claimed}; | ||
| 21 | use crate::domain::fee_plan::{FeePlan, FeePlanId}; | 23 | use crate::domain::fee_plan::{FeePlan, FeePlanId}; |
| 22 | use crate::domain::page::PagedList; | 24 | use crate::domain::page::PagedList; |
| 23 | use crate::domain::payment_ledger::PaymentLedger; | 25 | use crate::domain::payment_ledger::PaymentLedger; |
| @@ -90,6 +92,20 @@ impl FeePlanAssignment { | |||
| 90 | /// whether it was *already* there, so the web layer can answer a replay | 92 | /// whether it was *already* there, so the web layer can answer a replay |
| 91 | /// honestly instead of pretending it just happened. | 93 | /// honestly instead of pretending it just happened. |
| 92 | /// | 94 | /// |
| 95 | + /// The row and the plan's assignment refcount are written in **one** | ||
| 96 | + /// transaction ([`cap::claim_and_create`]): that increment is what makes the | ||
| 97 | + /// plan un-editable and un-deletable, and it has to be indivisible from the | ||
| 98 | + /// row it counts, or an edit could slip between the two. A plan the counter | ||
| 99 | + /// cannot be claimed on is one a concurrent delete already removed, which is | ||
| 100 | + /// the same `404` the handler's own lookup would have given. | ||
| 101 | + /// | ||
| 102 | + /// The installments are then re-read **from the stored plan**, not taken | ||
| 103 | + /// from the caller's snapshot: the claim is the moment the plan freezes, and | ||
| 104 | + /// an edit that landed between the handler's read and that claim is | ||
| 105 | + /// legitimate. Billing the snapshot would raise charges from a schedule the | ||
| 106 | + /// plan no longer shows β precisely the divergence the 409 exists to | ||
| 107 | + /// prevent. | ||
| 108 | + /// | ||
| 93 | /// The charges are appended after the row, never before: each one is keyed | 109 | /// The charges are appended after the row, never before: each one is keyed |
| 94 | /// by (assignment, installment number), so this loop is safe to re-enter | 110 | /// by (assignment, installment number), so this loop is safe to re-enter |
| 95 | /// from the top β which is exactly what a repeated assign does, and the | 111 | /// from the top β which is exactly what a repeated assign does, and the |
| @@ -101,30 +117,35 @@ impl FeePlanAssignment { | |||
| 101 | db: &Database, | 117 | db: &Database, |
| 102 | ) -> Result<(FeePlanAssignment, bool), AppError> { | 118 | ) -> Result<(FeePlanAssignment, bool), AppError> { |
| 103 | let id = FeePlanAssignmentId::composite(plan.get_id(), student); | 119 | let id = FeePlanAssignmentId::composite(plan.get_id(), student); |
| 104 | - let (assignment, existed) = match Self::read(&id, db).await? { | 120 | + let row = FeePlanAssignment { |
| 105 | - Some(existing) => (existing, true), | 121 | + id: id.clone(), |
| 106 | - None => { | 122 | + plan: plan.get_id().clone(), |
| 107 | - let row = FeePlanAssignment { | 123 | + student: student.clone(), |
| 108 | - id: id.clone(), | 124 | + assigned_by: assigned_by.clone(), |
| 109 | - plan: plan.get_id().clone(), | 125 | + created_at: Timestamp::now(), |
| 110 | - student: student.clone(), | 126 | + }; |
| 111 | - assigned_by: assigned_by.clone(), | 127 | + let claimed = cap::claim_and_create( |
| 112 | - created_at: Timestamp::now(), | 128 | + &plan.get_id().record(), |
| 113 | - }; | 129 | + FEE_PLAN_ASSIGNMENT_COUNT_FIELD, |
| 114 | - match db.create(id.record()).content(row).await { | 130 | + cap::UNLIMITED, |
| 115 | - Ok(Some(created)) => (created, false), | 131 | + &id.record(), |
| 116 | - // Someone assigned this pair first, or the write was | 132 | + &row, |
| 117 | - // aborted as retryable β either way their row is the | 133 | + db, |
| 118 | - // answer, and the charges below are keyed the same, so | 134 | + ) |
| 119 | - // continuing here can only *complete* the billing. | 135 | + .await?; |
| 120 | - Ok(None) => (Self::require(&id, db).await?, true), | 136 | + let (assignment, existed) = match claimed { |
| 121 | - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | 137 | + Claimed::Made(created) => (created, false), |
| 122 | - (Self::require(&id, db).await?, true) | 138 | + // Someone assigned this pair first β their row is the answer, and |
| 123 | - } | 139 | + // the charges below are keyed the same, so continuing here can only |
| 124 | - Err(e) => return Err(e.into()), | 140 | + // *complete* the billing. Their claim already counts this row. |
| 125 | - } | 141 | + Claimed::Duplicate => (Self::require(&id, db).await?, true), |
| 126 | - } | 142 | + // The counter is uncapped, so the only miss is a plan that is gone. |
| 143 | + Claimed::Full => return Err(AppError::NotFound), | ||
| 127 | }; | 144 | }; |
| 145 | + // Frozen as of the claim above: no edit can land past it any more. | ||
| 146 | + let plan = FeePlan::read(plan.get_id(), db) | ||
| 147 | + .await? | ||
| 148 | + .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; | ||
| 128 | for (index, installment) in plan.get_installments().iter().enumerate() { | 149 | for (index, installment) in plan.get_installments().iter().enumerate() { |
| 129 | PaymentLedger::charge_for_installment( | 150 | PaymentLedger::charge_for_installment( |
| 130 | &assignment, | 151 | &assignment, |
| @@ -170,8 +191,10 @@ impl FeePlanAssignment { | |||
| 170 | .await | 191 | .await |
| 171 | } | 192 | } |
| 172 | 193 | ||
| 173 | - /// Is anybody on this plan? Backs the edit/delete guard β see | 194 | + /// Is anybody on this plan? A scan, and no longer a guard: the edit and |
| 174 | - /// [`FeePlan::has_assignments`] for the race it accepts. | 195 | + /// delete guards read the plan's own refcount, which no concurrent assign |
| 196 | + /// can be behind. Kept because a *test* asserting the rows and the counter | ||
| 197 | + /// agree is the only thing that would catch the counter drifting. | ||
| 175 | pub async fn exists_for_plan(plan: &FeePlanId, db: &Database) -> Result<bool, AppError> { | 198 | pub async fn exists_for_plan(plan: &FeePlanId, db: &Database) -> Result<bool, AppError> { |
| 176 | let mut result = db | 199 | let mut result = db |
| 177 | .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") | 200 | .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") |
| @@ -198,15 +221,6 @@ impl FeePlanAssignment { | |||
| 198 | } | 221 | } |
| 199 | } | 222 | } |
| 200 | 223 | ||
| 201 | -/// Did this `CREATE` fail *only* because the row is already there? Same typed | ||
| 202 | -/// match, and the same reasoning, as the ledger's. | ||
| 203 | -fn is_duplicate_record(error: &surrealdb::Error) -> bool { | ||
| 204 | - matches!( | ||
| 205 | - error.already_exists_details(), | ||
| 206 | - Some(AlreadyExistsError::Record { .. }) | ||
| 207 | - ) | ||
| 208 | -} | ||
| 209 | - | ||
| 210 | #[cfg(test)] | 224 | #[cfg(test)] |
| 211 | mod tests { | 225 | mod tests { |
| 212 | use super::*; | 226 | use super::*; |
| @@ -275,4 +289,214 @@ mod tests { | |||
| 275 | .unwrap() | 289 | .unwrap() |
| 276 | ); | 290 | ); |
| 277 | } | 291 | } |
| 292 | + | ||
| 293 | + /// The race the refcount exists for: an edit and an assign, both licensed | ||
| 294 | + /// by the same instant. | ||
| 295 | + /// | ||
| 296 | + /// "Neither lands" is *not* the invariant β the two are legal in one order | ||
| 297 | + /// (edit, then assign the edited plan) and illegal in the other. What may | ||
| 298 | + /// never happen is the money and the plan disagreeing: the charges raised | ||
| 299 | + /// must be copies of the schedule the plan actually ends up carrying, and | ||
| 300 | + /// once anybody is on the plan no further edit or delete may land at all. | ||
| 301 | + /// | ||
| 302 | + /// Asserted against the **stored** state, never against which call returned | ||
| 303 | + /// `Ok`: a winner's word is not evidence about what the store kept. | ||
| 304 | + /// The one thing the *returned* values are good for is the second | ||
| 305 | + /// invariant: neither racer may answer 500. Losing a single-record round to | ||
| 306 | + /// a rival is the ordinary way this guard works, and the loser's recovery is | ||
| 307 | + /// to re-send, not to fail the request. | ||
| 308 | + /// | ||
| 309 | + /// Multi-threaded on purpose: on the single-threaded runtime the two tasks | ||
| 310 | + /// interleave only at await points and the store never reports a conflict at | ||
| 311 | + /// all, which is how a version of this test watched a 45-in-50 500 rate and | ||
| 312 | + /// passed. | ||
| 313 | + /// | ||
| 314 | + /// Real server, and `#[ignore]`d rather than falling back to `init_mem`: | ||
| 315 | + /// the embedded engine drops one of two concurrent writes to a record and | ||
| 316 | + /// answers `Ok` to both, which fails this very assertion out of nowhere | ||
| 317 | + /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in | ||
| 318 | + /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. | ||
| 319 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 320 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 321 | + async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { | ||
| 322 | + let db = crate::database::init_test_server("edit_race").await; | ||
| 323 | + let mut reached = 0; | ||
| 324 | + for round in 0..20 { | ||
| 325 | + let manager = UserId::from_key("mgr1"); | ||
| 326 | + let student = UserId::from_key(&format!("stu{round}")); | ||
| 327 | + let plan = FeePlan::create( | ||
| 328 | + FeePlanName::try_new("Yearly").unwrap(), | ||
| 329 | + vec![Installment::new( | ||
| 330 | + LedgerAmount::try_new(100).unwrap(), | ||
| 331 | + Timestamp::from_millis(1_000), | ||
| 332 | + )], | ||
| 333 | + &manager, | ||
| 334 | + &db, | ||
| 335 | + ) | ||
| 336 | + .await | ||
| 337 | + .unwrap(); | ||
| 338 | + | ||
| 339 | + let edit = { | ||
| 340 | + let (plan, db) = (plan.clone(), db.clone()); | ||
| 341 | + tokio::spawn(async move { | ||
| 342 | + plan.update( | ||
| 343 | + None, | ||
| 344 | + Some(vec![Installment::new( | ||
| 345 | + LedgerAmount::try_new(999).unwrap(), | ||
| 346 | + Timestamp::from_millis(2_000), | ||
| 347 | + )]), | ||
| 348 | + &db, | ||
| 349 | + ) | ||
| 350 | + .await | ||
| 351 | + }) | ||
| 352 | + }; | ||
| 353 | + let assign = { | ||
| 354 | + let (plan, db, manager, student) = | ||
| 355 | + (plan.clone(), db.clone(), manager.clone(), student.clone()); | ||
| 356 | + tokio::spawn(async move { | ||
| 357 | + FeePlanAssignment::assign(&plan, &student, &manager, &db).await | ||
| 358 | + }) | ||
| 359 | + }; | ||
| 360 | + let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap()); | ||
| 361 | + assert!( | ||
| 362 | + !matches!(edit, Err(AppError::Db(_))), | ||
| 363 | + "a raced edit must be refused, not 500: {edit:?}" | ||
| 364 | + ); | ||
| 365 | + assert!( | ||
| 366 | + !matches!(assign, Err(AppError::Db(_))), | ||
| 367 | + "a raced assign must retry, not 500: {assign:?}" | ||
| 368 | + ); | ||
| 369 | + | ||
| 370 | + let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); | ||
| 371 | + let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) | ||
| 372 | + .await | ||
| 373 | + .unwrap(); | ||
| 374 | + if assigned { | ||
| 375 | + reached += 1; | ||
| 376 | + // The counter is what refuses every later edit, so it has to | ||
| 377 | + // agree with the rows it stands for. | ||
| 378 | + let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | ||
| 379 | + .await | ||
| 380 | + .unwrap(); | ||
| 381 | + assert_eq!(lines.len(), 1, "one installment, one charge"); | ||
| 382 | + assert_eq!( | ||
| 383 | + lines[0].get_amount_minor().as_minor(), | ||
| 384 | + stored.get_installments()[0].get_amount_minor().as_minor(), | ||
| 385 | + "the charge must be a copy of the plan as it now stands" | ||
| 386 | + ); | ||
| 387 | + assert!( | ||
| 388 | + plan.clone().update(None, None, &db).await.is_ok(), | ||
| 389 | + "an empty PATCH writes nothing, so it is not refused" | ||
| 390 | + ); | ||
| 391 | + assert!( | ||
| 392 | + matches!( | ||
| 393 | + plan.clone() | ||
| 394 | + .update(Some(FeePlanName::try_new("Nope").unwrap()), None, &db) | ||
| 395 | + .await, | ||
| 396 | + Err(AppError::Conflict(_)) | ||
| 397 | + ), | ||
| 398 | + "an assigned plan stays frozen afterwards" | ||
| 399 | + ); | ||
| 400 | + assert!( | ||
| 401 | + !plan.clone().delete(&db).await.unwrap(), | ||
| 402 | + "and it cannot be deleted either" | ||
| 403 | + ); | ||
| 404 | + } | ||
| 405 | + } | ||
| 406 | + // Every assertion above sits behind "the assign landed", so a run where | ||
| 407 | + // it never did asserts nothing at all β the failure this counter turns | ||
| 408 | + // into a loud one. | ||
| 409 | + assert!(reached > 0, "no round ever placed the assignment"); | ||
| 410 | + } | ||
| 411 | + | ||
| 412 | + /// The other half, and here "never both" *is* the invariant: a delete and | ||
| 413 | + /// an assign racing must never leave a live assignment β with the charges | ||
| 414 | + /// it billed β pointing at a plan that is gone. Stored state again, and a | ||
| 415 | + /// real server again, for the same reasons. | ||
| 416 | + /// | ||
| 417 | + /// Both orderings are forced, because the interesting one does not happen on | ||
| 418 | + /// its own: with both racers released together the assign wins ~24 rounds in | ||
| 419 | + /// 25, so a run that only ever saw that ordering never tested a delete | ||
| 420 | + /// landing first at all. Half the rounds therefore hold the assign back by a | ||
| 421 | + /// beat, and the two counters below fail the test if either ordering went | ||
| 422 | + /// unseen. Neither racer may answer 500 here either β this is the pair that | ||
| 423 | + /// contends hardest, both writing the plan record itself. | ||
| 424 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 425 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 426 | + async fn a_delete_racing_an_assign_never_orphans_an_assignment() { | ||
| 427 | + let db = crate::database::init_test_server("delete_race").await; | ||
| 428 | + let (mut deleted_first, mut assigned_first) = (0, 0); | ||
| 429 | + for round in 0..20 { | ||
| 430 | + let hold_back_the_assign = round % 2 == 0; | ||
| 431 | + let manager = UserId::from_key("mgr1"); | ||
| 432 | + let student = UserId::from_key(&format!("stu{round}")); | ||
| 433 | + let plan = FeePlan::create( | ||
| 434 | + FeePlanName::try_new("Yearly").unwrap(), | ||
| 435 | + vec![Installment::new( | ||
| 436 | + LedgerAmount::try_new(100).unwrap(), | ||
| 437 | + Timestamp::from_millis(1_000), | ||
| 438 | + )], | ||
| 439 | + &manager, | ||
| 440 | + &db, | ||
| 441 | + ) | ||
| 442 | + .await | ||
| 443 | + .unwrap(); | ||
| 444 | + | ||
| 445 | + let head_start = std::time::Duration::from_millis(5); | ||
| 446 | + let drop_it = { | ||
| 447 | + let (plan, db) = (plan.clone(), db.clone()); | ||
| 448 | + tokio::spawn(async move { | ||
| 449 | + if !hold_back_the_assign { | ||
| 450 | + tokio::time::sleep(head_start).await; | ||
| 451 | + } | ||
| 452 | + plan.delete(&db).await | ||
| 453 | + }) | ||
| 454 | + }; | ||
| 455 | + let assign = { | ||
| 456 | + let (plan, db, manager, student) = | ||
| 457 | + (plan.clone(), db.clone(), manager.clone(), student.clone()); | ||
| 458 | + tokio::spawn(async move { | ||
| 459 | + if hold_back_the_assign { | ||
| 460 | + tokio::time::sleep(head_start).await; | ||
| 461 | + } | ||
| 462 | + FeePlanAssignment::assign(&plan, &student, &manager, &db).await | ||
| 463 | + }) | ||
| 464 | + }; | ||
| 465 | + let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap()); | ||
| 466 | + assert!( | ||
| 467 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 468 | + "a raced delete must retry, not 500: {drop_it:?}" | ||
| 469 | + ); | ||
| 470 | + assert!( | ||
| 471 | + !matches!(assign, Err(AppError::Db(_))), | ||
| 472 | + "a raced assign must retry, not 500: {assign:?}" | ||
| 473 | + ); | ||
| 474 | + | ||
| 475 | + let gone = FeePlan::read(plan.get_id(), &db).await.unwrap().is_none(); | ||
| 476 | + let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) | ||
| 477 | + .await | ||
| 478 | + .unwrap(); | ||
| 479 | + deleted_first += usize::from(gone); | ||
| 480 | + assigned_first += usize::from(assigned); | ||
| 481 | + assert!( | ||
| 482 | + !(gone && assigned), | ||
| 483 | + "an assignment may not outlive the plan it names" | ||
| 484 | + ); | ||
| 485 | + let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | ||
| 486 | + .await | ||
| 487 | + .unwrap(); | ||
| 488 | + assert!( | ||
| 489 | + !(gone && !lines.is_empty()), | ||
| 490 | + "and neither may the charges it raised" | ||
| 491 | + ); | ||
| 492 | + } | ||
| 493 | + // The premise, not a nicety: "never both" is trivially true in a run | ||
| 494 | + // where one of the two never landed, so a run that only saw one | ||
| 495 | + // ordering has proven nothing and says so. | ||
| 496 | + assert!(deleted_first > 0, "no round ever let the delete land first"); | ||
| 497 | + assert!( | ||
| 498 | + assigned_first > 0, | ||
| 499 | + "no round ever let the assign land first" | ||
| 500 | + ); | ||
| 501 | + } | ||
| 278 | } | 502 | } |
src/domain/field_update.rsmodified+46 -14
| @@ -24,7 +24,7 @@ | |||
| 24 | 24 | ||
| 25 | use surrealdb::types::{RecordId, SurrealValue, Value}; | 25 | use surrealdb::types::{RecordId, SurrealValue, Value}; |
| 26 | 26 | ||
| 27 | -use crate::database::Database; | 27 | +use crate::database::{Database, write_with_retry}; |
| 28 | use crate::error::AppError; | 28 | use crate::error::AppError; |
| 29 | 29 | ||
| 30 | pub struct FieldUpdate { | 30 | pub struct FieldUpdate { |
| @@ -34,6 +34,8 @@ pub struct FieldUpdate { | |||
| 34 | bindings: Vec<(String, Value)>, | 34 | bindings: Vec<(String, Value)>, |
| 35 | /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. | 35 | /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. |
| 36 | ordered: Option<(&'static str, &'static str, AppError)>, | 36 | ordered: Option<(&'static str, &'static str, AppError)>, |
| 37 | + /// `(condition, refusal)` for [`FieldUpdate::guard`]. | ||
| 38 | + guard: Option<(&'static str, AppError)>, | ||
| 37 | } | 39 | } |
| 38 | 40 | ||
| 39 | impl FieldUpdate { | 41 | impl FieldUpdate { |
| @@ -43,6 +45,7 @@ impl FieldUpdate { | |||
| 43 | assignments: Vec::new(), | 45 | assignments: Vec::new(), |
| 44 | bindings: Vec::new(), | 46 | bindings: Vec::new(), |
| 45 | ordered: None, | 47 | ordered: None, |
| 48 | + guard: None, | ||
| 46 | } | 49 | } |
| 47 | } | 50 | } |
| 48 | 51 | ||
| @@ -77,6 +80,23 @@ impl FieldUpdate { | |||
| 77 | self | 80 | self |
| 78 | } | 81 | } |
| 79 | 82 | ||
| 83 | + /// Refuse the write unless `condition` β a predicate on this same row β | ||
| 84 | + /// still holds at write time. The [`FieldUpdate::ordered`] guard for a | ||
| 85 | + /// precondition that is not about a range: a handler that read "nothing | ||
| 86 | + /// references this yet" re-asks the database at the instant it writes, so a | ||
| 87 | + /// reference landing in between refuses the edit instead of being edited | ||
| 88 | + /// out from under. `condition` is always an in-crate SQL literal, never | ||
| 89 | + /// user input. | ||
| 90 | + /// | ||
| 91 | + /// A request that carries no field at all emits no `UPDATE`, so it is not | ||
| 92 | + /// refused: it writes nothing, and reading the row back is a truthful | ||
| 93 | + /// answer to a PATCH that asked for no change. | ||
| 94 | + #[must_use] | ||
| 95 | + pub fn guard(mut self, condition: &'static str, refused: AppError) -> Self { | ||
| 96 | + self.guard = Some((condition, refused)); | ||
| 97 | + self | ||
| 98 | + } | ||
| 99 | + | ||
| 80 | /// Run the update and return the stored row. An empty request writes | 100 | /// Run the update and return the stored row. An empty request writes |
| 81 | /// nothing at all and reads the row back unchanged. | 101 | /// nothing at all and reads the row back unchanged. |
| 82 | pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> { | 102 | pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> { |
| @@ -84,7 +104,7 @@ impl FieldUpdate { | |||
| 84 | let row: Option<T> = db.select(self.id).await?; | 104 | let row: Option<T> = db.select(self.id).await?; |
| 85 | return row.ok_or(AppError::NotFound); | 105 | return row.ok_or(AppError::NotFound); |
| 86 | } | 106 | } |
| 87 | - let (guard, mut refused) = match self.ordered.take() { | 107 | + let (ordered, mut refused) = match self.ordered.take() { |
| 88 | // Both ends stored: name the bound variable for an end this request | 108 | // Both ends stored: name the bound variable for an end this request |
| 89 | // set, the column for one it left alone. | 109 | // set, the column for one it left alone. |
| 90 | Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { | 110 | Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { |
| @@ -98,26 +118,38 @@ impl FieldUpdate { | |||
| 98 | let low = side(low, self.is_set(low)); | 118 | let low = side(low, self.is_set(low)); |
| 99 | let high = side(high, self.is_set(high)); | 119 | let high = side(high, self.is_set(high)); |
| 100 | ( | 120 | ( |
| 101 | - format!(" WHERE ({low} = NONE OR {high} = NONE OR {low} <= {high})"), | 121 | + Some(format!( |
| 122 | + "({low} = NONE OR {high} = NONE OR {low} <= {high})" | ||
| 123 | + )), | ||
| 102 | Some(err), | 124 | Some(err), |
| 103 | ) | 125 | ) |
| 104 | } | 126 | } |
| 105 | - _ => (String::new(), None), | 127 | + _ => (None, None), |
| 128 | + }; | ||
| 129 | + // Both guards land on the one `UPDATE`, ANDed. No caller sets both, so | ||
| 130 | + // the refusal is whichever one is there. | ||
| 131 | + let (extra, extra_refused) = match self.guard.take() { | ||
| 132 | + Some((condition, err)) => (Some(condition.to_string()), Some(err)), | ||
| 133 | + None => (None, None), | ||
| 134 | + }; | ||
| 135 | + refused = refused.or(extra_refused); | ||
| 136 | + let conditions: Vec<String> = ordered.into_iter().chain(extra).collect(); | ||
| 137 | + let guard = if conditions.is_empty() { | ||
| 138 | + String::new() | ||
| 139 | + } else { | ||
| 140 | + format!(" WHERE {}", conditions.join(" AND ")) | ||
| 106 | }; | 141 | }; |
| 107 | let sets = self.assignments.join(", "); | 142 | let sets = self.assignments.join(", "); |
| 108 | - let mut query = db | 143 | + let sql = format!("UPDATE $id SET {sets}{guard} RETURN AFTER"); |
| 109 | - .query(format!("UPDATE $id SET {sets}{guard} RETURN AFTER")) | 144 | + self.bindings.push(("id".into(), self.id.into_value())); |
| 110 | - .bind(("id", self.id)); | 145 | + // Retried on a write conflict: a guarded PATCH contends on the very row |
| 111 | - for (name, value) in self.bindings { | 146 | + // its guard reads, and the loser wrote nothing, so re-sending it is the |
| 112 | - query = query.bind((name, value)); | 147 | + // recovery β see [`write_with_retry`]. |
| 113 | - } | 148 | + let rows: Vec<T> = write_with_retry(db, &sql, &self.bindings).await?; |
| 114 | - let mut result = query.await?.check()?; | ||
| 115 | // No row back means the guard bit (or, in the window after the handler's | 149 | // No row back means the guard bit (or, in the window after the handler's |
| 116 | // read, the row was deleted β the guard cannot tell the two apart, and | 150 | // read, the row was deleted β the guard cannot tell the two apart, and |
| 117 | // reports the refusal it was given). | 151 | // reports the refusal it was given). |
| 118 | - result | 152 | + rows.into_iter() |
| 119 | - .take::<Vec<T>>(0)? | ||
| 120 | - .into_iter() | ||
| 121 | .next() | 153 | .next() |
| 122 | .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) | 154 | .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) |
| 123 | } | 155 | } |
src/lib.rsmodified+1 -1
| @@ -58,7 +58,7 @@ use crate::state::AppState; | |||
| 58 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 58 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 59 | (name = "exams", description = "Exams (per course, weighted by their kind β see `settings`): results, sync/async/open scheduling, attempts (students only β staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, β€ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β no `mode`, or `open` β drop out); without it the list stays newest-first"), | 59 | (name = "exams", description = "Exams (per course, weighted by their kind β see `settings`): results, sync/async/open scheduling, attempts (students only β staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, β€ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β no `mode`, or `open` β drop out); without it the list stays newest-first"), |
| 60 | (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruΕ) as an integer β this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β own always, otherwise teacher+ or a parent link β and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β inside that window neither booking nor cancelling lands (`409`) β measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), | 60 | (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruΕ) as an integer β this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β own always, otherwise teacher+ or a parent link β and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β inside that window neither booking nor cancelling lands (`409`) β measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), |
| 61 | - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruΕ) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, β¦}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1β64 characters β no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β that cap is a cross-record sum, which the database cannot enforce on its own β it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", β¦). Every write here is **manager+** β teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope β the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β all folded from the raw lines on every request and stored nowhere"), | 61 | + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruΕ) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it β so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, β¦}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1β64 characters β no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β that cap is a cross-record sum, which the database cannot enforce on its own β it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", β¦). Every write here is **manager+** β teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope β the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β all folded from the raw lines on every request and stored nowhere"), |
| 62 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 62 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 63 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β those marks would silently re-weight. Also the food program: the meal slots menus are published for β each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), | 63 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β those marks would silently re-weight. Also the food program: the meal slots menus are published for β each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), |
| 64 | (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), | 64 | (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), |
src/migration_sql.rsmodified+26 -0
| @@ -651,6 +651,12 @@ pub const MIGRATION: &str = " | |||
| 651 | DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int; | 651 | DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int; |
| 652 | DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record<user> READONLY; | 652 | DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record<user> READONLY; |
| 653 | DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY; | 653 | DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY; |
| 654 | + -- How many students are on the plan. The edit and delete guards read it, | ||
| 655 | + -- an assignment's own transaction increments it, and nothing decrements it | ||
| 656 | + -- (assignments are never removed). `option<int>` and no DEFAULT, like every | ||
| 657 | + -- other counter: no Rust struct carries it, so the plan's create must not | ||
| 658 | + -- be expected to state it. | ||
| 659 | + DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option<int>; | ||
| 654 | 660 | ||
| 655 | -- One plan on one student, keyed `<plan>_<student>`: assigning twice is the | 661 | -- One plan on one student, keyed `<plan>_<student>`: assigning twice is the |
| 656 | -- same record id, so a replay writes nothing and an assignment cut short | 662 | -- same record id, so a replay writes nothing and an assignment cut short |
| @@ -947,6 +953,26 @@ pub const BACKFILL: &str = " | |||
| 947 | FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) { | 953 | FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) { |
| 948 | UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE; | 954 | UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE; |
| 949 | }; | 955 | }; |
| 956 | + | ||
| 957 | + -- The fee-plan guard became a refcount (2026-07-30): editing or deleting a | ||
| 958 | + -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row | ||
| 959 | + -- itself, instead of by a scan a concurrent assign could land behind. | ||
| 960 | + -- | ||
| 961 | + -- This seeding is what keeps a *stale* volume safe: a plan written by an | ||
| 962 | + -- older binary carries no counter, an absent counter reads as zero, and a | ||
| 963 | + -- zero would make an already-assigned plan editable and deletable again β | ||
| 964 | + -- the exact thing the 409 exists to prevent. Boot seeds it from the | ||
| 965 | + -- assignment rows that actually exist, and `migrate` runs to completion | ||
| 966 | + -- before the router is bound, so no request is ever served against the | ||
| 967 | + -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes | ||
| 968 | + -- nothing. | ||
| 969 | + -- | ||
| 970 | + -- No zero pass, for the same reason the subject counters get none: a plan | ||
| 971 | + -- nobody is on has no assignment rows, and absent already reads as zero in | ||
| 972 | + -- the guard β writing it would touch every plan row to say what it says. | ||
| 973 | + FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) { | ||
| 974 | + UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE; | ||
| 975 | + }; | ||
| 950 | "; | 976 | "; |
| 951 | 977 | ||
| 952 | /// The migration batches, in the order a boot applies them β and the *only* | 978 | /// The migration batches, in the order a boot applies them β and the *only* |
src/web/payments.rsmodified+28 -20
| @@ -247,6 +247,12 @@ async fn get_plan( | |||
| 247 | /// been assigned to anyone: those charges are frozen copies of the installments | 247 | /// been assigned to anyone: those charges are frozen copies of the installments |
| 248 | /// as they stood, so editing afterwards would leave the plan and the money | 248 | /// as they stood, so editing afterwards would leave the plan and the money |
| 249 | /// telling different stories. Write a new plan instead. | 249 | /// telling different stories. Write a new plan instead. |
| 250 | +/// | ||
| 251 | +/// The refusal is decided by the database as the edit is written, not by a | ||
| 252 | +/// read taken before it, so an assign arriving at the same instant cannot end | ||
| 253 | +/// up on either side of the edit: it either freezes the plan first (and this is | ||
| 254 | +/// a `409`) or bills the edited schedule. A PATCH carrying no field at all | ||
| 255 | +/// writes nothing and returns the plan unchanged, assigned or not. | ||
| 250 | #[utoipa::path( | 256 | #[utoipa::path( |
| 251 | patch, | 257 | patch, |
| 252 | path = "/plans/{id}", | 258 | path = "/plans/{id}", |
| @@ -270,7 +276,6 @@ async fn update_plan( | |||
| 270 | Json(req): Json<UpdateFeePlan>, | 276 | Json(req): Json<UpdateFeePlan>, |
| 271 | ) -> Result<Json<FeePlanResponse>, AppError> { | 277 | ) -> Result<Json<FeePlanResponse>, AppError> { |
| 272 | let plan = require_plan(&id, &st.db).await?; | 278 | let plan = require_plan(&id, &st.db).await?; |
| 273 | - ensure_unassigned(plan.get_id(), "an assigned plan cannot be edited", &st.db).await?; | ||
| 274 | let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?; | 279 | let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?; |
| 275 | let installments = req.installments.map(InstallmentBody::list).transpose()?; | 280 | let installments = req.installments.map(InstallmentBody::list).transpose()?; |
| 276 | let plan = plan.update(name, installments, &st.db).await?; | 281 | let plan = plan.update(name, installments, &st.db).await?; |
| @@ -282,7 +287,9 @@ async fn update_plan( | |||
| 282 | 287 | ||
| 283 | /// Delete a plan. Refused (`409`) once it has been assigned to anyone β the | 288 | /// Delete a plan. Refused (`409`) once it has been assigned to anyone β the |
| 284 | /// charges it raised name it, and a school's financial history keeps its | 289 | /// charges it raised name it, and a school's financial history keeps its |
| 285 | -/// references. | 290 | +/// references. Decided as the delete is written, the same way the edit is, so a |
| 291 | +/// simultaneous assign can never leave a live assignment pointing at a plan | ||
| 292 | +/// that is gone. | ||
| 286 | #[utoipa::path( | 293 | #[utoipa::path( |
| 287 | delete, | 294 | delete, |
| 288 | path = "/plans/{id}", | 295 | path = "/plans/{id}", |
| @@ -303,22 +310,10 @@ async fn delete_plan( | |||
| 303 | Path(id): Path<String>, | 310 | Path(id): Path<String>, |
| 304 | ) -> Result<StatusCode, AppError> { | 311 | ) -> Result<StatusCode, AppError> { |
| 305 | let plan = require_plan(&id, &st.db).await?; | 312 | let plan = require_plan(&id, &st.db).await?; |
| 306 | - ensure_unassigned(plan.get_id(), "an assigned plan cannot be deleted", &st.db).await?; | 313 | + if !plan.delete(&st.db).await? { |
| 307 | - plan.delete(&st.db).await?; | 314 | + return Err(AppError::Conflict("an assigned plan cannot be deleted")); |
| 308 | - Ok(StatusCode::NO_CONTENT) | ||
| 309 | -} | ||
| 310 | - | ||
| 311 | -/// The shared 409 guard behind editing and deleting a plan. A scan, and | ||
| 312 | -/// deliberately so β see [`FeePlan::has_assignments`] for the race it accepts. | ||
| 313 | -async fn ensure_unassigned( | ||
| 314 | - plan: &FeePlanId, | ||
| 315 | - reason: &'static str, | ||
| 316 | - db: &Database, | ||
| 317 | -) -> Result<(), AppError> { | ||
| 318 | - if FeePlan::has_assignments(plan, db).await? { | ||
| 319 | - return Err(AppError::Conflict(reason)); | ||
| 320 | } | 315 | } |
| 321 | - Ok(()) | 316 | + Ok(StatusCode::NO_CONTENT) |
| 322 | } | 317 | } |
| 323 | 318 | ||
| 324 | // ---- assignments ------------------------------------------------------------ | 319 | // ---- assignments ------------------------------------------------------------ |
| @@ -361,6 +356,13 @@ struct FeePlanAssignmentResponse { | |||
| 361 | /// Only students carry a fee record, so any other target is rejected. One bad | 356 | /// Only students carry a fee record, so any other target is rejected. One bad |
| 362 | /// id never loses the rest of the batch: the response reports each student | 357 | /// id never loses the rest of the batch: the response reports each student |
| 363 | /// separately. | 358 | /// separately. |
| 359 | +/// | ||
| 360 | +/// Placing the first student **freezes** the plan: it can no longer be edited | ||
| 361 | +/// or deleted. The installments billed are read back from the stored plan at | ||
| 362 | +/// that instant, so an edit that landed a moment earlier is the one billed, | ||
| 363 | +/// never the version this request first looked at. A plan deleted while the | ||
| 364 | +/// batch is running is `rejected` from that student on β a per-student outcome | ||
| 365 | +/// like any other, so the students it already billed stay in the report. | ||
| 364 | #[utoipa::path( | 366 | #[utoipa::path( |
| 365 | post, | 367 | post, |
| 366 | path = "/plans/{id}/assignments", | 368 | path = "/plans/{id}/assignments", |
| @@ -398,9 +400,15 @@ async fn assign_plan( | |||
| 398 | .await? | 400 | .await? |
| 399 | .is_some_and(|user| user.get_role() == Role::Student); | 401 | .is_some_and(|user| user.get_role() == Role::Student); |
| 400 | let (status, reason) = if is_student { | 402 | let (status, reason) = if is_student { |
| 401 | - match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await? { | 403 | + match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await { |
| 402 | - (_, true) => ("already_assigned", None), | 404 | + Ok((_, true)) => ("already_assigned", None), |
| 403 | - (_, false) => ("assigned", None), | 405 | + Ok((_, false)) => ("assigned", None), |
| 406 | + // The plan was deleted mid-batch. That is a per-student outcome | ||
| 407 | + // like any other, not a reason to throw away the report for the | ||
| 408 | + // students this batch already billed β their charges are | ||
| 409 | + // written and the caller has to be told about them. | ||
| 410 | + Err(AppError::NotFound) => ("rejected", Some("no such plan")), | ||
| 411 | + Err(err) => return Err(err), | ||
| 404 | } | 412 | } |
| 405 | } else { | 413 | } else { |
| 406 | ("rejected", Some("no such student")) | 414 | ("rejected", Some("no such student")) |
tests/limits_completeness.rsmodified+6 -0
| @@ -51,6 +51,12 @@ const EXCLUDED: &[(&str, &str)] = &[ | |||
| 51 | a grade freezes it in the database; the client sees the freeze as a 409, \ | 51 | a grade freezes it in the database; the client sees the freeze as a 409, \ |
| 52 | never as a number", | 52 | never as a number", |
| 53 | ), | 53 | ), |
| 54 | + ( | ||
| 55 | + "FEE_PLAN_UNASSIGNED_GUARD", | ||
| 56 | + "SQL fragment: the condition a fee plan's edit and delete carry so an \ | ||
| 57 | + assigned plan freezes in the database; the client sees the freeze as a \ | ||
| 58 | + 409, never as a number", | ||
| 59 | + ), | ||
| 54 | ( | 60 | ( |
| 55 | "UPLOAD_BODY_OVERHEAD_BYTES", | 61 | "UPLOAD_BODY_OVERHEAD_BYTES", |
| 56 | "multipart headroom over max_file_bytes; the client sizes against \ | 62 | "multipart headroom over max_file_bytes; the client sizes against \ |