Split meal_attendance, meal_ledger, menu, menu_dish, dietary_profile into domain/db/service layers
Browse files at this commitd5481204ffd92d42643485074f2096a4e5fd4e20Parent: 387eb31- chore
- split meal_attendance, meal_ledger, menu, menu_dish, dietary_profile into domain/db/service layers
22 changed files +1783 -1410
- src/db/dietary_profile.rs +73 -0
- src/db/exam_attempt.rs +1 -1
- src/db/meal_attendance.rs +114 -0
- src/db/meal_booking.rs +37 -34
- src/db/meal_ledger.rs +195 -0
- src/db/menu.rs +608 -0
- src/db/menu_dish.rs +175 -0
- src/db/mod.rs +5 -1
- src/domain/dietary_profile.rs +11 -71
- src/domain/meal_attendance.rs +11 -106
- src/domain/meal_ledger.rs +29 -303
- src/domain/menu.rs +21 -623
- src/domain/menu_dish.rs +14 -173
- src/service/dietary_profile.rs +32 -0
- src/service/meal_attendance.rs +49 -0
- src/service/meal_booking.rs +24 -20
- src/service/meal_ledger.rs +138 -0
- src/service/menu.rs +161 -0
- src/service/mod.rs +4 -1
- src/web/meals.rs +64 -63
- tests/integration.rs +8 -7
- tests/regress_meals.rs +9 -7
src/db/dietary_profile.rsadded+73 -0
| @@ -0,0 +1,73 @@ | |||
| 1 | +//! The `dietary_profile` table: one row per student (the record key *is* | ||
| 2 | +//! the student's key), created on first write and afterwards patched | ||
| 3 | +//! field-by-field. The tag/note newtypes and the pure tag intersection live | ||
| 4 | +//! in [`crate::domain::dietary_profile`]; the web layer reads through | ||
| 5 | +//! [`crate::service::dietary_profile`]. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::field_update::FieldUpdate; | ||
| 9 | +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags}; | ||
| 10 | +use crate::domain::timestamp::Timestamp; | ||
| 11 | +use crate::domain::user::UserId; | ||
| 12 | +use crate::error::AppError; | ||
| 13 | + | ||
| 14 | +/// One student's profile, or `None` while the school never recorded one. | ||
| 15 | +/// A single `SELECT` by record id — this is what a menu read joins on. | ||
| 16 | +pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> { | ||
| 17 | + Ok(db.select(DietaryProfileId::of(student).record()).await?) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// The tags a menu read matches its dishes against: the caller's, or an | ||
| 21 | +/// empty list when they have no profile (every manager, every teacher). | ||
| 22 | +pub async fn tags_of(db: &Database, student: &UserId) -> Result<Vec<String>, AppError> { | ||
| 23 | + Ok(read(db, student) | ||
| 24 | + .await? | ||
| 25 | + .map(|profile| profile.get_tags().as_slice().to_vec()) | ||
| 26 | + .unwrap_or_default()) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Write the fields the PATCH carried. Creates the row on first write; | ||
| 30 | +/// afterwards only the named fields move, because `student` is `READONLY` | ||
| 31 | +/// and a whole-row save would also revert a concurrent edit of the other | ||
| 32 | +/// field (see [`FieldUpdate`]). | ||
| 33 | +pub async fn save( | ||
| 34 | + db: &Database, | ||
| 35 | + student: &UserId, | ||
| 36 | + tags: Option<DietaryTags>, | ||
| 37 | + note: Option<Option<DietaryNote>>, | ||
| 38 | + by: &UserId, | ||
| 39 | +) -> Result<DietaryProfile, AppError> { | ||
| 40 | + if read(db, student).await?.is_none() { | ||
| 41 | + let profile = DietaryProfile { | ||
| 42 | + id: DietaryProfileId::of(student), | ||
| 43 | + student: student.clone(), | ||
| 44 | + tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), | ||
| 45 | + note: note.clone().flatten(), | ||
| 46 | + updated_by: by.clone(), | ||
| 47 | + updated_at: Timestamp::now(), | ||
| 48 | + }; | ||
| 49 | + match db.create(profile.id.record()).content(profile).await { | ||
| 50 | + Ok(Some(created)) => return Ok(created), | ||
| 51 | + Ok(None) => { | ||
| 52 | + return Err(AppError::Internal("failed to save the profile".into())); | ||
| 53 | + } | ||
| 54 | + // A rival first `PATCH` created the row in the round trip since | ||
| 55 | + // the read above (the `dietary_profile_student` UNIQUE index | ||
| 56 | + // catches the same collision), and `CREATE` leaves that row | ||
| 57 | + // untouched — so this call is a plain field write after all, | ||
| 58 | + // exactly as it would have been a moment later. Propagated, it | ||
| 59 | + // was a 500 on a legitimate request. Same shape as | ||
| 60 | + // [`crate::db::meal_ledger::append`], which | ||
| 61 | + // reads the winner back rather than failing. | ||
| 62 | + Err(err) if err.is_already_exists() => {} | ||
| 63 | + Err(err) => return Err(err.into()), | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + FieldUpdate::new(DietaryProfileId::of(student).record()) | ||
| 67 | + .set("tags", tags) | ||
| 68 | + .set("note", note) | ||
| 69 | + .set("updated_by", Some(by.clone())) | ||
| 70 | + .set("updated_at", Some(Timestamp::now())) | ||
| 71 | + .run::<DietaryProfile>(db) | ||
| 72 | + .await | ||
| 73 | +} | ||
src/db/exam_attempt.rsmodified+1 -1
| @@ -172,7 +172,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError | |||
| 172 | /// with neither caller told anything. Writing a key the delete also writes | 172 | /// with neither caller told anything. Writing a key the delete also writes |
| 173 | /// makes the two collide and the store refuses one side. It is the shape | 173 | /// makes the two collide and the store refuses one side. It is the shape |
| 174 | /// [`crate::domain::exam_answer::ExamAnswer::save`] and | 174 | /// [`crate::domain::exam_answer::ExamAnswer::save`] and |
| 175 | -/// [`crate::domain::menu::bump_menu_and_write`] already use. | 175 | +/// [`crate::db::menu::bump_menu_and_write`] already use. |
| 176 | /// | 176 | /// |
| 177 | /// An orphan here is not merely untidy: an `exam_question` that outlives | 177 | /// An orphan here is not merely untidy: an `exam_question` that outlives |
| 178 | /// its exam keeps the reference it claimed on its subject (the cascade's | 178 | /// its exam keeps the reference it claimed on its subject (the cascade's |
src/db/meal_attendance.rsadded+114 -0
| @@ -0,0 +1,114 @@ | |||
| 1 | +//! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per | ||
| 2 | +//! (menu, student) that rides the menu's revision bump | ||
| 3 | +//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the | ||
| 4 | +//! two listings. Attendance is reporting only: nothing here writes the | ||
| 5 | +//! ledger, and the workflows that read it live in the web layer via | ||
| 6 | +//! [`crate::service::meal_attendance`]. | ||
| 7 | + | ||
| 8 | +use surrealdb::types::SurrealValue; | ||
| 9 | + | ||
| 10 | +use crate::database::Database; | ||
| 11 | +use crate::db::menu::bump_menu_and_write; | ||
| 12 | +use crate::db::page::PagedList; | ||
| 13 | +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; | ||
| 14 | +use crate::domain::menu::MenuDate; | ||
| 15 | +use crate::domain::menu::MenuId; | ||
| 16 | +use crate::domain::timestamp::Timestamp; | ||
| 17 | +use crate::domain::user::UserId; | ||
| 18 | +use crate::error::AppError; | ||
| 19 | + | ||
| 20 | +/// Record (or overwrite) whether `student` ate off `menu`. One row per | ||
| 21 | +/// pair by construction, so a correction is the same UPSERT flipping the | ||
| 22 | +/// status. No ledger line, ever — see the domain module header. | ||
| 23 | +/// | ||
| 24 | +/// `NotFound` = the menu is gone, and the mark was *not* written. The mark | ||
| 25 | +/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to | ||
| 26 | +/// the menu row rather than a read the write then trusts: a delete racing | ||
| 27 | +/// this one touches the very key this transaction bumps, and the store | ||
| 28 | +/// refuses to commit both. Guarding by reading the menu — even as the | ||
| 29 | +/// `UPSERT`'s own target — did not survive that race: the read saw a row | ||
| 30 | +/// [`crate::db::menu::delete`] had deleted but not | ||
| 31 | +/// yet committed, its sweep ran on a snapshot predating this insert, and the | ||
| 32 | +/// mark outlived its menu with neither caller told anything (measured 378 of | ||
| 33 | +/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, | ||
| 34 | +/// republishing that day and slot then resurrected it as a mark on the new | ||
| 35 | +/// menu. | ||
| 36 | +/// | ||
| 37 | +/// The bump costs a booking in flight one re-read (its seat claim asserts | ||
| 38 | +/// the revision it priced against) — the same tax every dish write already | ||
| 39 | +/// levies, and it lands after the cutoff on a meal being served, where | ||
| 40 | +/// bookings are rare. | ||
| 41 | +pub async fn mark( | ||
| 42 | + db: &Database, | ||
| 43 | + menu: &MenuId, | ||
| 44 | + student: &UserId, | ||
| 45 | + status: MealAttendanceStatus, | ||
| 46 | + marked_by: &UserId, | ||
| 47 | +) -> Result<MealAttendance, AppError> { | ||
| 48 | + let row = MealAttendance { | ||
| 49 | + id: MealAttendanceId::composite(menu, student), | ||
| 50 | + menu: menu.clone(), | ||
| 51 | + student: student.clone(), | ||
| 52 | + status, | ||
| 53 | + marked_by: marked_by.clone(), | ||
| 54 | + marked_at: Timestamp::now(), | ||
| 55 | + }; | ||
| 56 | + // Admissible for the retry loop inside: the id is bijective with the | ||
| 57 | + // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` | ||
| 58 | + // resolves onto the row that index already points at instead of | ||
| 59 | + // colliding with it — it can never answer "already exists", and a | ||
| 60 | + // re-sent round writes the identical row. | ||
| 61 | + bump_menu_and_write( | ||
| 62 | + menu, | ||
| 63 | + "UPSERT $id CONTENT $row RETURN AFTER", | ||
| 64 | + vec![ | ||
| 65 | + ("id".into(), row.id.record().into_value()), | ||
| 66 | + ("row".into(), row.into_value()), | ||
| 67 | + ], | ||
| 68 | + db, | ||
| 69 | + ) | ||
| 70 | + .await? | ||
| 71 | + .ok_or_else(|| AppError::Internal("failed to record the mark".into())) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// The kitchen's list for one menu. | ||
| 75 | +pub async fn list_for_menu( | ||
| 76 | + db: &Database, | ||
| 77 | + menu: &MenuId, | ||
| 78 | + limit: Option<i64>, | ||
| 79 | + offset: i64, | ||
| 80 | +) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 81 | + PagedList::new( | ||
| 82 | + "meal_attendance WHERE menu = $menu", | ||
| 83 | + "ORDER BY marked_at DESC, id DESC", | ||
| 84 | + ) | ||
| 85 | + .bind("menu", menu.record()) | ||
| 86 | + .run(limit, offset, db) | ||
| 87 | + .await | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// One student's marks, newest first. `from`/`to` are inclusive | ||
| 91 | +/// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, | ||
| 92 | +/// which is chronological for that format (see [`MenuDate`]), and the link | ||
| 93 | +/// is followed rather than denormalized so a row can never disagree with | ||
| 94 | +/// the menu it belongs to. | ||
| 95 | +pub async fn list_for_student( | ||
| 96 | + db: &Database, | ||
| 97 | + student: &UserId, | ||
| 98 | + from: Option<&MenuDate>, | ||
| 99 | + to: Option<&MenuDate>, | ||
| 100 | + limit: Option<i64>, | ||
| 101 | + offset: i64, | ||
| 102 | +) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 103 | + PagedList::new( | ||
| 104 | + "meal_attendance WHERE student = $usr \ | ||
| 105 | + AND ($from = NONE OR menu.date >= $from) \ | ||
| 106 | + AND ($to = NONE OR menu.date <= $to)", | ||
| 107 | + "ORDER BY marked_at DESC, id DESC", | ||
| 108 | + ) | ||
| 109 | + .bind("usr", student.record()) | ||
| 110 | + .bind("from", from.map(|date| date.as_str().to_string())) | ||
| 111 | + .bind("to", to.map(|date| date.as_str().to_string())) | ||
| 112 | + .run(limit, offset, db) | ||
| 113 | + .await | ||
| 114 | +} | ||
src/db/meal_booking.rsmodified+37 -34
| @@ -306,8 +306,11 @@ mod tests { | |||
| 306 | use super::*; | 306 | use super::*; |
| 307 | use crate::database::init_mem; | 307 | use crate::database::init_mem; |
| 308 | use crate::db::cap; | 308 | use crate::db::cap; |
| 309 | + use crate::db::meal_ledger; | ||
| 310 | + use crate::db::menu; | ||
| 311 | + use crate::db::menu_dish; | ||
| 309 | use crate::domain::meal_booking::{MealBookingStatus, MealCutoff}; | 312 | use crate::domain::meal_booking::{MealBookingStatus, MealCutoff}; |
| 310 | - use crate::domain::menu::{Menu, MenuDate, MenuSlot}; | 313 | + use crate::domain::menu::{MenuDate, MenuSlot}; |
| 311 | use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; | 314 | use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; |
| 312 | use crate::domain::settings::MealSlotDef; | 315 | use crate::domain::settings::MealSlotDef; |
| 313 | use crate::service::meal_booking; | 316 | use crate::service::meal_booking; |
| @@ -322,12 +325,12 @@ mod tests { | |||
| 322 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { | 325 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { |
| 323 | let db = init_mem().await.unwrap(); | 326 | let db = init_mem().await.unwrap(); |
| 324 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; | 327 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; |
| 325 | - let menu = Menu::create( | 328 | + let menu = menu::create( |
| 329 | + &db, | ||
| 326 | MenuDate::try_new(date).unwrap(), | 330 | MenuDate::try_new(date).unwrap(), |
| 327 | MenuSlot::try_new("lunch", &slots).unwrap(), | 331 | MenuSlot::try_new("lunch", &slots).unwrap(), |
| 328 | capacity, | 332 | capacity, |
| 329 | &UserId::generate(), | 333 | &UserId::generate(), |
| 330 | - &db, | ||
| 331 | ) | 334 | ) |
| 332 | .await | 335 | .await |
| 333 | .unwrap(); | 336 | .unwrap(); |
| @@ -354,13 +357,13 @@ mod tests { | |||
| 354 | } | 357 | } |
| 355 | 358 | ||
| 356 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { | 359 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { |
| 357 | - MenuDish::create( | 360 | + menu_dish::create( |
| 361 | + db, | ||
| 358 | menu, | 362 | menu, |
| 359 | DishName::try_new("çorba").unwrap(), | 363 | DishName::try_new("çorba").unwrap(), |
| 360 | None, | 364 | None, |
| 361 | DishPrice::try_new(price).unwrap(), | 365 | DishPrice::try_new(price).unwrap(), |
| 362 | DishTags::try_new(&[], &[]).unwrap(), | 366 | DishTags::try_new(&[], &[]).unwrap(), |
| 363 | - db, | ||
| 364 | ) | 367 | ) |
| 365 | .await | 368 | .await |
| 366 | .unwrap() | 369 | .unwrap() |
| @@ -374,7 +377,7 @@ mod tests { | |||
| 374 | async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { | 377 | async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { |
| 375 | let (db, menu) = menu(None).await; | 378 | let (db, menu) = menu(None).await; |
| 376 | let ali = UserId::generate(); | 379 | let ali = UserId::generate(); |
| 377 | - let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); | 380 | + let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| 378 | // A dish lands: the price a booking read a moment ago is now stale. | 381 | // A dish lands: the price a booking read a moment ago is now stale. |
| 379 | add_dish(&menu, 1_000, &db).await; | 382 | add_dish(&menu, 1_000, &db).await; |
| 380 | let row = MealBooking { | 383 | let row = MealBooking { |
| @@ -404,7 +407,7 @@ mod tests { | |||
| 404 | ); | 407 | ); |
| 405 | 408 | ||
| 406 | // Re-read, and the same seat is taken with the row it belongs to. | 409 | // Re-read, and the same seat is taken with the row it belongs to. |
| 407 | - let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); | 410 | + let now = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| 408 | assert!(now > seen); | 411 | assert!(now > seen); |
| 409 | assert!(matches!(place(now).await, Claimed::Made(_))); | 412 | assert!(matches!(place(now).await, Claimed::Made(_))); |
| 410 | assert_eq!(seats(&menu, &db).await, 1); | 413 | assert_eq!(seats(&menu, &db).await, 1); |
| @@ -426,7 +429,7 @@ mod tests { | |||
| 426 | let (db, id) = menu(None).await; | 429 | let (db, id) = menu(None).await; |
| 427 | let mut seen = 0; | 430 | let mut seen = 0; |
| 428 | let mut moved = async |db: &Database| { | 431 | let mut moved = async |db: &Database| { |
| 429 | - let now = Menu::read(&id, db).await.unwrap().unwrap().get_version(); | 432 | + let now = menu::read(db, &id).await.unwrap().unwrap().get_version(); |
| 430 | let stepped = now > seen; | 433 | let stepped = now > seen; |
| 431 | seen = now; | 434 | seen = now; |
| 432 | stepped | 435 | stepped |
| @@ -435,26 +438,26 @@ mod tests { | |||
| 435 | 438 | ||
| 436 | let dish = add_dish(&id, 1_000, &db).await; | 439 | let dish = add_dish(&id, 1_000, &db).await; |
| 437 | assert!(moved(&db).await, "a dish added"); | 440 | assert!(moved(&db).await, "a dish added"); |
| 438 | - let dish = dish | 441 | + let dish = menu_dish::update( |
| 439 | - .update( | 442 | + &db, |
| 440 | - None, | 443 | + dish, |
| 441 | - None, | 444 | + None, |
| 442 | - Some(DishPrice::try_new(2_000).unwrap()), | 445 | + None, |
| 443 | - None, | 446 | + Some(DishPrice::try_new(2_000).unwrap()), |
| 444 | - &db, | 447 | + None, |
| 445 | - ) | 448 | + ) |
| 446 | - .await | 449 | + .await |
| 447 | - .unwrap(); | 450 | + .unwrap(); |
| 448 | assert!(moved(&db).await, "a dish re-priced"); | 451 | assert!(moved(&db).await, "a dish re-priced"); |
| 449 | - dish.delete(&db).await.unwrap(); | 452 | + menu_dish::delete(&db, dish).await.unwrap(); |
| 450 | assert!(moved(&db).await, "a dish removed"); | 453 | assert!(moved(&db).await, "a dish removed"); |
| 451 | - Menu::read(&id, &db) | 454 | + menu::update( |
| 452 | - .await | 455 | + &db, |
| 453 | - .unwrap() | 456 | + menu::read(&db, &id).await.unwrap().unwrap(), |
| 454 | - .unwrap() | 457 | + Some(Some(5)), |
| 455 | - .update(Some(Some(5)), &db) | 458 | + ) |
| 456 | - .await | 459 | + .await |
| 457 | - .unwrap(); | 460 | + .unwrap(); |
| 458 | assert!(moved(&db).await, "the capacity moved"); | 461 | assert!(moved(&db).await, "the capacity moved"); |
| 459 | } | 462 | } |
| 460 | 463 | ||
| @@ -493,7 +496,7 @@ mod tests { | |||
| 493 | assert_eq!(stored.get_attempt(), live.get_attempt()); | 496 | assert_eq!(stored.get_attempt(), live.get_attempt()); |
| 494 | assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); | 497 | assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); |
| 495 | assert_eq!( | 498 | assert_eq!( |
| 496 | - MealLedger::balance_of(&ali, &db).await.unwrap(), | 499 | + meal_ledger::balance_of(&db, &ali).await.unwrap(), |
| 497 | -1_000, | 500 | -1_000, |
| 498 | "the live attempt's charge stands: it was never cancelled" | 501 | "the live attempt's charge stands: it was never cancelled" |
| 499 | ); | 502 | ); |
| @@ -530,7 +533,7 @@ mod tests { | |||
| 530 | assert_eq!(freed.get_status(), MealBookingStatus::Cancelled); | 533 | assert_eq!(freed.get_status(), MealBookingStatus::Cancelled); |
| 531 | assert_eq!(seats(&menu, &db).await, 0); | 534 | assert_eq!(seats(&menu, &db).await, 0); |
| 532 | assert_eq!( | 535 | assert_eq!( |
| 533 | - MealLedger::balance_of(&ali, &db).await.unwrap(), | 536 | + meal_ledger::balance_of(&db, &ali).await.unwrap(), |
| 534 | 0, | 537 | 0, |
| 535 | "the reversal must have committed with the flip, not after it" | 538 | "the reversal must have committed with the flip, not after it" |
| 536 | ); | 539 | ); |
| @@ -540,7 +543,7 @@ mod tests { | |||
| 540 | meal_booking::book(&db, &menu, &ali, &ali, &open) | 543 | meal_booking::book(&db, &menu, &ali, &ali, &open) |
| 541 | .await | 544 | .await |
| 542 | .unwrap(); | 545 | .unwrap(); |
| 543 | - assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); | 546 | + assert_eq!(meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000); |
| 544 | } | 547 | } |
| 545 | 548 | ||
| 546 | /// The seat may not be held without its money. Driven against | 549 | /// The seat may not be held without its money. Driven against |
| @@ -555,8 +558,8 @@ mod tests { | |||
| 555 | let (db, menu) = menu(None).await; | 558 | let (db, menu) = menu(None).await; |
| 556 | let ali = UserId::generate(); | 559 | let ali = UserId::generate(); |
| 557 | add_dish(&menu, 1_000, &db).await; | 560 | add_dish(&menu, 1_000, &db).await; |
| 558 | - let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); | 561 | + let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); |
| 559 | - let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); | 562 | + let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| 560 | let row = MealBooking { | 563 | let row = MealBooking { |
| 561 | id: MealBookingId::composite(&menu, &ali), | 564 | id: MealBookingId::composite(&menu, &ali), |
| 562 | menu: menu.clone(), | 565 | menu: menu.clone(), |
| @@ -586,7 +589,7 @@ mod tests { | |||
| 586 | assert!(matches!(place().await, Claimed::Made(_))); | 589 | assert!(matches!(place().await, Claimed::Made(_))); |
| 587 | assert_eq!(seats(&menu, &db).await, 1); | 590 | assert_eq!(seats(&menu, &db).await, 1); |
| 588 | assert_eq!( | 591 | assert_eq!( |
| 589 | - MealLedger::balance_of(&ali, &db).await.unwrap(), | 592 | + meal_ledger::balance_of(&db, &ali).await.unwrap(), |
| 590 | -1_000, | 593 | -1_000, |
| 591 | "the charge must have committed with the claim, not after it" | 594 | "the charge must have committed with the claim, not after it" |
| 592 | ); | 595 | ); |
| @@ -595,7 +598,7 @@ mod tests { | |||
| 595 | // back — no second seat and, just as importantly, no second charge. | 598 | // back — no second seat and, just as importantly, no second charge. |
| 596 | assert!(matches!(place().await, Claimed::Duplicate)); | 599 | assert!(matches!(place().await, Claimed::Duplicate)); |
| 597 | assert_eq!(seats(&menu, &db).await, 1); | 600 | assert_eq!(seats(&menu, &db).await, 1); |
| 598 | - assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); | 601 | + assert_eq!(meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000); |
| 599 | } | 602 | } |
| 600 | 603 | ||
| 601 | /// A free menu owes no refund, so the flip must carry no ledger line at all | 604 | /// A free menu owes no refund, so the flip must carry no ledger line at all |
| @@ -613,7 +616,7 @@ mod tests { | |||
| 613 | .unwrap() | 616 | .unwrap() |
| 614 | .expect("a free seat is still a seat"); | 617 | .expect("a free seat is still a seat"); |
| 615 | assert_eq!(seats(&menu, &db).await, 0); | 618 | assert_eq!(seats(&menu, &db).await, 0); |
| 616 | - let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) | 619 | + let (lines, total) = meal_ledger::list_for_student(&db, &ali, None, 0) |
| 617 | .await | 620 | .await |
| 618 | .unwrap(); | 621 | .unwrap(); |
| 619 | assert!(lines.is_empty() && total == 0, "a free seat moves no money"); | 622 | assert!(lines.is_empty() && total == 0, "a free seat moves no money"); |
src/db/meal_ledger.rsadded+195 -0
| @@ -0,0 +1,195 @@ | |||
| 1 | +//! The `meal_ledger` table: the append-only money writes and reads. The | ||
| 2 | +//! row/newtype shapes, the deterministic id minters and the sign | ||
| 3 | +//! convention live in [`crate::domain::meal_ledger`]; the charge/reversal | ||
| 4 | +//! and credit workflows that sequence these in [`crate::service::meal_ledger`]. | ||
| 5 | + | ||
| 6 | +use surrealdb::types::{AlreadyExistsError, SurrealValue}; | ||
| 7 | + | ||
| 8 | +use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE}; | ||
| 9 | +use crate::database::{Database, lost_the_race}; | ||
| 10 | +use crate::db::menu_dish; | ||
| 11 | +use crate::db::page::PagedList; | ||
| 12 | +use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind}; | ||
| 13 | +use crate::domain::menu::MenuId; | ||
| 14 | +use crate::domain::user::UserId; | ||
| 15 | +use crate::error::AppError; | ||
| 16 | + | ||
| 17 | +/// Did this `CREATE` fail *only* because the row is already there? Matched on | ||
| 18 | +/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text | ||
| 19 | +/// and never on "any database error", because swallowing a real fault in money | ||
| 20 | +/// code would be far worse than the 500 it saves. | ||
| 21 | +fn is_duplicate_record(error: &surrealdb::Error) -> bool { | ||
| 22 | + matches!( | ||
| 23 | + error.already_exists_details(), | ||
| 24 | + Some(AlreadyExistsError::Record { .. }) | ||
| 25 | + ) | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// The only writer: one `CREATE`, no update path anywhere in this module. | ||
| 29 | +/// | ||
| 30 | +/// A line whose id already exists is left exactly as it is — the row wins, | ||
| 31 | +/// the write is dropped. That is what makes a deterministic id (see | ||
| 32 | +/// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same | ||
| 33 | +/// append is a no-op, never a second line and never an edit of the first. | ||
| 34 | +/// The point read is on the id itself, so unlike a scan it cannot miss a | ||
| 35 | +/// row a concurrent writer just made — but it is only a fast path. The | ||
| 36 | +/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves | ||
| 37 | +/// the row untouched, so the writer that lost the race reads back the | ||
| 38 | +/// winner's line instead of failing the request with a 500. | ||
| 39 | +/// | ||
| 40 | +/// A *write conflict* is the same race decided one layer down — two | ||
| 41 | +/// appends of one id arriving together are no longer serialized by a | ||
| 42 | +/// process-wide lock, so the store aborts one as retryable instead of | ||
| 43 | +/// answering it "already exists". Both are read back the same way, and a | ||
| 44 | +/// conflict that turns out to have written nothing is simply tried again; | ||
| 45 | +/// no path here can write a second line, since the id is the key. | ||
| 46 | +pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> { | ||
| 47 | + if let Some(existing) = read(db, &row.id).await? { | ||
| 48 | + return Ok(existing); | ||
| 49 | + } | ||
| 50 | + let id = row.id.clone(); | ||
| 51 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 52 | + match db.create(id.record()).content(row.clone()).await { | ||
| 53 | + Ok(Some(created)) => return Ok(created), | ||
| 54 | + Ok(None) => break, | ||
| 55 | + Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | ||
| 56 | + if let Some(existing) = read(db, &id).await? { | ||
| 57 | + return Ok(existing); | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + Err(e) => return Err(e.into()), | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + Err(AppError::Internal("failed to write the ledger line".into())) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> { | ||
| 67 | + Ok(db.select(id.record()).await?) | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// What a seat on `menu` costs *right now*: the sum of its dishes. `None` | ||
| 71 | +/// when the menu is free (or empty) — a zero line is noise, not history. | ||
| 72 | +/// | ||
| 73 | +/// Called before the seat is taken so an unchargeable menu (one summing | ||
| 74 | +/// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of | ||
| 75 | +/// leaving a booked-but-unbilled row behind. | ||
| 76 | +pub async fn price_snapshot( | ||
| 77 | + db: &Database, | ||
| 78 | + menu: &MenuId, | ||
| 79 | +) -> Result<Option<LedgerAmount>, AppError> { | ||
| 80 | + let total = menu_dish::list_for_menu(db, menu) | ||
| 81 | + .await? | ||
| 82 | + .iter() | ||
| 83 | + .fold(0i64, |sum, dish| { | ||
| 84 | + sum.saturating_add(dish.get_price_minor().as_minor()) | ||
| 85 | + }); | ||
| 86 | + if total == 0 { | ||
| 87 | + return Ok(None); | ||
| 88 | + } | ||
| 89 | + Ok(Some(LedgerAmount::try_new(total)?)) | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// A student's whole statement, newest first. | ||
| 93 | +pub async fn list_for_student( | ||
| 94 | + db: &Database, | ||
| 95 | + student: &UserId, | ||
| 96 | + limit: Option<i64>, | ||
| 97 | + offset: i64, | ||
| 98 | +) -> Result<(Vec<MealLedger>, i64), AppError> { | ||
| 99 | + PagedList::new( | ||
| 100 | + "meal_ledger WHERE student = $student", | ||
| 101 | + "ORDER BY created_at DESC, id DESC", | ||
| 102 | + ) | ||
| 103 | + .bind("student", student.record()) | ||
| 104 | + .run(limit, offset, db) | ||
| 105 | + .await | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// The derived balance: `credits + reversals - charges`, in minor units. | ||
| 109 | +/// Negative means the student owes the school. Never stored anywhere. | ||
| 110 | +/// | ||
| 111 | +/// **The sum is taken per kind by the database** and only the three totals | ||
| 112 | +/// come back, so a balance read costs the same whether the statement holds | ||
| 113 | +/// four lines or forty thousand. It used to decode and fold every line, and | ||
| 114 | +/// nothing bounds a statement's length but the cycle ceiling | ||
| 115 | +/// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS)) | ||
| 116 | +/// added alongside this: every book/cancel | ||
| 117 | +/// pair appends two permanent rows, and each one was paid for again by | ||
| 118 | +/// every later `GET /meals/balance/*`. | ||
| 119 | +/// | ||
| 120 | +/// **The signs stay on the kind**, applied by the very | ||
| 121 | +/// [`MealLedgerKind::sign`] | ||
| 122 | +/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN | ||
| 123 | +/// -amount …` in SQL would have folded the whole balance in one statement | ||
| 124 | +/// and forked the one rule that decides what money means into a second | ||
| 125 | +/// language, where nothing would fail the day the two disagreed. Grouping | ||
| 126 | +/// instead keeps the aggregate ignorant of signs: it counts kinds, and | ||
| 127 | +/// Rust still says what a kind does. A stored running total was the third | ||
| 128 | +/// option and is a counter that can drift — a bug class this repo closes, | ||
| 129 | +/// not one it opens. | ||
| 130 | +pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { | ||
| 131 | + let totals: Vec<KindTotal> = db | ||
| 132 | + .query(format!( | ||
| 133 | + "SELECT kind, math::sum(amount_minor) AS total \ | ||
| 134 | + FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" | ||
| 135 | + )) | ||
| 136 | + .bind(("student", student.record())) | ||
| 137 | + .await? | ||
| 138 | + .check()? | ||
| 139 | + .take(0)?; | ||
| 140 | + Ok(totals | ||
| 141 | + .iter() | ||
| 142 | + .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands | ||
| 146 | +/// it back — at most three rows, never the lines behind them. | ||
| 147 | +#[derive(Debug, SurrealValue)] | ||
| 148 | +struct KindTotal { | ||
| 149 | + kind: MealLedgerKind, | ||
| 150 | + total: i64, | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +#[cfg(test)] | ||
| 154 | +mod tests { | ||
| 155 | + use super::*; | ||
| 156 | + | ||
| 157 | + /// The balance aggregate **against a real server**, and `#[ignore]`d for | ||
| 158 | + /// it: `init_mem`'s embedded engine is not the store this runs on, and an | ||
| 159 | + /// aggregate is exactly where the two are known to differ — a `count()` | ||
| 160 | + /// over an indexed field comes back `{count: N}` from the server and a | ||
| 161 | + /// bare int from memory, and `student` here *is* indexed. This asserts the | ||
| 162 | + /// `GROUP BY` really decodes into [`KindTotal`] and folds to the | ||
| 163 | + /// documented figure, per kind, scoped to one student. | ||
| 164 | + #[tokio::test] | ||
| 165 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 166 | + async fn the_balance_aggregate_decodes_on_a_real_server() { | ||
| 167 | + let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; | ||
| 168 | + db.query( | ||
| 169 | + "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ | ||
| 170 | + amount_minor = 10000, recorded_by = user:adm, created_at = 1; | ||
| 171 | + CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ | ||
| 172 | + amount_minor = 4500, recorded_by = user:adm, created_at = 2; | ||
| 173 | + CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ | ||
| 174 | + amount_minor = 1500, recorded_by = user:adm, created_at = 3; | ||
| 175 | + CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ | ||
| 176 | + amount_minor = 4500, recorded_by = user:adm, created_at = 4; | ||
| 177 | + CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ | ||
| 178 | + amount_minor = 777, recorded_by = user:adm, created_at = 5;", | ||
| 179 | + ) | ||
| 180 | + .await | ||
| 181 | + .unwrap() | ||
| 182 | + .check() | ||
| 183 | + .unwrap(); | ||
| 184 | + let ali = UserId::from_key("ali"); | ||
| 185 | + assert_eq!( | ||
| 186 | + balance_of(&db, &ali).await.unwrap(), | ||
| 187 | + 10_000 - 4_500 - 1_500 + 4_500 | ||
| 188 | + ); | ||
| 189 | + // Somebody with no lines at all: no groups come back, not an error. | ||
| 190 | + assert_eq!( | ||
| 191 | + balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), | ||
| 192 | + 0 | ||
| 193 | + ); | ||
| 194 | + } | ||
| 195 | +} | ||
src/db/menu.rsadded+608 -0
| @@ -0,0 +1,608 @@ | |||
| 1 | +//! The `menu` table: publishing (the slot reference claimed inside the | ||
| 2 | +//! write's own transaction), row reads and listings, the compare-and-set | ||
| 3 | +//! every cap PATCH writes through, the cascading delete, and | ||
| 4 | +//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every | ||
| 5 | +//! child write (a dish, an attendance mark) uses so nothing can outlive its | ||
| 6 | +//! menu. The kitchen workflows — the dish cap under | ||
| 7 | +//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in | ||
| 8 | +//! [`crate::service::menu`]. | ||
| 9 | + | ||
| 10 | +use surrealdb::types::{SurrealValue, Value}; | ||
| 11 | + | ||
| 12 | +use crate::constant::{ | ||
| 13 | + MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, | ||
| 14 | + REF_COUNT_FIELD, | ||
| 15 | +}; | ||
| 16 | +use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 17 | +use crate::db::cap; | ||
| 18 | +use crate::db::page::PagedList; | ||
| 19 | +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref}; | ||
| 20 | +use crate::domain::timestamp::Timestamp; | ||
| 21 | +use crate::domain::user::UserId; | ||
| 22 | +use crate::error::AppError; | ||
| 23 | + | ||
| 24 | +/// Move the menu's revision **and** run `statement` — a write to something | ||
| 25 | +/// hanging off a menu — in one transaction, handing back the row it returned. | ||
| 26 | +/// | ||
| 27 | +/// What a seat on that menu costs, or who is recorded against it, is about to | ||
| 28 | +/// change, so any booking that priced itself against the old revision has to | ||
| 29 | +/// re-read. The bump cannot be a query of its own: in the gap the menu row | ||
| 30 | +/// carries the *new* revision with the *old* price, and a booking reading there | ||
| 31 | +/// passes the very CAS that exists to refuse it — a seat billed a price the | ||
| 32 | +/// menu had already left, or admitted past a capacity that had already shrunk. | ||
| 33 | +/// | ||
| 34 | +/// The bump is also what makes the menu's **existence** part of the write | ||
| 35 | +/// ([`crate::db::menu_dish::create`] leans on | ||
| 36 | +/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, | ||
| 37 | +/// and a delete racing this one touches the very key this transaction writes, | ||
| 38 | +/// so the two cannot both commit. Reading the menu instead — even as the write | ||
| 39 | +/// statement's own target — does not survive that race: the read sees a row the | ||
| 40 | +/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot | ||
| 41 | +/// predating this insert, so both commit and the child outlives its menu | ||
| 42 | +/// (measured 378 of 3600 raced rounds before this shape was shared). | ||
| 43 | +/// | ||
| 44 | +/// Deliberately on every such write, not only the ones that move | ||
| 45 | +/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies | ||
| 46 | +/// to every write cannot be forgotten by the next one added. | ||
| 47 | +/// | ||
| 48 | +/// Admissible for [`transaction_with_retry`] as long as `statement` is: an | ||
| 49 | +/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never | ||
| 50 | +/// answer "already exists", and neither can an `UPSERT` whose id is bijective | ||
| 51 | +/// with every unique tuple its table indexes — a lost round wrote nothing, so | ||
| 52 | +/// re-sending it is the recovery. | ||
| 53 | +pub(crate) async fn bump_menu_and_write<T: SurrealValue>( | ||
| 54 | + menu: &MenuId, | ||
| 55 | + statement: &str, | ||
| 56 | + mut bindings: Vec<(String, Value)>, | ||
| 57 | + db: &Database, | ||
| 58 | +) -> Result<Option<T>, AppError> { | ||
| 59 | + bindings.push(("menu".into(), menu.record().into_value())); | ||
| 60 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 61 | + db, | ||
| 62 | + &format!( | ||
| 63 | + "BEGIN TRANSACTION; | ||
| 64 | + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ | ||
| 65 | + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 66 | + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; | ||
| 67 | + LET $row = ({statement}); | ||
| 68 | + RETURN $row; | ||
| 69 | + COMMIT TRANSACTION;" | ||
| 70 | + ), | ||
| 71 | + &bindings, | ||
| 72 | + &["no_menu"], | ||
| 73 | + ) | ||
| 74 | + .await?; | ||
| 75 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 76 | + // executed" — only the THROW's own slot names the reason. | ||
| 77 | + if errors | ||
| 78 | + .values() | ||
| 79 | + .any(|error| error.to_string().contains("no_menu")) | ||
| 80 | + { | ||
| 81 | + return Err(AppError::NotFound); | ||
| 82 | + } | ||
| 83 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 84 | + return Err(error.into()); | ||
| 85 | + } | ||
| 86 | + // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. | ||
| 87 | + Ok(result.take::<Vec<T>>(4)?.into_iter().next()) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// Publish a menu. Refused (409) when the day+slot already carries one. | ||
| 91 | +/// | ||
| 92 | +/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the | ||
| 93 | +/// refusal is decided by the store rather than by a check a concurrent | ||
| 94 | +/// publish can outrun: two publishes of the same meal write one id, and the loser's | ||
| 95 | +/// "already exists" becomes the same 409. The pre-check stays for the | ||
| 96 | +/// ordinary case — and for menus published before ids were derived, whose | ||
| 97 | +/// ULID key no new publish can collide with. | ||
| 98 | +pub async fn create( | ||
| 99 | + db: &Database, | ||
| 100 | + date: MenuDate, | ||
| 101 | + slot: MenuSlot, | ||
| 102 | + capacity: Option<i64>, | ||
| 103 | + created_by: &UserId, | ||
| 104 | +) -> Result<Menu, AppError> { | ||
| 105 | + let taken = AppError::Conflict("a menu is already published for that date and slot"); | ||
| 106 | + if find(db, &date, &slot).await?.is_some() { | ||
| 107 | + return Err(taken); | ||
| 108 | + } | ||
| 109 | + // The menu takes a reference on its slot, which is what stops the slot | ||
| 110 | + // being dropped from the settings while this menu (whose slot is only | ||
| 111 | + // snapshotted text) still points at it. Claimed *inside* the write's own | ||
| 112 | + // transaction: a claim of its own could land and the row then fail to, | ||
| 113 | + // leaving the slot counted by a menu that does not exist — a slot | ||
| 114 | + // nobody can ever retire, and no crash window is small enough for that. | ||
| 115 | + let counter = slot_ref(slot.as_str()); | ||
| 116 | + let menu = Menu { | ||
| 117 | + id: MenuId::for_slot(&date, &slot), | ||
| 118 | + date, | ||
| 119 | + slot, | ||
| 120 | + capacity, | ||
| 121 | + version: Some(0), | ||
| 122 | + created_by: created_by.clone(), | ||
| 123 | + created_at: Timestamp::now(), | ||
| 124 | + }; | ||
| 125 | + let id = menu.id.record(); | ||
| 126 | + match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { | ||
| 127 | + cap::ClaimedRef::Made(created) => Ok(created), | ||
| 128 | + cap::ClaimedRef::Duplicate => Err(taken), | ||
| 129 | + cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( | ||
| 130 | + "the '{}' meal slot has been removed from the school's settings", | ||
| 131 | + menu.slot.as_str() | ||
| 132 | + ))), | ||
| 133 | + } | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> { | ||
| 137 | + Ok(db.select(id.record()).await?) | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// The menu for one day and slot, if any — the uniqueness check. | ||
| 141 | +pub async fn find( | ||
| 142 | + db: &Database, | ||
| 143 | + date: &MenuDate, | ||
| 144 | + slot: &MenuSlot, | ||
| 145 | +) -> Result<Option<Menu>, AppError> { | ||
| 146 | + let mut result = db | ||
| 147 | + .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") | ||
| 148 | + .bind(("date", date.as_str().to_string())) | ||
| 149 | + .bind(("slot", slot.as_str().to_string())) | ||
| 150 | + .await? | ||
| 151 | + .check()?; | ||
| 152 | + Ok(result.take::<Vec<Menu>>(0)?.into_iter().next()) | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +/// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; | ||
| 156 | +/// either may be omitted. The comparison is lexical, which is chronological | ||
| 157 | +/// for this format. | ||
| 158 | +pub async fn list( | ||
| 159 | + db: &Database, | ||
| 160 | + from: Option<&MenuDate>, | ||
| 161 | + to: Option<&MenuDate>, | ||
| 162 | + limit: Option<i64>, | ||
| 163 | + offset: i64, | ||
| 164 | +) -> Result<(Vec<Menu>, i64), AppError> { | ||
| 165 | + PagedList::new( | ||
| 166 | + "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", | ||
| 167 | + "ORDER BY date DESC, slot ASC, id DESC", | ||
| 168 | + ) | ||
| 169 | + .bind("from", from.map(|date| date.as_str().to_string())) | ||
| 170 | + .bind("to", to.map(|date| date.as_str().to_string())) | ||
| 171 | + .run(limit, offset, db) | ||
| 172 | + .await | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, | ||
| 176 | +/// because moving a published menu to another day is a different menu. | ||
| 177 | +/// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. | ||
| 178 | +/// | ||
| 179 | +/// The revision moves **in the same statement** as the cap, indivisibly: a | ||
| 180 | +/// booking claims its seat against the revision | ||
| 181 | +/// it read the cap at, so a shrink that bumped in a query of its own left a | ||
| 182 | +/// window where the row carried the *new* revision and the *old* cap — and | ||
| 183 | +/// a booking arriving there passes a CAS meant to refuse it, over-admitting | ||
| 184 | +/// by exactly the seats in flight. | ||
| 185 | +pub async fn update( | ||
| 186 | + db: &Database, | ||
| 187 | + menu: Menu, | ||
| 188 | + capacity: Option<Option<i64>>, | ||
| 189 | +) -> Result<Menu, AppError> { | ||
| 190 | + let Some(capacity) = capacity else { | ||
| 191 | + // A PATCH carrying nothing writes nothing and bumps nothing: no | ||
| 192 | + // booking's price or cap has moved, so none owes a re-read. | ||
| 193 | + return read(db, &menu.id).await?.ok_or(AppError::NotFound); | ||
| 194 | + }; | ||
| 195 | + let sql = format!( | ||
| 196 | + "UPDATE $id SET capacity = $capacity, \ | ||
| 197 | + {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" | ||
| 198 | + ); | ||
| 199 | + // One counter write in flight at a time, like every other one. | ||
| 200 | + let _guard = cap::counter_lock().await; | ||
| 201 | + write_with_retry::<Menu>( | ||
| 202 | + db, | ||
| 203 | + &sql, | ||
| 204 | + &[ | ||
| 205 | + ("id".into(), menu.id.record().into_value()), | ||
| 206 | + ("capacity".into(), capacity.into_value()), | ||
| 207 | + ], | ||
| 208 | + ) | ||
| 209 | + .await? | ||
| 210 | + .into_iter() | ||
| 211 | + .next() | ||
| 212 | + .ok_or(AppError::NotFound) | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Delete the menu and the dishes on it — a dish has no meaning without | ||
| 216 | +/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. | ||
| 217 | +/// | ||
| 218 | +/// Refused (409) while a seat is still held, and the *row itself* decides | ||
| 219 | +/// that: the delete carries the seat counter in its `WHERE`, so a booking | ||
| 220 | +/// landing at that instant either takes its seat before | ||
| 221 | +/// the delete (which then finds a non-zero counter and refuses) or after it | ||
| 222 | +/// (and finds no menu). A read-then-delete pair had a window where both | ||
| 223 | +/// happened — a paid seat on a menu that no longer exists. | ||
| 224 | +/// | ||
| 225 | +/// The slot gets its reference back in that same transaction — a slot no | ||
| 226 | +/// menu is published for any more may leave the settings again, and the | ||
| 227 | +/// `FOR` runs only over a row the guard actually took. Released afterwards | ||
| 228 | +/// in a query of its own, a crash between the two left the slot counted by | ||
| 229 | +/// a menu that no longer exists: a slot nobody can retire. | ||
| 230 | +/// | ||
| 231 | +/// The marks go in that same `FOR`, for a sharper reason than tidiness: | ||
| 232 | +/// [`MenuId::for_slot`] is deterministic, so republishing the same day and | ||
| 233 | +/// slot mints the *same* record id. A mark left behind would come back as a | ||
| 234 | +/// mark on the new menu — the kitchen reading "served" for a student who | ||
| 235 | +/// never came — and until then the student's own report cites a menu that | ||
| 236 | +/// is gone. Attendance carries no money and no counter, so it is safe to | ||
| 237 | +/// drop; cancelled *bookings* deliberately stay, because their `attempt` | ||
| 238 | +/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut | ||
| 239 | +/// those and a re-book on a republished menu would reuse a charge id the | ||
| 240 | +/// ledger already holds, and the append (idempotent by design) would bill | ||
| 241 | +/// the seat nothing. | ||
| 242 | +/// | ||
| 243 | +/// The dishes ride in that `FOR` too, and for the same reason as the marks: | ||
| 244 | +/// run after the transaction committed, a crash between the two orphaned | ||
| 245 | +/// them on a record id republishing the day and slot mints again — a new | ||
| 246 | +/// menu serving (and pricing) the old one's food. | ||
| 247 | +pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { | ||
| 248 | + let sql = format!( | ||
| 249 | + "BEGIN TRANSACTION; | ||
| 250 | + LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); | ||
| 251 | + FOR $row IN ($gone ?? []) {{ | ||
| 252 | + UPSERT $counter SET {REF_COUNT_FIELD} = \ | ||
| 253 | + math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 254 | + DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; | ||
| 255 | + DELETE {MENU_DISH_TABLE} WHERE menu = $id; | ||
| 256 | + }}; | ||
| 257 | + RETURN $gone; | ||
| 258 | + COMMIT TRANSACTION;" | ||
| 259 | + ); | ||
| 260 | + // `slot` is a `READONLY` column, so this counter is the one the deleted | ||
| 261 | + // row carries. Nothing here can answer "already exists" — the `UPSERT` | ||
| 262 | + // is keyed by a slot name on a table with no `UNIQUE` index, so it | ||
| 263 | + // resolves onto the row it names ([`transaction_with_retry`]). | ||
| 264 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 265 | + db, | ||
| 266 | + &sql, | ||
| 267 | + &[ | ||
| 268 | + ("id".into(), menu.id.record().into_value()), | ||
| 269 | + ("counter".into(), slot_ref(menu.slot.as_str()).into_value()), | ||
| 270 | + ], | ||
| 271 | + &[], | ||
| 272 | + ) | ||
| 273 | + .await?; | ||
| 274 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 275 | + return Err(error.into()); | ||
| 276 | + } | ||
| 277 | + // BEGIN, the LET and the FOR take a slot each. | ||
| 278 | + let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else { | ||
| 279 | + // Nothing back: either seats are held, or the menu is already gone. | ||
| 280 | + return Err(match read(db, &menu.id).await? { | ||
| 281 | + Some(_) => AppError::Conflict("the menu still has live bookings"), | ||
| 282 | + None => AppError::NotFound, | ||
| 283 | + }); | ||
| 284 | + }; | ||
| 285 | + Ok(deleted) | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +#[cfg(test)] | ||
| 289 | +mod tests { | ||
| 290 | + use super::*; | ||
| 291 | + use crate::database::init_mem; | ||
| 292 | + use crate::db::meal_attendance; | ||
| 293 | + use crate::db::menu_dish; | ||
| 294 | + use crate::domain::meal_attendance::MealAttendanceStatus; | ||
| 295 | + use crate::domain::menu_dish::{DishName, DishPrice, DishTags}; | ||
| 296 | + use crate::domain::settings::MealSlotDef; | ||
| 297 | + | ||
| 298 | + async fn school() -> Database { | ||
| 299 | + let db = init_mem().await.unwrap(); | ||
| 300 | + db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | ||
| 301 | + .await | ||
| 302 | + .unwrap() | ||
| 303 | + .check() | ||
| 304 | + .unwrap(); | ||
| 305 | + db | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + fn lunch() -> MenuSlot { | ||
| 309 | + MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + /// The reference count, re-read out of the store — never off a return | ||
| 313 | + /// value, which the in-memory engine forges wins on. | ||
| 314 | + async fn refs(db: &Database) -> i64 { | ||
| 315 | + let mut result = db | ||
| 316 | + .query("SELECT VALUE (count ?? 0) FROM $id") | ||
| 317 | + .bind(("id", slot_ref("lunch"))) | ||
| 318 | + .await | ||
| 319 | + .unwrap() | ||
| 320 | + .check() | ||
| 321 | + .unwrap(); | ||
| 322 | + result | ||
| 323 | + .take::<Vec<i64>>(0) | ||
| 324 | + .unwrap() | ||
| 325 | + .into_iter() | ||
| 326 | + .next() | ||
| 327 | + .unwrap_or(0) | ||
| 328 | + } | ||
| 329 | + | ||
| 330 | + async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> { | ||
| 331 | + create( | ||
| 332 | + db, | ||
| 333 | + MenuDate::try_new(date).unwrap(), | ||
| 334 | + lunch(), | ||
| 335 | + None, | ||
| 336 | + &UserId::from_key("teacher"), | ||
| 337 | + ) | ||
| 338 | + .await | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + /// Plant a menu row the pre-check will (or will not) find, without going | ||
| 342 | + /// through the claim — a row published before the counter existed. | ||
| 343 | + async fn plant(id: &MenuId, date: &str, db: &Database) { | ||
| 344 | + db.query( | ||
| 345 | + "CREATE $id SET date = $date, slot = 'lunch', \ | ||
| 346 | + created_by = user:teacher, created_at = 1", | ||
| 347 | + ) | ||
| 348 | + .bind(("id", id.record())) | ||
| 349 | + .bind(("date", date.to_string())) | ||
| 350 | + .await | ||
| 351 | + .unwrap() | ||
| 352 | + .check() | ||
| 353 | + .unwrap(); | ||
| 354 | + } | ||
| 355 | + | ||
| 356 | + #[tokio::test] | ||
| 357 | + async fn publishing_lands_the_menu_and_its_reference_together() { | ||
| 358 | + let db = school().await; | ||
| 359 | + let menu = publish("2026-08-02", &db).await.unwrap(); | ||
| 360 | + assert!(read(&db, menu.get_id()).await.unwrap().is_some()); | ||
| 361 | + assert_eq!(refs(&db).await, 1); | ||
| 362 | + | ||
| 363 | + // The day+slot pre-check answers the second publish — and a refusal | ||
| 364 | + // may not count the slot, or the menu would outlive its own reference. | ||
| 365 | + let again = publish("2026-08-02", &db) | ||
| 366 | + .await | ||
| 367 | + .expect_err("that day and slot are taken"); | ||
| 368 | + assert!(matches!(again, AppError::Conflict(_)), "got {again:?}"); | ||
| 369 | + assert_eq!(refs(&db).await, 1); | ||
| 370 | + } | ||
| 371 | + | ||
| 372 | + #[tokio::test] | ||
| 373 | + async fn a_retired_slot_refuses_and_writes_nothing() { | ||
| 374 | + let db = school().await; | ||
| 375 | + assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); | ||
| 376 | + | ||
| 377 | + let refused = publish("2026-08-02", &db) | ||
| 378 | + .await | ||
| 379 | + .expect_err("the slot left the settings"); | ||
| 380 | + assert!( | ||
| 381 | + matches!(refused, AppError::ConflictOwned(_)), | ||
| 382 | + "got {refused:?}" | ||
| 383 | + ); | ||
| 384 | + assert_eq!(refs(&db).await, 0); | ||
| 385 | + assert!( | ||
| 386 | + find(&db, &MenuDate::try_new("2026-08-02").unwrap(), &lunch(),) | ||
| 387 | + .await | ||
| 388 | + .unwrap() | ||
| 389 | + .is_none() | ||
| 390 | + ); | ||
| 391 | + } | ||
| 392 | + | ||
| 393 | + /// The race the fold exists for: a rival places the very row this publish | ||
| 394 | + /// is placing, between the pre-check and the write. Only the claim's own | ||
| 395 | + /// gate can answer it, and its answer must cost no reference. | ||
| 396 | + #[tokio::test] | ||
| 397 | + async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { | ||
| 398 | + let db = school().await; | ||
| 399 | + let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); | ||
| 400 | + // Planted under another day, so `find` misses it exactly as it would | ||
| 401 | + // in the instant before the rival's own row was visible. | ||
| 402 | + plant(&id, "1999-01-01", &db).await; | ||
| 403 | + | ||
| 404 | + let taken = publish("2026-08-02", &db) | ||
| 405 | + .await | ||
| 406 | + .expect_err("the id is taken"); | ||
| 407 | + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); | ||
| 408 | + assert_eq!(refs(&db).await, 0); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + /// Menus published before ids were derived keep a ULID key a new publish | ||
| 412 | + /// cannot collide with, so the pre-check is the only thing that can refuse. | ||
| 413 | + #[tokio::test] | ||
| 414 | + async fn a_legacy_ulid_menu_still_answers_taken() { | ||
| 415 | + let db = school().await; | ||
| 416 | + plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; | ||
| 417 | + | ||
| 418 | + let taken = publish("2026-08-02", &db) | ||
| 419 | + .await | ||
| 420 | + .expect_err("that day and slot are taken"); | ||
| 421 | + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); | ||
| 422 | + assert_eq!(refs(&db).await, 0); | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + /// The cap and the revision are one write. Nothing single-process can | ||
| 426 | + /// observe the torn state the two-query version left (a bumped revision | ||
| 427 | + /// over a cap that had not moved yet), so what is pinned here is the pair: | ||
| 428 | + /// the revision steps exactly once per cap move, and never for a PATCH that | ||
| 429 | + /// carried no cap at all — a booking re-reads only when something it priced | ||
| 430 | + /// itself against actually changed. | ||
| 431 | + #[tokio::test] | ||
| 432 | + async fn the_cap_and_the_revision_move_together_or_not_at_all() { | ||
| 433 | + let db = school().await; | ||
| 434 | + let menu = publish("2026-08-05", &db).await.unwrap(); | ||
| 435 | + let id = menu.get_id().clone(); | ||
| 436 | + assert_eq!(menu.get_version(), 0); | ||
| 437 | + | ||
| 438 | + let capped = update(&db, menu, Some(Some(5))).await.unwrap(); | ||
| 439 | + assert_eq!(capped.get_capacity(), Some(5)); | ||
| 440 | + assert_eq!(capped.get_version(), 1); | ||
| 441 | + // Re-read out of the store, never off the return value. | ||
| 442 | + let stored = read(&db, &id).await.unwrap().unwrap(); | ||
| 443 | + assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1)); | ||
| 444 | + | ||
| 445 | + // An empty PATCH moves neither, and reads the row back unchanged. | ||
| 446 | + let same = update(&db, stored, None).await.unwrap(); | ||
| 447 | + assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1)); | ||
| 448 | + | ||
| 449 | + // Clearing the cap is a move like any other. | ||
| 450 | + let uncapped = update(&db, same, Some(None)).await.unwrap(); | ||
| 451 | + assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2)); | ||
| 452 | + } | ||
| 453 | + | ||
| 454 | + #[tokio::test] | ||
| 455 | + async fn deleting_hands_the_reference_back_in_the_same_step() { | ||
| 456 | + let db = school().await; | ||
| 457 | + let monday = publish("2026-08-03", &db).await.unwrap(); | ||
| 458 | + publish("2026-08-04", &db).await.unwrap(); | ||
| 459 | + assert_eq!(refs(&db).await, 2); | ||
| 460 | + | ||
| 461 | + let id = monday.get_id().clone(); | ||
| 462 | + let ghost = monday.clone(); | ||
| 463 | + delete(&db, monday).await.unwrap(); | ||
| 464 | + assert!(read(&db, &id).await.unwrap().is_none()); | ||
| 465 | + assert_eq!(refs(&db).await, 1, "the row and its reference go together"); | ||
| 466 | + | ||
| 467 | + // Deleting what is already gone hands nothing back: a second release | ||
| 468 | + // would leave a slot one menu still uses free to be retired. | ||
| 469 | + let gone = delete(&db, ghost).await.expect_err("already deleted"); | ||
| 470 | + assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); | ||
| 471 | + assert_eq!(refs(&db).await, 1); | ||
| 472 | + assert!( | ||
| 473 | + !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), | ||
| 474 | + "a slot a menu is still published for may not be retired" | ||
| 475 | + ); | ||
| 476 | + | ||
| 477 | + // …and once the last menu goes, it may. | ||
| 478 | + let last = find(&db, &MenuDate::try_new("2026-08-04").unwrap(), &lunch()) | ||
| 479 | + .await | ||
| 480 | + .unwrap() | ||
| 481 | + .unwrap(); | ||
| 482 | + delete(&db, last).await.unwrap(); | ||
| 483 | + assert_eq!(refs(&db).await, 0); | ||
| 484 | + } | ||
| 485 | + | ||
| 486 | + /// Nothing hanging off a menu may survive the delete that swept it — not a | ||
| 487 | + /// dish, and not an attendance mark. Menu ids are deterministic on | ||
| 488 | + /// (date, slot), so a survivor is not litter: republishing that meal mints | ||
| 489 | + /// the *same* id and the orphan comes back attached to the new menu — the | ||
| 490 | + /// kitchen reading "served" for a student who never came, or pricing the | ||
| 491 | + /// old menu's food. | ||
| 492 | + /// | ||
| 493 | + /// The window is between [`delete`]'s `DELETE` and its cascade: a | ||
| 494 | + /// child write committing in there is a phantom insert into a range the | ||
| 495 | + /// delete already swept on an older snapshot, so the sweep removes nothing | ||
| 496 | + /// and *both* commit. It is closed by making every child write **write** the | ||
| 497 | + /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two | ||
| 498 | + /// transactions then touch one key and the store refuses to commit both. | ||
| 499 | + /// | ||
| 500 | + /// The window is opened by the database itself rather than by a lucky | ||
| 501 | + /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own | ||
| 502 | + /// transaction, the instant the row goes, so the `SLEEP` lands exactly | ||
| 503 | + /// between the delete and its sweep every single time. Nothing in `src/` | ||
| 504 | + /// knows about it; the seam is the schema. | ||
| 505 | + /// | ||
| 506 | + /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 507 | + /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 508 | + /// it commits both writes and answers `Ok` to each, which would fail this | ||
| 509 | + /// test on correct code (see [`crate::database::init_test_server`]). | ||
| 510 | + /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read* | ||
| 511 | + /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) | ||
| 512 | + /// turns this red at **both** of its two rounds — the mark commits, the | ||
| 513 | + /// sweep misses it, and the row is left pointing at a menu that is gone. | ||
| 514 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 515 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 516 | + async fn a_child_written_inside_a_delete_never_outlives_the_menu() { | ||
| 517 | + use crate::domain::menu_dish::DishDescription; | ||
| 518 | + | ||
| 519 | + let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; | ||
| 520 | + db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | ||
| 521 | + .await | ||
| 522 | + .unwrap() | ||
| 523 | + .check() | ||
| 524 | + .unwrap(); | ||
| 525 | + // Hold the delete open for a full second after the row is gone, while | ||
| 526 | + // its cascade still has to run. | ||
| 527 | + db.query( | ||
| 528 | + "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ | ||
| 529 | + THEN { SLEEP 1s; };", | ||
| 530 | + ) | ||
| 531 | + .await | ||
| 532 | + .unwrap() | ||
| 533 | + .check() | ||
| 534 | + .unwrap(); | ||
| 535 | + | ||
| 536 | + let (mut dishes, mut marks, mut swept) = (0, 0, 0); | ||
| 537 | + for round in 0..4 { | ||
| 538 | + let menu = publish(&format!("2026-09-{:02}", round + 1), &db) | ||
| 539 | + .await | ||
| 540 | + .unwrap(); | ||
| 541 | + let id = menu.get_id().clone(); | ||
| 542 | + | ||
| 543 | + let drop_it = { | ||
| 544 | + let db = db.clone(); | ||
| 545 | + tokio::spawn(async move { delete(&db, menu).await }) | ||
| 546 | + }; | ||
| 547 | + // The child starts inside the held window — the delete's row is | ||
| 548 | + // gone but uncommitted, which is exactly what a menu read believes. | ||
| 549 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 550 | + // One child per round, never both: whichever wrote first forces the | ||
| 551 | + // delete to re-send, and its second pass sweeps the other's row — | ||
| 552 | + // which would mask exactly the defect this test exists to catch. | ||
| 553 | + let child = { | ||
| 554 | + let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); | ||
| 555 | + tokio::spawn(async move { | ||
| 556 | + if dish { | ||
| 557 | + menu_dish::create( | ||
| 558 | + &db, | ||
| 559 | + &id, | ||
| 560 | + DishName::try_new("Pilav").unwrap(), | ||
| 561 | + None::<DishDescription>, | ||
| 562 | + DishPrice::try_new(1).unwrap(), | ||
| 563 | + DishTags::try_new(&[], &[]).unwrap(), | ||
| 564 | + ) | ||
| 565 | + .await | ||
| 566 | + .map(|_| ()) | ||
| 567 | + } else { | ||
| 568 | + meal_attendance::mark( | ||
| 569 | + &db, | ||
| 570 | + &id, | ||
| 571 | + &UserId::from_key("teacher"), | ||
| 572 | + MealAttendanceStatus::try_new("served").unwrap(), | ||
| 573 | + &UserId::from_key("teacher"), | ||
| 574 | + ) | ||
| 575 | + .await | ||
| 576 | + .map(|_| ()) | ||
| 577 | + } | ||
| 578 | + }) | ||
| 579 | + }; | ||
| 580 | + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 581 | + // A 404 for the child, or a 409/NotFound for the delete, is a | ||
| 582 | + // correct answer — the only defect is stored state. | ||
| 583 | + assert!( | ||
| 584 | + !matches!(child, Err(AppError::Db(_))), | ||
| 585 | + "round {round}: a raced child write must be answered, not 500: {child:?}" | ||
| 586 | + ); | ||
| 587 | + | ||
| 588 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 589 | + if read(&db, &id).await.unwrap().is_none() { | ||
| 590 | + swept += 1; | ||
| 591 | + dishes += menu_dish::list_for_menu(&db, &id).await.unwrap().len(); | ||
| 592 | + marks += meal_attendance::list_for_menu(&db, &id, None, 0) | ||
| 593 | + .await | ||
| 594 | + .unwrap() | ||
| 595 | + .1; | ||
| 596 | + } else if drop_it.is_ok() { | ||
| 597 | + panic!("round {round}: the delete reported success but the menu is still there"); | ||
| 598 | + } | ||
| 599 | + } | ||
| 600 | + eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); | ||
| 601 | + assert!( | ||
| 602 | + swept > 0, | ||
| 603 | + "no round ever deleted the menu, so the window was never reached" | ||
| 604 | + ); | ||
| 605 | + assert_eq!(dishes, 0, "a dish outlived its menu"); | ||
| 606 | + assert_eq!(marks, 0, "a mark outlived its menu"); | ||
| 607 | + } | ||
| 608 | +} | ||
src/db/menu_dish.rsadded+175 -0
| @@ -0,0 +1,175 @@ | |||
| 1 | +//! The `menu_dish` table: the dishes on a menu — the insert and the field | ||
| 2 | +//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the | ||
| 3 | +//! reads and listings, and the delete. The dish-cap gate and the | ||
| 4 | +//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in | ||
| 5 | +//! [`crate::service::menu`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::{SurrealValue, Value}; | ||
| 8 | + | ||
| 9 | +use crate::constant::MENU_VERSION_FIELD; | ||
| 10 | +use crate::database::{Database, transaction_with_retry}; | ||
| 11 | +use crate::db::menu::bump_menu_and_write; | ||
| 12 | +use crate::domain::menu::MenuId; | ||
| 13 | +use crate::domain::menu_dish::{ | ||
| 14 | + DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, | ||
| 15 | +}; | ||
| 16 | +use crate::domain::timestamp::Timestamp; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | + | ||
| 19 | +/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. | ||
| 20 | +pub async fn create( | ||
| 21 | + db: &Database, | ||
| 22 | + menu: &MenuId, | ||
| 23 | + name: DishName, | ||
| 24 | + description: Option<DishDescription>, | ||
| 25 | + price_minor: DishPrice, | ||
| 26 | + tags: DishTags, | ||
| 27 | +) -> Result<MenuDish, AppError> { | ||
| 28 | + let dish = MenuDish { | ||
| 29 | + id: MenuDishId::generate(), | ||
| 30 | + menu: menu.clone(), | ||
| 31 | + name, | ||
| 32 | + description, | ||
| 33 | + price_minor, | ||
| 34 | + tags, | ||
| 35 | + created_at: Timestamp::now(), | ||
| 36 | + }; | ||
| 37 | + // The revision bump and the insert are one transaction, and the bump is | ||
| 38 | + // what makes the menu's existence part of it: the `UPDATE` matches | ||
| 39 | + // nothing once the menu row is deleted, and a delete racing this one | ||
| 40 | + // touches the very key this transaction writes, so the two cannot both | ||
| 41 | + // commit. Without that, a dish landing just after `DELETE /menus/{id}` | ||
| 42 | + // removed the row but before its cascade ran outlived its menu. | ||
| 43 | + // Every other dish write bumps the same version key, so a lost round is | ||
| 44 | + // ordinary here; it is re-sent rather than reported. Re-sending is sound | ||
| 45 | + // even with the `CREATE` in the batch — the abort wrote nothing, the id | ||
| 46 | + // is a ULID freshly generated above and never seen by a rival, and | ||
| 47 | + // `menu_dish` carries no UNIQUE index — so the retry cannot answer | ||
| 48 | + // "already exists" (see [`transaction_with_retry`]). | ||
| 49 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 50 | + db, | ||
| 51 | + &format!( | ||
| 52 | + "BEGIN TRANSACTION; | ||
| 53 | + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ | ||
| 54 | + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 55 | + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; | ||
| 56 | + CREATE $id CONTENT $dish; | ||
| 57 | + COMMIT TRANSACTION;" | ||
| 58 | + ), | ||
| 59 | + &[ | ||
| 60 | + ("menu".into(), menu.record().into_value()), | ||
| 61 | + ("id".into(), dish.id.record().into_value()), | ||
| 62 | + ("dish".into(), dish.into_value()), | ||
| 63 | + ], | ||
| 64 | + &["no_menu"], | ||
| 65 | + ) | ||
| 66 | + .await?; | ||
| 67 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 68 | + // executed" — only the THROW's own slot names the reason. | ||
| 69 | + if errors | ||
| 70 | + .values() | ||
| 71 | + .any(|error| error.to_string().contains("no_menu")) | ||
| 72 | + { | ||
| 73 | + return Err(AppError::NotFound); | ||
| 74 | + } | ||
| 75 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 76 | + return Err(error.into()); | ||
| 77 | + } | ||
| 78 | + // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. | ||
| 79 | + result | ||
| 80 | + .take::<Vec<MenuDish>>(3)? | ||
| 81 | + .into_iter() | ||
| 82 | + .next() | ||
| 83 | + .ok_or_else(|| AppError::Internal("failed to add the dish".into())) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> { | ||
| 87 | + Ok(db.select(id.record()).await?) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// Every dish on one menu, in the order they were added. | ||
| 91 | +pub async fn list_for_menu(db: &Database, menu: &MenuId) -> Result<Vec<MenuDish>, AppError> { | ||
| 92 | + list_for_menus(db, std::slice::from_ref(menu)).await | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Dishes for a whole page of menus in one round trip — the alternative is | ||
| 96 | +/// a query per menu, which is the N+1 the pagination slice exists to avoid. | ||
| 97 | +pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result<Vec<MenuDish>, AppError> { | ||
| 98 | + if menus.is_empty() { | ||
| 99 | + return Ok(Vec::new()); | ||
| 100 | + } | ||
| 101 | + let mut result = db | ||
| 102 | + .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") | ||
| 103 | + .bind(( | ||
| 104 | + "menus", | ||
| 105 | + menus.iter().map(MenuId::record).collect::<Vec<_>>(), | ||
| 106 | + )) | ||
| 107 | + .await? | ||
| 108 | + .check()?; | ||
| 109 | + Ok(result.take::<Vec<MenuDish>>(0)?) | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. | ||
| 113 | +pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result<usize, AppError> { | ||
| 114 | + Ok(list_for_menu(db, menu).await?.len()) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// Write only the fields the PATCH carried. `description` is nullable, so | ||
| 118 | +/// it takes the three-way shape: absent = keep, `Some(None)` = clear. | ||
| 119 | +/// | ||
| 120 | +/// The `SET` is built here rather than by | ||
| 121 | +/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the | ||
| 122 | +/// revision bump lands on *another* row and has to share this write's | ||
| 123 | +/// transaction; the field-by-field scoping — an omitted field is never | ||
| 124 | +/// written, so a concurrent PATCH of another one is not reverted — is the | ||
| 125 | +/// same rule, spelled out. | ||
| 126 | +pub async fn update( | ||
| 127 | + db: &Database, | ||
| 128 | + dish: MenuDish, | ||
| 129 | + name: Option<DishName>, | ||
| 130 | + description: Option<Option<DishDescription>>, | ||
| 131 | + price_minor: Option<DishPrice>, | ||
| 132 | + tags: Option<DishTags>, | ||
| 133 | +) -> Result<MenuDish, AppError> { | ||
| 134 | + let mut sets: Vec<&str> = Vec::new(); | ||
| 135 | + let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())]; | ||
| 136 | + let mut set = |field: &'static str, value: Option<Value>| { | ||
| 137 | + if let Some(value) = value { | ||
| 138 | + sets.push(field); | ||
| 139 | + bindings.push((field.into(), value)); | ||
| 140 | + } | ||
| 141 | + }; | ||
| 142 | + set("name", name.map(SurrealValue::into_value)); | ||
| 143 | + set("description", description.map(SurrealValue::into_value)); | ||
| 144 | + set("price_minor", price_minor.map(SurrealValue::into_value)); | ||
| 145 | + set("tags", tags.map(SurrealValue::into_value)); | ||
| 146 | + // A PATCH that carried nothing writes nothing and reads the row back, | ||
| 147 | + // exactly as `FieldUpdate` answers one — but it still moves the | ||
| 148 | + // revision, because "every dish write bumps" is the rule a caller can | ||
| 149 | + // rely on without knowing which fields were on the wire. | ||
| 150 | + let statement = if sets.is_empty() { | ||
| 151 | + "SELECT * FROM $id".to_string() | ||
| 152 | + } else { | ||
| 153 | + format!( | ||
| 154 | + "UPDATE $id SET {} RETURN AFTER", | ||
| 155 | + sets.iter() | ||
| 156 | + .map(|field| format!("{field} = ${field}")) | ||
| 157 | + .collect::<Vec<_>>() | ||
| 158 | + .join(", ") | ||
| 159 | + ) | ||
| 160 | + }; | ||
| 161 | + bump_menu_and_write(&dish.menu, &statement, bindings, db) | ||
| 162 | + .await? | ||
| 163 | + .ok_or(AppError::NotFound) | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { | ||
| 167 | + bump_menu_and_write( | ||
| 168 | + &dish.menu, | ||
| 169 | + "DELETE $id RETURN BEFORE", | ||
| 170 | + vec![("id".into(), dish.id.record().into_value())], | ||
| 171 | + db, | ||
| 172 | + ) | ||
| 173 | + .await? | ||
| 174 | + .ok_or(AppError::NotFound) | ||
| 175 | +} | ||
src/db/mod.rsmodified+5 -1
| @@ -1,17 +1,21 @@ | |||
| 1 | //! The only layer that executes queries. | 1 | //! The only layer that executes queries. |
| 2 | - | ||
| 3 | pub mod appointment; | 2 | pub mod appointment; |
| 4 | pub mod appointment_slot; | 3 | pub mod appointment_slot; |
| 5 | pub mod cap; | 4 | pub mod cap; |
| 6 | pub mod class_blueprint; | 5 | pub mod class_blueprint; |
| 7 | pub mod course; | 6 | pub mod course; |
| 8 | pub mod course_session; | 7 | pub mod course_session; |
| 8 | +pub mod dietary_profile; | ||
| 9 | pub mod enrollment; | 9 | pub mod enrollment; |
| 10 | pub mod exam; | 10 | pub mod exam; |
| 11 | pub mod exam_attempt; | 11 | pub mod exam_attempt; |
| 12 | pub mod exam_question; | 12 | pub mod exam_question; |
| 13 | pub mod field_update; | 13 | pub mod field_update; |
| 14 | +pub mod meal_attendance; | ||
| 14 | pub mod meal_booking; | 15 | pub mod meal_booking; |
| 16 | +pub mod meal_ledger; | ||
| 17 | +pub mod menu; | ||
| 18 | +pub mod menu_dish; | ||
| 15 | pub mod note; | 19 | pub mod note; |
| 16 | pub mod page; | 20 | pub mod page; |
| 17 | pub mod payment_ledger; | 21 | pub mod payment_ledger; |
src/domain/dietary_profile.rsmodified+11 -71
| @@ -8,16 +8,17 @@ | |||
| 8 | //! student" answerable as a set intersection, without the backend knowing any | 8 | //! student" answerable as a set intersection, without the backend knowing any |
| 9 | //! nutrition. | 9 | //! nutrition. |
| 10 | //! | 10 | //! |
| 11 | +//! The queries live in [`crate::db::dietary_profile`]; the web layer reads | ||
| 12 | +//! through [`crate::service::dietary_profile`]. | ||
| 13 | +//! | ||
| 11 | //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags | 14 | //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags |
| 12 | 15 | ||
| 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 16 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 14 | 17 | ||
| 15 | use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; | 18 | use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; |
| 16 | -use crate::database::Database; | ||
| 17 | -use crate::db::field_update::FieldUpdate; | ||
| 18 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 19 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 20 | -use crate::error::{AppError, ValidationError}; | 21 | +use crate::error::ValidationError; |
| 21 | use crate::validate::validate_optional; | 22 | use crate::validate::validate_optional; |
| 22 | 23 | ||
| 23 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 24 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -46,7 +47,7 @@ impl DietaryProfileId { | |||
| 46 | /// list — the same vocabulary a dish is tagged from, deduplicated and in the | 47 | /// list — the same vocabulary a dish is tagged from, deduplicated and in the |
| 47 | /// order given. | 48 | /// order given. |
| 48 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 49 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 49 | -pub struct DietaryTags(Vec<String>); | 50 | +pub struct DietaryTags(pub(crate) Vec<String>); |
| 50 | 51 | ||
| 51 | impl DietaryTags { | 52 | impl DietaryTags { |
| 52 | pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> { | 53 | pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> { |
| @@ -97,12 +98,12 @@ impl DietaryNote { | |||
| 97 | 98 | ||
| 98 | #[derive(Debug, Clone, SurrealValue)] | 99 | #[derive(Debug, Clone, SurrealValue)] |
| 99 | pub struct DietaryProfile { | 100 | pub struct DietaryProfile { |
| 100 | - id: DietaryProfileId, | 101 | + pub(crate) id: DietaryProfileId, |
| 101 | - student: UserId, | 102 | + pub(crate) student: UserId, |
| 102 | - tags: DietaryTags, | 103 | + pub(crate) tags: DietaryTags, |
| 103 | - note: Option<DietaryNote>, | 104 | + pub(crate) note: Option<DietaryNote>, |
| 104 | - updated_by: UserId, | 105 | + pub(crate) updated_by: UserId, |
| 105 | - updated_at: Timestamp, | 106 | + pub(crate) updated_at: Timestamp, |
| 106 | } | 107 | } |
| 107 | 108 | ||
| 108 | impl DietaryProfile { | 109 | impl DietaryProfile { |
| @@ -125,67 +126,6 @@ impl DietaryProfile { | |||
| 125 | pub fn get_updated_at(&self) -> Timestamp { | 126 | pub fn get_updated_at(&self) -> Timestamp { |
| 126 | self.updated_at | 127 | self.updated_at |
| 127 | } | 128 | } |
| 128 | - | ||
| 129 | - /// One student's profile, or `None` while the school never recorded one. | ||
| 130 | - /// A single `SELECT` by record id — this is what a menu read joins on. | ||
| 131 | - pub async fn read(student: &UserId, db: &Database) -> Result<Option<Self>, AppError> { | ||
| 132 | - Ok(db.select(DietaryProfileId::of(student).record()).await?) | ||
| 133 | - } | ||
| 134 | - | ||
| 135 | - /// The tags a menu read matches its dishes against: the caller's, or an | ||
| 136 | - /// empty list when they have no profile (every manager, every teacher). | ||
| 137 | - pub async fn tags_of(student: &UserId, db: &Database) -> Result<Vec<String>, AppError> { | ||
| 138 | - Ok(Self::read(student, db) | ||
| 139 | - .await? | ||
| 140 | - .map(|profile| profile.tags.as_slice().to_vec()) | ||
| 141 | - .unwrap_or_default()) | ||
| 142 | - } | ||
| 143 | - | ||
| 144 | - /// Write the fields the PATCH carried. Creates the row on first write; | ||
| 145 | - /// afterwards only the named fields move, because `student` is `READONLY` | ||
| 146 | - /// and a whole-row save would also revert a concurrent edit of the other | ||
| 147 | - /// field (see [`FieldUpdate`]). | ||
| 148 | - pub async fn save( | ||
| 149 | - student: &UserId, | ||
| 150 | - tags: Option<DietaryTags>, | ||
| 151 | - note: Option<Option<DietaryNote>>, | ||
| 152 | - by: &UserId, | ||
| 153 | - db: &Database, | ||
| 154 | - ) -> Result<Self, AppError> { | ||
| 155 | - if Self::read(student, db).await?.is_none() { | ||
| 156 | - let profile = Self { | ||
| 157 | - id: DietaryProfileId::of(student), | ||
| 158 | - student: student.clone(), | ||
| 159 | - tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), | ||
| 160 | - note: note.clone().flatten(), | ||
| 161 | - updated_by: by.clone(), | ||
| 162 | - updated_at: Timestamp::now(), | ||
| 163 | - }; | ||
| 164 | - match db.create(profile.id.record()).content(profile).await { | ||
| 165 | - Ok(Some(created)) => return Ok(created), | ||
| 166 | - Ok(None) => { | ||
| 167 | - return Err(AppError::Internal("failed to save the profile".into())); | ||
| 168 | - } | ||
| 169 | - // A rival first `PATCH` created the row in the round trip since | ||
| 170 | - // the read above (the `dietary_profile_student` UNIQUE index | ||
| 171 | - // catches the same collision), and `CREATE` leaves that row | ||
| 172 | - // untouched — so this call is a plain field write after all, | ||
| 173 | - // exactly as it would have been a moment later. Propagated, it | ||
| 174 | - // was a 500 on a legitimate request. Same shape as | ||
| 175 | - // [`MealLedger::append`](crate::domain::meal_ledger), which | ||
| 176 | - // reads the winner back rather than failing. | ||
| 177 | - Err(err) if err.is_already_exists() => {} | ||
| 178 | - Err(err) => return Err(err.into()), | ||
| 179 | - } | ||
| 180 | - } | ||
| 181 | - FieldUpdate::new(DietaryProfileId::of(student).record()) | ||
| 182 | - .set("tags", tags) | ||
| 183 | - .set("note", note) | ||
| 184 | - .set("updated_by", Some(by.clone())) | ||
| 185 | - .set("updated_at", Some(Timestamp::now())) | ||
| 186 | - .run::<Self>(db) | ||
| 187 | - .await | ||
| 188 | - } | ||
| 189 | } | 129 | } |
| 190 | 130 | ||
| 191 | /// Which of a dish's tags the reader's own profile flags. Empty when there is | 131 | /// Which of a dish's tags the reader's own profile flags. Empty when there is |
src/domain/meal_attendance.rsmodified+11 -106
| @@ -14,16 +14,17 @@ | |||
| 14 | //! The statuses are the fixed [`MEAL_ATTENDANCE_STATUSES`] pair, deliberately | 14 | //! The statuses are the fixed [`MEAL_ATTENDANCE_STATUSES`] pair, deliberately |
| 15 | //! *not* the school's editable `attendance_statuses`: a canteen line has no | 15 | //! *not* the school's editable `attendance_statuses`: a canteen line has no |
| 16 | //! "late" or "excused". | 16 | //! "late" or "excused". |
| 17 | +//! | ||
| 18 | +//! The queries live in [`crate::db::meal_attendance`]; the web layer reads | ||
| 19 | +//! through [`crate::service::meal_attendance`]. | ||
| 17 | 20 | ||
| 18 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 21 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 19 | 22 | ||
| 20 | use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; | 23 | use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; |
| 21 | -use crate::database::Database; | 24 | +use crate::domain::menu::MenuId; |
| 22 | -use crate::domain::menu::{MenuDate, MenuId, bump_menu_and_write}; | ||
| 23 | -use crate::db::page::PagedList; | ||
| 24 | use crate::domain::timestamp::Timestamp; | 25 | use crate::domain::timestamp::Timestamp; |
| 25 | use crate::domain::user::UserId; | 26 | use crate::domain::user::UserId; |
| 26 | -use crate::error::{AppError, ValidationError}; | 27 | +use crate::error::ValidationError; |
| 27 | 28 | ||
| 28 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 29 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 29 | pub struct MealAttendanceId(RecordId); | 30 | pub struct MealAttendanceId(RecordId); |
| @@ -74,12 +75,12 @@ impl MealAttendanceStatus { | |||
| 74 | 75 | ||
| 75 | #[derive(Debug, Clone, SurrealValue)] | 76 | #[derive(Debug, Clone, SurrealValue)] |
| 76 | pub struct MealAttendance { | 77 | pub struct MealAttendance { |
| 77 | - id: MealAttendanceId, | 78 | + pub(crate) id: MealAttendanceId, |
| 78 | - menu: MenuId, | 79 | + pub(crate) menu: MenuId, |
| 79 | - student: UserId, | 80 | + pub(crate) student: UserId, |
| 80 | - status: MealAttendanceStatus, | 81 | + pub(crate) status: MealAttendanceStatus, |
| 81 | - marked_by: UserId, | 82 | + pub(crate) marked_by: UserId, |
| 82 | - marked_at: Timestamp, | 83 | + pub(crate) marked_at: Timestamp, |
| 83 | } | 84 | } |
| 84 | 85 | ||
| 85 | impl MealAttendance { | 86 | impl MealAttendance { |
| @@ -106,102 +107,6 @@ impl MealAttendance { | |||
| 106 | pub fn get_marked_at(&self) -> Timestamp { | 107 | pub fn get_marked_at(&self) -> Timestamp { |
| 107 | self.marked_at | 108 | self.marked_at |
| 108 | } | 109 | } |
| 109 | - | ||
| 110 | - /// Record (or overwrite) whether `student` ate off `menu`. One row per | ||
| 111 | - /// pair by construction, so a correction is the same UPSERT flipping the | ||
| 112 | - /// status. No ledger line, ever — see the module header. | ||
| 113 | - /// | ||
| 114 | - /// `NotFound` = the menu is gone, and the mark was *not* written. The mark | ||
| 115 | - /// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to | ||
| 116 | - /// the menu row rather than a read the write then trusts: a delete racing | ||
| 117 | - /// this one touches the very key this transaction bumps, and the store | ||
| 118 | - /// refuses to commit both. Guarding by reading the menu — even as the | ||
| 119 | - /// `UPSERT`'s own target — did not survive that race: the read saw a row | ||
| 120 | - /// [`Menu::delete`](crate::domain::menu::Menu::delete) had deleted but not | ||
| 121 | - /// yet committed, its sweep ran on a snapshot predating this insert, and the | ||
| 122 | - /// mark outlived its menu with neither caller told anything (measured 378 of | ||
| 123 | - /// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, | ||
| 124 | - /// republishing that day and slot then resurrected it as a mark on the new | ||
| 125 | - /// menu. | ||
| 126 | - /// | ||
| 127 | - /// The bump costs a booking in flight one re-read (its seat claim asserts | ||
| 128 | - /// the revision it priced against) — the same tax every dish write already | ||
| 129 | - /// levies, and it lands after the cutoff on a meal being served, where | ||
| 130 | - /// bookings are rare. | ||
| 131 | - pub async fn mark( | ||
| 132 | - menu: &MenuId, | ||
| 133 | - student: &UserId, | ||
| 134 | - status: MealAttendanceStatus, | ||
| 135 | - marked_by: &UserId, | ||
| 136 | - db: &Database, | ||
| 137 | - ) -> Result<MealAttendance, AppError> { | ||
| 138 | - let row = MealAttendance { | ||
| 139 | - id: MealAttendanceId::composite(menu, student), | ||
| 140 | - menu: menu.clone(), | ||
| 141 | - student: student.clone(), | ||
| 142 | - status, | ||
| 143 | - marked_by: marked_by.clone(), | ||
| 144 | - marked_at: Timestamp::now(), | ||
| 145 | - }; | ||
| 146 | - // Admissible for the retry loop inside: the id is bijective with the | ||
| 147 | - // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` | ||
| 148 | - // resolves onto the row that index already points at instead of | ||
| 149 | - // colliding with it — it can never answer "already exists", and a | ||
| 150 | - // re-sent round writes the identical row. | ||
| 151 | - bump_menu_and_write( | ||
| 152 | - menu, | ||
| 153 | - "UPSERT $id CONTENT $row RETURN AFTER", | ||
| 154 | - vec![ | ||
| 155 | - ("id".into(), row.id.record().into_value()), | ||
| 156 | - ("row".into(), row.into_value()), | ||
| 157 | - ], | ||
| 158 | - db, | ||
| 159 | - ) | ||
| 160 | - .await? | ||
| 161 | - .ok_or_else(|| AppError::Internal("failed to record the mark".into())) | ||
| 162 | - } | ||
| 163 | - | ||
| 164 | - /// The kitchen's list for one menu. | ||
| 165 | - pub async fn list_for_menu( | ||
| 166 | - menu: &MenuId, | ||
| 167 | - limit: Option<i64>, | ||
| 168 | - offset: i64, | ||
| 169 | - db: &Database, | ||
| 170 | - ) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 171 | - PagedList::new( | ||
| 172 | - "meal_attendance WHERE menu = $menu", | ||
| 173 | - "ORDER BY marked_at DESC, id DESC", | ||
| 174 | - ) | ||
| 175 | - .bind("menu", menu.record()) | ||
| 176 | - .run(limit, offset, db) | ||
| 177 | - .await | ||
| 178 | - } | ||
| 179 | - | ||
| 180 | - /// One student's marks, newest first. `from`/`to` are inclusive | ||
| 181 | - /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, | ||
| 182 | - /// which is chronological for that format (see [`MenuDate`]), and the link | ||
| 183 | - /// is followed rather than denormalized so a row can never disagree with | ||
| 184 | - /// the menu it belongs to. | ||
| 185 | - pub async fn list_for_student( | ||
| 186 | - student: &UserId, | ||
| 187 | - from: Option<&MenuDate>, | ||
| 188 | - to: Option<&MenuDate>, | ||
| 189 | - limit: Option<i64>, | ||
| 190 | - offset: i64, | ||
| 191 | - db: &Database, | ||
| 192 | - ) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 193 | - PagedList::new( | ||
| 194 | - "meal_attendance WHERE student = $usr \ | ||
| 195 | - AND ($from = NONE OR menu.date >= $from) \ | ||
| 196 | - AND ($to = NONE OR menu.date <= $to)", | ||
| 197 | - "ORDER BY marked_at DESC, id DESC", | ||
| 198 | - ) | ||
| 199 | - .bind("usr", student.record()) | ||
| 200 | - .bind("from", from.map(|date| date.as_str().to_string())) | ||
| 201 | - .bind("to", to.map(|date| date.as_str().to_string())) | ||
| 202 | - .run(limit, offset, db) | ||
| 203 | - .await | ||
| 204 | - } | ||
| 205 | } | 110 | } |
| 206 | 111 | ||
| 207 | #[cfg(test)] | 112 | #[cfg(test)] |
src/domain/meal_ledger.rsmodified+29 -303
| @@ -49,27 +49,25 @@ | |||
| 49 | //! here: the seat was reserved and the food was cooked. | 49 | //! here: the seat was reserved and the food was cooked. |
| 50 | //! | 50 | //! |
| 51 | //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. | 51 | //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. |
| 52 | +//! | ||
| 53 | +//! The writes and the SUM/balance reads live in [`crate::db::meal_ledger`]; | ||
| 54 | +//! the charge/reversal and credit workflows in | ||
| 55 | +//! [`crate::service::meal_ledger`]. | ||
| 52 | 56 | ||
| 53 | use std::sync::LazyLock; | 57 | use std::sync::LazyLock; |
| 54 | 58 | ||
| 55 | -use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; | 59 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 56 | use ulid::Generator; | 60 | use ulid::Generator; |
| 57 | 61 | ||
| 58 | use crate::constant::{ | 62 | use crate::constant::{ |
| 59 | - CAS_UPDATE_RETRIES, MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, | 63 | + MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, |
| 60 | - MEAL_LEDGER_TABLE, | ||
| 61 | }; | 64 | }; |
| 62 | -use crate::database::{Database, lost_the_race}; | ||
| 63 | -use crate::domain::meal_booking::{MealBooking, MealBookingId}; | ||
| 64 | -use crate::domain::menu::MenuId; | ||
| 65 | -use crate::domain::menu_dish::MenuDish; | ||
| 66 | -use crate::db::page::PagedList; | ||
| 67 | // The client-chosen idempotence key both ledgers take — one grammar, one | 65 | // The client-chosen idempotence key both ledgers take — one grammar, one |
| 68 | // validator, one type, rather than a second newtype that could drift from it. | 66 | // validator, one type, rather than a second newtype that could drift from it. |
| 69 | use crate::domain::payment_ledger::PaymentRequestKey; | 67 | use crate::domain::payment_ledger::PaymentRequestKey; |
| 70 | use crate::domain::timestamp::Timestamp; | 68 | use crate::domain::timestamp::Timestamp; |
| 71 | use crate::domain::user::UserId; | 69 | use crate::domain::user::UserId; |
| 72 | -use crate::error::{AppError, ValidationError}; | 70 | +use crate::error::ValidationError; |
| 73 | use crate::validate::validate_optional; | 71 | use crate::validate::validate_optional; |
| 74 | 72 | ||
| 75 | /// Mints ledger ids in write order — `Ulid::new()`'s random low bits sort | 73 | /// Mints ledger ids in write order — `Ulid::new()`'s random low bits sort |
| @@ -95,13 +93,18 @@ impl MealLedgerId { | |||
| 95 | } | 93 | } |
| 96 | 94 | ||
| 97 | /// The one line a booking attempt may ever write of this `kind` — a | 95 | /// The one line a booking attempt may ever write of this `kind` — a |
| 98 | - /// deterministic id, exactly like [`MealBookingId::composite`]. Two racing | 96 | + /// deterministic id, exactly like [`MealBookingId::composite`](crate::domain::meal_booking::MealBookingId::composite). |
| 97 | + /// Two racing | ||
| 99 | /// `POST`s of one seat derive the *same* id and so cannot become two | 98 | /// `POST`s of one seat derive the *same* id and so cannot become two |
| 100 | /// charges: idempotence rests on identity, never on a scan that a | 99 | /// charges: idempotence rests on identity, never on a scan that a |
| 101 | /// concurrent writer can slip past. The `attempt` counter is what keeps a | 100 | /// concurrent writer can slip past. The `attempt` counter is what keeps a |
| 102 | /// re-book after a cancel a genuinely fresh charge. Booking keys are | 101 | /// re-book after a cancel a genuinely fresh charge. Booking keys are |
| 103 | /// `<ulid>_<ulid>`, so the `c`/`r` marker keeps the two kinds apart. | 102 | /// `<ulid>_<ulid>`, so the `c`/`r` marker keeps the two kinds apart. |
| 104 | - pub fn for_attempt(booking: &MealBookingId, attempt: i64, kind: MealLedgerKind) -> Self { | 103 | + pub fn for_attempt( |
| 104 | + booking: &crate::domain::meal_booking::MealBookingId, | ||
| 105 | + attempt: i64, | ||
| 106 | + kind: MealLedgerKind, | ||
| 107 | + ) -> Self { | ||
| 105 | let marker = match kind { | 108 | let marker = match kind { |
| 106 | MealLedgerKind::Charge => 'c', | 109 | MealLedgerKind::Charge => 'c', |
| 107 | MealLedgerKind::Reversal => 'r', | 110 | MealLedgerKind::Reversal => 'r', |
| @@ -143,17 +146,6 @@ impl MealLedgerId { | |||
| 143 | } | 146 | } |
| 144 | } | 147 | } |
| 145 | 148 | ||
| 146 | -/// Did this `CREATE` fail *only* because the row is already there? Matched on | ||
| 147 | -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text | ||
| 148 | -/// and never on "any database error", because swallowing a real fault in money | ||
| 149 | -/// code would be far worse than the 500 it saves. | ||
| 150 | -fn is_duplicate_record(error: &surrealdb::Error) -> bool { | ||
| 151 | - matches!( | ||
| 152 | - error.already_exists_details(), | ||
| 153 | - Some(AlreadyExistsError::Record { .. }) | ||
| 154 | - ) | ||
| 155 | -} | ||
| 156 | - | ||
| 157 | /// The bare key of a record id — how every id leaves this API. | 149 | /// The bare key of a record id — how every id leaves this API. |
| 158 | fn key_of(record: &RecordId) -> &str { | 150 | fn key_of(record: &RecordId) -> &str { |
| 159 | match &record.key { | 151 | match &record.key { |
| @@ -184,7 +176,7 @@ impl MealLedgerKind { | |||
| 184 | 176 | ||
| 185 | /// How the line folds into the balance: a charge is the only thing that | 177 | /// How the line folds into the balance: a charge is the only thing that |
| 186 | /// takes money away. This is the *single* place the sign convention lives. | 178 | /// takes money away. This is the *single* place the sign convention lives. |
| 187 | - fn sign(self) -> i64 { | 179 | + pub(crate) fn sign(self) -> i64 { |
| 188 | match self { | 180 | match self { |
| 189 | MealLedgerKind::Charge => -1, | 181 | MealLedgerKind::Charge => -1, |
| 190 | MealLedgerKind::Credit | MealLedgerKind::Reversal => 1, | 182 | MealLedgerKind::Credit | MealLedgerKind::Reversal => 1, |
| @@ -249,17 +241,17 @@ impl LedgerNote { | |||
| 249 | 241 | ||
| 250 | #[derive(Debug, Clone, SurrealValue)] | 242 | #[derive(Debug, Clone, SurrealValue)] |
| 251 | pub struct MealLedger { | 243 | pub struct MealLedger { |
| 252 | - id: MealLedgerId, | 244 | + pub(crate) id: MealLedgerId, |
| 253 | - student: UserId, | 245 | + pub(crate) student: UserId, |
| 254 | - kind: MealLedgerKind, | 246 | + pub(crate) kind: MealLedgerKind, |
| 255 | - amount_minor: LedgerAmount, | 247 | + pub(crate) amount_minor: LedgerAmount, |
| 256 | /// What caused the line: a charge points at its `meal_booking`, a reversal | 248 | /// What caused the line: a charge points at its `meal_booking`, a reversal |
| 257 | /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. | 249 | /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. |
| 258 | - source: Option<RecordId>, | 250 | + pub(crate) source: Option<RecordId>, |
| 259 | - method: Option<LedgerMethod>, | 251 | + pub(crate) method: Option<LedgerMethod>, |
| 260 | - note: Option<LedgerNote>, | 252 | + pub(crate) note: Option<LedgerNote>, |
| 261 | - recorded_by: UserId, | 253 | + pub(crate) recorded_by: UserId, |
| 262 | - created_at: Timestamp, | 254 | + pub(crate) created_at: Timestamp, |
| 263 | } | 255 | } |
| 264 | 256 | ||
| 265 | impl MealLedger { | 257 | impl MealLedger { |
| @@ -300,95 +292,6 @@ impl MealLedger { | |||
| 300 | self.created_at | 292 | self.created_at |
| 301 | } | 293 | } |
| 302 | 294 | ||
| 303 | - /// The only writer: one `CREATE`, no update path anywhere in this module. | ||
| 304 | - /// | ||
| 305 | - /// A line whose id already exists is left exactly as it is — the row wins, | ||
| 306 | - /// the write is dropped. That is what makes a deterministic id (see | ||
| 307 | - /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same | ||
| 308 | - /// append is a no-op, never a second line and never an edit of the first. | ||
| 309 | - /// The point read is on the id itself, so unlike a scan it cannot miss a | ||
| 310 | - /// row a concurrent writer just made — but it is only a fast path. The | ||
| 311 | - /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves | ||
| 312 | - /// the row untouched, so the writer that lost the race reads back the | ||
| 313 | - /// winner's line instead of failing the request with a 500. | ||
| 314 | - /// | ||
| 315 | - /// A *write conflict* is the same race decided one layer down — two | ||
| 316 | - /// appends of one id arriving together are no longer serialized by a | ||
| 317 | - /// process-wide lock, so the store aborts one as retryable instead of | ||
| 318 | - /// answering it "already exists". Both are read back the same way, and a | ||
| 319 | - /// conflict that turns out to have written nothing is simply tried again; | ||
| 320 | - /// no path here can write a second line, since the id is the key. | ||
| 321 | - async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> { | ||
| 322 | - if let Some(existing) = Self::read(&row.id, db).await? { | ||
| 323 | - return Ok(existing); | ||
| 324 | - } | ||
| 325 | - let id = row.id.clone(); | ||
| 326 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 327 | - match db.create(id.record()).content(row.clone()).await { | ||
| 328 | - Ok(Some(created)) => return Ok(created), | ||
| 329 | - Ok(None) => break, | ||
| 330 | - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | ||
| 331 | - if let Some(existing) = Self::read(&id, db).await? { | ||
| 332 | - return Ok(existing); | ||
| 333 | - } | ||
| 334 | - } | ||
| 335 | - Err(e) => return Err(e.into()), | ||
| 336 | - } | ||
| 337 | - } | ||
| 338 | - Err(AppError::Internal("failed to write the ledger line".into())) | ||
| 339 | - } | ||
| 340 | - | ||
| 341 | - pub async fn read(id: &MealLedgerId, db: &Database) -> Result<Option<MealLedger>, AppError> { | ||
| 342 | - Ok(db.select(id.record()).await?) | ||
| 343 | - } | ||
| 344 | - | ||
| 345 | - /// What a seat on `menu` costs *right now*: the sum of its dishes. `None` | ||
| 346 | - /// when the menu is free (or empty) — a zero line is noise, not history. | ||
| 347 | - /// | ||
| 348 | - /// Called before the seat is taken so an unchargeable menu (one summing | ||
| 349 | - /// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of | ||
| 350 | - /// leaving a booked-but-unbilled row behind. | ||
| 351 | - pub async fn price_snapshot( | ||
| 352 | - menu: &MenuId, | ||
| 353 | - db: &Database, | ||
| 354 | - ) -> Result<Option<LedgerAmount>, AppError> { | ||
| 355 | - let total = MenuDish::list_for_menu(menu, db) | ||
| 356 | - .await? | ||
| 357 | - .iter() | ||
| 358 | - .fold(0i64, |sum, dish| { | ||
| 359 | - sum.saturating_add(dish.get_price_minor().as_minor()) | ||
| 360 | - }); | ||
| 361 | - if total == 0 { | ||
| 362 | - return Ok(None); | ||
| 363 | - } | ||
| 364 | - Ok(Some(LedgerAmount::try_new(total)?)) | ||
| 365 | - } | ||
| 366 | - | ||
| 367 | - /// Bill `booking`'s current attempt at the price frozen onto it when that | ||
| 368 | - /// attempt took the seat. | ||
| 369 | - /// | ||
| 370 | - /// The price comes off the *booking row*, never off the menu as it stands | ||
| 371 | - /// now: a seat taken while the menu was free carries `None` forever, so | ||
| 372 | - /// "was free" is a recorded fact and a later dish never bills a seat | ||
| 373 | - /// retroactively. Called from | ||
| 374 | - /// [`book`](crate::service::meal_booking::book) alone, right after the seat | ||
| 375 | - /// was claimed, so the seat and its money move together. | ||
| 376 | - /// | ||
| 377 | - /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate | ||
| 378 | - /// `POST` writes nothing, and an attempt whose charge failed the first time | ||
| 379 | - /// self-heals on the next `POST` of the same seat. | ||
| 380 | - pub async fn charge_booking( | ||
| 381 | - booking: &MealBooking, | ||
| 382 | - recorded_by: &UserId, | ||
| 383 | - db: &Database, | ||
| 384 | - ) -> Result<(), AppError> { | ||
| 385 | - let Some(line) = Self::charge_for(booking, recorded_by) else { | ||
| 386 | - return Ok(()); | ||
| 387 | - }; | ||
| 388 | - Self::append(line, db).await?; | ||
| 389 | - Ok(()) | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | /// The charge `booking`'s current attempt owes — the line | 295 | /// The charge `booking`'s current attempt owes — the line |
| 393 | /// [`claim_and_place`](crate::db::meal_booking::claim_and_place) appends inside the very transaction that | 296 | /// [`claim_and_place`](crate::db::meal_booking::claim_and_place) appends inside the very transaction that |
| 394 | /// takes the seat. `None` when the menu was free, which owes no line. | 297 | /// takes the seat. `None` when the menu was free, which owes no line. |
| @@ -397,7 +300,10 @@ impl MealLedger { | |||
| 397 | /// the caller that writes in one transaction has to make it there. Note the | 300 | /// the caller that writes in one transaction has to make it there. Note the |
| 398 | /// attempt has to be settled *before* the SQL runs, which is why the claim | 301 | /// attempt has to be settled *before* the SQL runs, which is why the claim |
| 399 | /// mints the number itself rather than letting the revival increment it. | 302 | /// mints the number itself rather than letting the revival increment it. |
| 400 | - pub(crate) fn charge_for(booking: &MealBooking, recorded_by: &UserId) -> Option<MealLedger> { | 303 | + pub(crate) fn charge_for( |
| 304 | + booking: &crate::domain::meal_booking::MealBooking, | ||
| 305 | + recorded_by: &UserId, | ||
| 306 | + ) -> Option<MealLedger> { | ||
| 401 | let amount = booking.get_price_minor()?; | 307 | let amount = booking.get_price_minor()?; |
| 402 | Some(MealLedger { | 308 | Some(MealLedger { |
| 403 | id: MealLedgerId::for_attempt( | 309 | id: MealLedgerId::for_attempt( |
| @@ -416,34 +322,6 @@ impl MealLedger { | |||
| 416 | }) | 322 | }) |
| 417 | } | 323 | } |
| 418 | 324 | ||
| 419 | - /// Give the money back for a cancelled `booking`: a new `reversal` line for | ||
| 420 | - /// the charge's exact amount, pointing at it. The charge is never touched. | ||
| 421 | - /// A booking that was never billed (a free menu) reverses nothing, and | ||
| 422 | - /// neither does one whose charge never landed — the reversal is keyed to | ||
| 423 | - /// the very charge it undoes, so it can only exist alongside it. | ||
| 424 | - /// | ||
| 425 | - /// Keyed by `(booking, attempt)` like the charge, so a retried cancel | ||
| 426 | - /// refunds once. The line normally lands *inside* the flip's own | ||
| 427 | - /// transaction | ||
| 428 | - /// ([`release_seat`](crate::db::meal_booking::release_seat)); this path is what heals a | ||
| 429 | - /// seat flipped before that was true, and it is why | ||
| 430 | - /// [`cancel`](crate::service::meal_booking::cancel) replays it on an already-cancelled row instead | ||
| 431 | - /// of refusing it. Nothing else on the API can append the missing line. | ||
| 432 | - pub async fn reverse_booking( | ||
| 433 | - booking: &MealBooking, | ||
| 434 | - recorded_by: &UserId, | ||
| 435 | - db: &Database, | ||
| 436 | - ) -> Result<(), AppError> { | ||
| 437 | - let Some((charge, line)) = Self::reversal_for(booking, recorded_by) else { | ||
| 438 | - return Ok(()); | ||
| 439 | - }; | ||
| 440 | - if Self::read(&charge, db).await?.is_none() { | ||
| 441 | - return Ok(()); | ||
| 442 | - } | ||
| 443 | - Self::append(line, db).await?; | ||
| 444 | - Ok(()) | ||
| 445 | - } | ||
| 446 | - | ||
| 447 | /// The refund `booking`'s current attempt owes, as `(the charge it undoes, | 325 | /// The refund `booking`'s current attempt owes, as `(the charge it undoes, |
| 448 | /// the reversal line)` — the two ids | 326 | /// the reversal line)` — the two ids |
| 449 | /// [`release_seat`](crate::db::meal_booking::release_seat) needs to | 327 | /// [`release_seat`](crate::db::meal_booking::release_seat) needs to |
| @@ -454,7 +332,7 @@ impl MealLedger { | |||
| 454 | /// read, and the caller that writes in one transaction has to make it there | 332 | /// read, and the caller that writes in one transaction has to make it there |
| 455 | /// rather than a round trip earlier. | 333 | /// rather than a round trip earlier. |
| 456 | pub(crate) fn reversal_for( | 334 | pub(crate) fn reversal_for( |
| 457 | - booking: &MealBooking, | 335 | + booking: &crate::domain::meal_booking::MealBooking, |
| 458 | recorded_by: &UserId, | 336 | recorded_by: &UserId, |
| 459 | ) -> Option<(MealLedgerId, MealLedger)> { | 337 | ) -> Option<(MealLedgerId, MealLedger)> { |
| 460 | let amount = booking.get_price_minor()?; | 338 | let amount = booking.get_price_minor()?; |
| @@ -480,117 +358,6 @@ impl MealLedger { | |||
| 480 | }; | 358 | }; |
| 481 | Some((charge, line)) | 359 | Some((charge, line)) |
| 482 | } | 360 | } |
| 483 | - | ||
| 484 | - /// Money in: a payment received, or an opening balance. | ||
| 485 | - /// | ||
| 486 | - /// With a `request_key` the line is keyed by it (see | ||
| 487 | - /// [`MealLedgerId::for_request`]) and the call is **retry-safe**: a client | ||
| 488 | - /// resending the identical body after a timeout gets back the line the | ||
| 489 | - /// first attempt wrote, not a second credit — nothing on this API can edit | ||
| 490 | - /// or delete one, so a doubled credit is corrected only by a compensating | ||
| 491 | - /// line. Without one the id is a fresh ulid and two identical calls are two | ||
| 492 | - /// credits, which is what a desk taking the same amount twice really means. | ||
| 493 | - pub async fn credit( | ||
| 494 | - student: &UserId, | ||
| 495 | - amount_minor: LedgerAmount, | ||
| 496 | - method: Option<LedgerMethod>, | ||
| 497 | - note: Option<LedgerNote>, | ||
| 498 | - request_key: Option<&PaymentRequestKey>, | ||
| 499 | - recorded_by: &UserId, | ||
| 500 | - db: &Database, | ||
| 501 | - ) -> Result<MealLedger, AppError> { | ||
| 502 | - let line = Self::append( | ||
| 503 | - MealLedger { | ||
| 504 | - id: match request_key { | ||
| 505 | - Some(key) => MealLedgerId::for_request(student, key), | ||
| 506 | - None => MealLedgerId::generate(), | ||
| 507 | - }, | ||
| 508 | - student: student.clone(), | ||
| 509 | - kind: MealLedgerKind::Credit, | ||
| 510 | - amount_minor, | ||
| 511 | - source: None, | ||
| 512 | - method, | ||
| 513 | - note, | ||
| 514 | - recorded_by: recorded_by.clone(), | ||
| 515 | - created_at: Timestamp::now(), | ||
| 516 | - }, | ||
| 517 | - db, | ||
| 518 | - ) | ||
| 519 | - .await?; | ||
| 520 | - // A replay is answered from the stored line — but only if it is the | ||
| 521 | - // same money. The same key for a different amount is a client bug, and | ||
| 522 | - // handing back the old line would hide it behind a `201`. Checked on | ||
| 523 | - // what `append` gave back rather than on a read before it: two retries | ||
| 524 | - // arriving together both find no row, and only the id decides which | ||
| 525 | - // one's amount is stored, so a check *before* the write would tell the | ||
| 526 | - // loser its own amount landed. | ||
| 527 | - if request_key.is_some() && line.amount_minor != amount_minor { | ||
| 528 | - return Err(AppError::Conflict( | ||
| 529 | - "this request_key was already used for a different amount", | ||
| 530 | - )); | ||
| 531 | - } | ||
| 532 | - Ok(line) | ||
| 533 | - } | ||
| 534 | - | ||
| 535 | - /// A student's whole statement, newest first. | ||
| 536 | - pub async fn list_for_student( | ||
| 537 | - student: &UserId, | ||
| 538 | - limit: Option<i64>, | ||
| 539 | - offset: i64, | ||
| 540 | - db: &Database, | ||
| 541 | - ) -> Result<(Vec<MealLedger>, i64), AppError> { | ||
| 542 | - PagedList::new( | ||
| 543 | - "meal_ledger WHERE student = $student", | ||
| 544 | - "ORDER BY created_at DESC, id DESC", | ||
| 545 | - ) | ||
| 546 | - .bind("student", student.record()) | ||
| 547 | - .run(limit, offset, db) | ||
| 548 | - .await | ||
| 549 | - } | ||
| 550 | - | ||
| 551 | - /// The derived balance: `credits + reversals - charges`, in minor units. | ||
| 552 | - /// Negative means the student owes the school. Never stored anywhere. | ||
| 553 | - /// | ||
| 554 | - /// **The sum is taken per kind by the database** and only the three totals | ||
| 555 | - /// come back, so a balance read costs the same whether the statement holds | ||
| 556 | - /// four lines or forty thousand. It used to decode and fold every line, and | ||
| 557 | - /// nothing bounds a statement's length but the cycle ceiling | ||
| 558 | - /// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS)) | ||
| 559 | - /// added alongside this: every book/cancel | ||
| 560 | - /// pair appends two permanent rows, and each one was paid for again by | ||
| 561 | - /// every later `GET /meals/balance/*`. | ||
| 562 | - /// | ||
| 563 | - /// **The signs stay here**, applied by the very [`MealLedgerKind::sign`] | ||
| 564 | - /// the documented formula is spelled in. Summing `IF kind = 'charge' THEN | ||
| 565 | - /// -amount …` in SQL would have folded the whole balance in one statement | ||
| 566 | - /// and forked the one rule that decides what money means into a second | ||
| 567 | - /// language, where nothing would fail the day the two disagreed. Grouping | ||
| 568 | - /// instead keeps the aggregate ignorant of signs: it counts kinds, and | ||
| 569 | - /// Rust still says what a kind does. A stored running total was the third | ||
| 570 | - /// option and is a counter that can drift — a bug class this repo closes, | ||
| 571 | - /// not one it opens. | ||
| 572 | - pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> { | ||
| 573 | - let totals: Vec<KindTotal> = db | ||
| 574 | - .query(format!( | ||
| 575 | - "SELECT kind, math::sum(amount_minor) AS total \ | ||
| 576 | - FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" | ||
| 577 | - )) | ||
| 578 | - .bind(("student", student.record())) | ||
| 579 | - .await? | ||
| 580 | - .check()? | ||
| 581 | - .take(0)?; | ||
| 582 | - Ok(totals | ||
| 583 | - .iter() | ||
| 584 | - .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) | ||
| 585 | - } | ||
| 586 | -} | ||
| 587 | - | ||
| 588 | -/// One kind's whole sum, as the `GROUP BY` in [`MealLedger::balance_of`] hands | ||
| 589 | -/// it back — at most three rows, never the lines behind them. | ||
| 590 | -#[derive(Debug, SurrealValue)] | ||
| 591 | -struct KindTotal { | ||
| 592 | - kind: MealLedgerKind, | ||
| 593 | - total: i64, | ||
| 594 | } | 361 | } |
| 595 | 362 | ||
| 596 | #[cfg(test)] | 363 | #[cfg(test)] |
| @@ -634,47 +401,6 @@ mod tests { | |||
| 634 | assert_eq!(balance, 10_000); | 401 | assert_eq!(balance, 10_000); |
| 635 | } | 402 | } |
| 636 | 403 | ||
| 637 | - /// The balance aggregate **against a real server**, and `#[ignore]`d for | ||
| 638 | - /// it: `init_mem`'s embedded engine is not the store this runs on, and an | ||
| 639 | - /// aggregate is exactly where the two are known to differ — a `count()` | ||
| 640 | - /// over an indexed field comes back `{count: N}` from the server and a | ||
| 641 | - /// bare int from memory, and `student` here *is* indexed. This asserts the | ||
| 642 | - /// `GROUP BY` really decodes into [`KindTotal`] and folds to the | ||
| 643 | - /// documented figure, per kind, scoped to one student. | ||
| 644 | - #[tokio::test] | ||
| 645 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 646 | - async fn the_balance_aggregate_decodes_on_a_real_server() { | ||
| 647 | - let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; | ||
| 648 | - db.query( | ||
| 649 | - "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ | ||
| 650 | - amount_minor = 10000, recorded_by = user:adm, created_at = 1; | ||
| 651 | - CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ | ||
| 652 | - amount_minor = 4500, recorded_by = user:adm, created_at = 2; | ||
| 653 | - CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ | ||
| 654 | - amount_minor = 1500, recorded_by = user:adm, created_at = 3; | ||
| 655 | - CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ | ||
| 656 | - amount_minor = 4500, recorded_by = user:adm, created_at = 4; | ||
| 657 | - CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ | ||
| 658 | - amount_minor = 777, recorded_by = user:adm, created_at = 5;", | ||
| 659 | - ) | ||
| 660 | - .await | ||
| 661 | - .unwrap() | ||
| 662 | - .check() | ||
| 663 | - .unwrap(); | ||
| 664 | - let ali = UserId::from_key("ali"); | ||
| 665 | - assert_eq!( | ||
| 666 | - MealLedger::balance_of(&ali, &db).await.unwrap(), | ||
| 667 | - 10_000 - 4_500 - 1_500 + 4_500 | ||
| 668 | - ); | ||
| 669 | - // Somebody with no lines at all: no groups come back, not an error. | ||
| 670 | - assert_eq!( | ||
| 671 | - MealLedger::balance_of(&UserId::from_key("nobody"), &db) | ||
| 672 | - .await | ||
| 673 | - .unwrap(), | ||
| 674 | - 0 | ||
| 675 | - ); | ||
| 676 | - } | ||
| 677 | - | ||
| 678 | #[test] | 404 | #[test] |
| 679 | fn an_amount_is_positive_and_capped() { | 405 | fn an_amount_is_positive_and_capped() { |
| 680 | assert!(LedgerAmount::try_new(0).is_err()); | 406 | assert!(LedgerAmount::try_new(0).is_err()); |
src/domain/menu.rsmodified+21 -623
| @@ -1,6 +1,6 @@ | |||
| 1 | //! A published menu: what the kitchen serves on one calendar day in one meal | 1 | //! A published menu: what the kitchen serves on one calendar day in one meal |
| 2 | //! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)), | 2 | //! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)), |
| 3 | -//! and bookings will hang off its `capacity`. | 3 | +//! and bookings hang off its `capacity`. |
| 4 | //! | 4 | //! |
| 5 | //! Two things are deliberate: | 5 | //! Two things are deliberate: |
| 6 | //! | 6 | //! |
| @@ -9,43 +9,17 @@ | |||
| 9 | //! day is only one school's day. | 9 | //! day is only one school's day. |
| 10 | //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must | 10 | //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must |
| 11 | //! never rewrite a menu already published under it. | 11 | //! never rewrite a menu already published under it. |
| 12 | +//! | ||
| 13 | +//! The queries live in [`crate::db::menu`]; the kitchen workflows (and the | ||
| 14 | +//! dish-cap lock) in [`crate::service::menu`]. | ||
| 12 | 15 | ||
| 13 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | 16 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 14 | -use tokio::sync::Mutex; | ||
| 15 | 17 | ||
| 16 | -use crate::constant::{ | 18 | +use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE, SLOT_REF_TABLE}; |
| 17 | - MAX_MENU_CAPACITY, MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_TABLE, | ||
| 18 | - MENU_VERSION_FIELD, REF_COUNT_FIELD, SLOT_REF_TABLE, | ||
| 19 | -}; | ||
| 20 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 21 | -use crate::db::cap; | ||
| 22 | -use crate::db::page::PagedList; | ||
| 23 | use crate::domain::settings::MealSlotDef; | 19 | use crate::domain::settings::MealSlotDef; |
| 24 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 25 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 26 | -use crate::error::{AppError, ValidationError}; | 22 | +use crate::error::ValidationError; |
| 27 | - | ||
| 28 | -/// Serializes what is left that counts rows against one menu: the dish cap | ||
| 29 | -/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not | ||
| 30 | -/// conflict-check). Publishing no longer needs it — the day+slot *is* the | ||
| 31 | -/// record id — and neither does a booking, a menu delete, or the settings | ||
| 32 | -/// slot-removal guard: those went to conditional single-record writes | ||
| 33 | -/// ([`crate::db::cap`]), which the store decides as this lock cannot. | ||
| 34 | -// | ||
| 35 | -// corner-cut: the dish cap therefore rests on this lock alone — a dish write | ||
| 36 | -// added without taking it reopens the count-then-write hole silently. Closing | ||
| 37 | -// it properly is another `cap` counter (`dish_count` on the menu row) plus its | ||
| 38 | -// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was | ||
| 39 | -// not worth the column here. | ||
| 40 | -/// | ||
| 41 | -/// **A leaf**: every dish write held under it moves the menu's revision inside | ||
| 42 | -/// its *own* transaction ([`bump_menu_and_write`]), | ||
| 43 | -/// so no path under this lock reaches `cap`'s counter lock any more — it did | ||
| 44 | -/// while the bump was a `cap` call of its own. Should one ever need both, the | ||
| 45 | -/// order is `MENU_LOCK` → `CLAIM_LOCK` and nothing may take this lock while | ||
| 46 | -/// holding a counter lock: that is the invariant a new caller must keep, and it | ||
| 47 | -/// is what would keep the pair deadlock-free. | ||
| 48 | -pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 49 | 23 | ||
| 50 | /// The reference counter for one meal slot — how many menus are published under | 24 | /// The reference counter for one meal slot — how many menus are published under |
| 51 | /// that name, and whether the school has retired it (see | 25 | /// that name, and whether the school has retired it (see |
| @@ -57,72 +31,6 @@ pub(crate) fn slot_ref(slot: &str) -> RecordId { | |||
| 57 | RecordId::new(SLOT_REF_TABLE, slot) | 31 | RecordId::new(SLOT_REF_TABLE, slot) |
| 58 | } | 32 | } |
| 59 | 33 | ||
| 60 | -/// Move the menu's revision **and** run `statement` — a write to something | ||
| 61 | -/// hanging off a menu — in one transaction, handing back the row it returned. | ||
| 62 | -/// | ||
| 63 | -/// What a seat on that menu costs, or who is recorded against it, is about to | ||
| 64 | -/// change, so any booking that priced itself against the old revision has to | ||
| 65 | -/// re-read. The bump cannot be a query of its own: in the gap the menu row | ||
| 66 | -/// carries the *new* revision with the *old* price, and a booking reading there | ||
| 67 | -/// passes the very CAS that exists to refuse it — a seat billed a price the | ||
| 68 | -/// menu had already left, or admitted past a capacity that had already shrunk. | ||
| 69 | -/// | ||
| 70 | -/// The bump is also what makes the menu's **existence** part of the write | ||
| 71 | -/// ([`MenuDish::create`](crate::domain::menu_dish::MenuDish::create) leans on | ||
| 72 | -/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, | ||
| 73 | -/// and a delete racing this one touches the very key this transaction writes, | ||
| 74 | -/// so the two cannot both commit. Reading the menu instead — even as the write | ||
| 75 | -/// statement's own target — does not survive that race: the read sees a row the | ||
| 76 | -/// delete has not committed yet, and [`Menu::delete`]'s sweep ran on a snapshot | ||
| 77 | -/// predating this insert, so both commit and the child outlives its menu | ||
| 78 | -/// (measured 378 of 3600 raced rounds before this shape was shared). | ||
| 79 | -/// | ||
| 80 | -/// Deliberately on every such write, not only the ones that move | ||
| 81 | -/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies | ||
| 82 | -/// to every write cannot be forgotten by the next one added. | ||
| 83 | -/// | ||
| 84 | -/// Admissible for [`transaction_with_retry`] as long as `statement` is: an | ||
| 85 | -/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never | ||
| 86 | -/// answer "already exists", and neither can an `UPSERT` whose id is bijective | ||
| 87 | -/// with every unique tuple its table indexes — a lost round wrote nothing, so | ||
| 88 | -/// re-sending it is the recovery. | ||
| 89 | -pub(crate) async fn bump_menu_and_write<T: SurrealValue>( | ||
| 90 | - menu: &MenuId, | ||
| 91 | - statement: &str, | ||
| 92 | - mut bindings: Vec<(String, Value)>, | ||
| 93 | - db: &Database, | ||
| 94 | -) -> Result<Option<T>, AppError> { | ||
| 95 | - bindings.push(("menu".into(), menu.record().into_value())); | ||
| 96 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 97 | - db, | ||
| 98 | - &format!( | ||
| 99 | - "BEGIN TRANSACTION; | ||
| 100 | - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ | ||
| 101 | - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 102 | - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; | ||
| 103 | - LET $row = ({statement}); | ||
| 104 | - RETURN $row; | ||
| 105 | - COMMIT TRANSACTION;" | ||
| 106 | - ), | ||
| 107 | - &bindings, | ||
| 108 | - &["no_menu"], | ||
| 109 | - ) | ||
| 110 | - .await?; | ||
| 111 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 112 | - // executed" — only the THROW's own slot names the reason. | ||
| 113 | - if errors | ||
| 114 | - .values() | ||
| 115 | - .any(|error| error.to_string().contains("no_menu")) | ||
| 116 | - { | ||
| 117 | - return Err(AppError::NotFound); | ||
| 118 | - } | ||
| 119 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 120 | - return Err(error.into()); | ||
| 121 | - } | ||
| 122 | - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. | ||
| 123 | - Ok(result.take::<Vec<T>>(4)?.into_iter().next()) | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 34 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 127 | pub struct MenuId(RecordId); | 35 | pub struct MenuId(RecordId); |
| 128 | 36 | ||
| @@ -276,18 +184,19 @@ pub fn validate_capacity(value: Option<i64>) -> Result<(), ValidationError> { | |||
| 276 | 184 | ||
| 277 | #[derive(Debug, Clone, SurrealValue)] | 185 | #[derive(Debug, Clone, SurrealValue)] |
| 278 | pub struct Menu { | 186 | pub struct Menu { |
| 279 | - id: MenuId, | 187 | + pub(crate) id: MenuId, |
| 280 | - date: MenuDate, | 188 | + pub(crate) date: MenuDate, |
| 281 | - slot: MenuSlot, | 189 | + pub(crate) slot: MenuSlot, |
| 282 | - capacity: Option<i64>, | 190 | + pub(crate) capacity: Option<i64>, |
| 283 | - /// The menu's revision (see [`MENU_VERSION_FIELD`]). Absent on rows written | 191 | + /// The menu's revision (see [`MENU_VERSION_FIELD`](crate::constant::MENU_VERSION_FIELD)). |
| 284 | - /// before the column existed, which reads as revision zero — the same thing | 192 | + /// Absent on rows written before the column existed, which reads as |
| 285 | - /// `(version ?? 0)` says in the claim's `WHERE`. The seat counter is | 193 | + /// revision zero — the same thing `(version ?? 0)` says in the claim's |
| 286 | - /// deliberately *not* here: it is the database's to own, and a whole-row | 194 | + /// `WHERE`. The seat counter is deliberately *not* here: it is the |
| 287 | - /// save must never carry a stale copy of it. | 195 | + /// database's to own, and a whole-row save must never carry a stale copy |
| 288 | - version: Option<i64>, | 196 | + /// of it. |
| 289 | - created_by: UserId, | 197 | + pub(crate) version: Option<i64>, |
| 290 | - created_at: Timestamp, | 198 | + pub(crate) created_by: UserId, |
| 199 | + pub(crate) created_at: Timestamp, | ||
| 291 | } | 200 | } |
| 292 | 201 | ||
| 293 | impl Menu { | 202 | impl Menu { |
| @@ -321,209 +230,12 @@ impl Menu { | |||
| 321 | pub fn get_created_at(&self) -> Timestamp { | 230 | pub fn get_created_at(&self) -> Timestamp { |
| 322 | self.created_at | 231 | self.created_at |
| 323 | } | 232 | } |
| 324 | - | ||
| 325 | - /// Publish a menu. Refused (409) when the day+slot already carries one. | ||
| 326 | - /// | ||
| 327 | - /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the | ||
| 328 | - /// refusal is decided by the store rather than by a check a concurrent | ||
| 329 | - /// publish can outrun: two publishes of the same meal write one id, and the loser's | ||
| 330 | - /// "already exists" becomes the same 409. The pre-check stays for the | ||
| 331 | - /// ordinary case — and for menus published before ids were derived, whose | ||
| 332 | - /// ULID key no new publish can collide with. | ||
| 333 | - pub async fn create( | ||
| 334 | - date: MenuDate, | ||
| 335 | - slot: MenuSlot, | ||
| 336 | - capacity: Option<i64>, | ||
| 337 | - created_by: &UserId, | ||
| 338 | - db: &Database, | ||
| 339 | - ) -> Result<Menu, AppError> { | ||
| 340 | - let taken = AppError::Conflict("a menu is already published for that date and slot"); | ||
| 341 | - if Self::find(&date, &slot, db).await?.is_some() { | ||
| 342 | - return Err(taken); | ||
| 343 | - } | ||
| 344 | - // The menu takes a reference on its slot, which is what stops the slot | ||
| 345 | - // being dropped from the settings while this menu (whose slot is only | ||
| 346 | - // snapshotted text) still points at it. Claimed *inside* the write's own | ||
| 347 | - // transaction: a claim of its own could land and the row then fail to, | ||
| 348 | - // leaving the slot counted by a menu that does not exist — a slot | ||
| 349 | - // nobody can ever retire, and no crash window is small enough for that. | ||
| 350 | - let counter = slot_ref(slot.as_str()); | ||
| 351 | - let menu = Menu { | ||
| 352 | - id: MenuId::for_slot(&date, &slot), | ||
| 353 | - date, | ||
| 354 | - slot, | ||
| 355 | - capacity, | ||
| 356 | - version: Some(0), | ||
| 357 | - created_by: created_by.clone(), | ||
| 358 | - created_at: Timestamp::now(), | ||
| 359 | - }; | ||
| 360 | - let id = menu.id.record(); | ||
| 361 | - match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { | ||
| 362 | - cap::ClaimedRef::Made(created) => Ok(created), | ||
| 363 | - cap::ClaimedRef::Duplicate => Err(taken), | ||
| 364 | - cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( | ||
| 365 | - "the '{}' meal slot has been removed from the school's settings", | ||
| 366 | - menu.slot.as_str() | ||
| 367 | - ))), | ||
| 368 | - } | ||
| 369 | - } | ||
| 370 | - | ||
| 371 | - pub async fn read(id: &MenuId, db: &Database) -> Result<Option<Menu>, AppError> { | ||
| 372 | - Ok(db.select(id.record()).await?) | ||
| 373 | - } | ||
| 374 | - | ||
| 375 | - /// The menu for one day and slot, if any — the uniqueness check. | ||
| 376 | - pub async fn find( | ||
| 377 | - date: &MenuDate, | ||
| 378 | - slot: &MenuSlot, | ||
| 379 | - db: &Database, | ||
| 380 | - ) -> Result<Option<Menu>, AppError> { | ||
| 381 | - let mut result = db | ||
| 382 | - .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") | ||
| 383 | - .bind(("date", date.as_str().to_string())) | ||
| 384 | - .bind(("slot", slot.as_str().to_string())) | ||
| 385 | - .await? | ||
| 386 | - .check()?; | ||
| 387 | - Ok(result.take::<Vec<Menu>>(0)?.into_iter().next()) | ||
| 388 | - } | ||
| 389 | - | ||
| 390 | - /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; | ||
| 391 | - /// either may be omitted. The comparison is lexical, which is chronological | ||
| 392 | - /// for this format. | ||
| 393 | - pub async fn list( | ||
| 394 | - from: Option<&MenuDate>, | ||
| 395 | - to: Option<&MenuDate>, | ||
| 396 | - limit: Option<i64>, | ||
| 397 | - offset: i64, | ||
| 398 | - db: &Database, | ||
| 399 | - ) -> Result<(Vec<Menu>, i64), AppError> { | ||
| 400 | - PagedList::new( | ||
| 401 | - "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", | ||
| 402 | - "ORDER BY date DESC, slot ASC, id DESC", | ||
| 403 | - ) | ||
| 404 | - .bind("from", from.map(|date| date.as_str().to_string())) | ||
| 405 | - .bind("to", to.map(|date| date.as_str().to_string())) | ||
| 406 | - .run(limit, offset, db) | ||
| 407 | - .await | ||
| 408 | - } | ||
| 409 | - | ||
| 410 | - /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, | ||
| 411 | - /// because moving a published menu to another day is a different menu. | ||
| 412 | - /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. | ||
| 413 | - /// | ||
| 414 | - /// The revision moves **in the same statement** as the cap, indivisibly: a | ||
| 415 | - /// booking claims its seat against the revision | ||
| 416 | - /// it read the cap at, so a shrink that bumped in a query of its own left a | ||
| 417 | - /// window where the row carried the *new* revision and the *old* cap — and | ||
| 418 | - /// a booking arriving there passes a CAS meant to refuse it, over-admitting | ||
| 419 | - /// by exactly the seats in flight. | ||
| 420 | - pub async fn update( | ||
| 421 | - self, | ||
| 422 | - capacity: Option<Option<i64>>, | ||
| 423 | - db: &Database, | ||
| 424 | - ) -> Result<Menu, AppError> { | ||
| 425 | - let Some(capacity) = capacity else { | ||
| 426 | - // A PATCH carrying nothing writes nothing and bumps nothing: no | ||
| 427 | - // booking's price or cap has moved, so none owes a re-read. | ||
| 428 | - return Self::read(&self.id, db).await?.ok_or(AppError::NotFound); | ||
| 429 | - }; | ||
| 430 | - let sql = format!( | ||
| 431 | - "UPDATE $id SET capacity = $capacity, \ | ||
| 432 | - {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" | ||
| 433 | - ); | ||
| 434 | - // One counter write in flight at a time, like every other one. | ||
| 435 | - let _guard = cap::counter_lock().await; | ||
| 436 | - write_with_retry::<Menu>( | ||
| 437 | - db, | ||
| 438 | - &sql, | ||
| 439 | - &[ | ||
| 440 | - ("id".into(), self.id.record().into_value()), | ||
| 441 | - ("capacity".into(), capacity.into_value()), | ||
| 442 | - ], | ||
| 443 | - ) | ||
| 444 | - .await? | ||
| 445 | - .into_iter() | ||
| 446 | - .next() | ||
| 447 | - .ok_or(AppError::NotFound) | ||
| 448 | - } | ||
| 449 | - | ||
| 450 | - /// Delete the menu and the dishes on it — a dish has no meaning without | ||
| 451 | - /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. | ||
| 452 | - /// | ||
| 453 | - /// Refused (409) while a seat is still held, and the *row itself* decides | ||
| 454 | - /// that: the delete carries the seat counter in its `WHERE`, so a booking | ||
| 455 | - /// landing at that instant either takes its seat before | ||
| 456 | - /// the delete (which then finds a non-zero counter and refuses) or after it | ||
| 457 | - /// (and finds no menu). A read-then-delete pair had a window where both | ||
| 458 | - /// happened — a paid seat on a menu that no longer exists. | ||
| 459 | - /// | ||
| 460 | - /// The slot gets its reference back in that same transaction — a slot no | ||
| 461 | - /// menu is published for any more may leave the settings again, and the | ||
| 462 | - /// `FOR` runs only over a row the guard actually took. Released afterwards | ||
| 463 | - /// in a query of its own, a crash between the two left the slot counted by | ||
| 464 | - /// a menu that no longer exists: a slot nobody can retire. | ||
| 465 | - /// | ||
| 466 | - /// The marks go in that same `FOR`, for a sharper reason than tidiness: | ||
| 467 | - /// [`MenuId::for_slot`] is deterministic, so republishing the same day and | ||
| 468 | - /// slot mints the *same* record id. A mark left behind would come back as a | ||
| 469 | - /// mark on the new menu — the kitchen reading "served" for a student who | ||
| 470 | - /// never came — and until then the student's own report cites a menu that | ||
| 471 | - /// is gone. Attendance carries no money and no counter, so it is safe to | ||
| 472 | - /// drop; cancelled *bookings* deliberately stay, because their `attempt` | ||
| 473 | - /// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut | ||
| 474 | - /// those and a re-book on a republished menu would reuse a charge id the | ||
| 475 | - /// ledger already holds, and the append (idempotent by design) would bill | ||
| 476 | - /// the seat nothing. | ||
| 477 | - /// | ||
| 478 | - /// The dishes ride in that `FOR` too, and for the same reason as the marks: | ||
| 479 | - /// run after the transaction committed, a crash between the two orphaned | ||
| 480 | - /// them on a record id republishing the day and slot mints again — a new | ||
| 481 | - /// menu serving (and pricing) the old one's food. | ||
| 482 | - pub async fn delete(self, db: &Database) -> Result<Menu, AppError> { | ||
| 483 | - let sql = format!( | ||
| 484 | - "BEGIN TRANSACTION; | ||
| 485 | - LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); | ||
| 486 | - FOR $row IN ($gone ?? []) {{ | ||
| 487 | - UPSERT $counter SET {REF_COUNT_FIELD} = \ | ||
| 488 | - math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 489 | - DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; | ||
| 490 | - DELETE {MENU_DISH_TABLE} WHERE menu = $id; | ||
| 491 | - }}; | ||
| 492 | - RETURN $gone; | ||
| 493 | - COMMIT TRANSACTION;" | ||
| 494 | - ); | ||
| 495 | - // `slot` is a `READONLY` column, so this counter is the one the deleted | ||
| 496 | - // row carries. Nothing here can answer "already exists" — the `UPSERT` | ||
| 497 | - // is keyed by a slot name on a table with no `UNIQUE` index, so it | ||
| 498 | - // resolves onto the row it names ([`transaction_with_retry`]). | ||
| 499 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 500 | - db, | ||
| 501 | - &sql, | ||
| 502 | - &[ | ||
| 503 | - ("id".into(), self.id.record().into_value()), | ||
| 504 | - ("counter".into(), slot_ref(self.slot.as_str()).into_value()), | ||
| 505 | - ], | ||
| 506 | - &[], | ||
| 507 | - ) | ||
| 508 | - .await?; | ||
| 509 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 510 | - return Err(error.into()); | ||
| 511 | - } | ||
| 512 | - // BEGIN, the LET and the FOR take a slot each. | ||
| 513 | - let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else { | ||
| 514 | - // Nothing back: either seats are held, or the menu is already gone. | ||
| 515 | - return Err(match Self::read(&self.id, db).await? { | ||
| 516 | - Some(_) => AppError::Conflict("the menu still has live bookings"), | ||
| 517 | - None => AppError::NotFound, | ||
| 518 | - }); | ||
| 519 | - }; | ||
| 520 | - Ok(deleted) | ||
| 521 | - } | ||
| 522 | } | 233 | } |
| 523 | 234 | ||
| 524 | #[cfg(test)] | 235 | #[cfg(test)] |
| 525 | mod tests { | 236 | mod tests { |
| 526 | use super::*; | 237 | use super::*; |
| 238 | + use surrealdb::types::Value; | ||
| 527 | 239 | ||
| 528 | #[test] | 240 | #[test] |
| 529 | fn date_accepts_only_padded_calendar_days() { | 241 | fn date_accepts_only_padded_calendar_days() { |
| @@ -657,318 +369,4 @@ mod tests { | |||
| 657 | assert!(validate_capacity(Some(-1)).is_err()); | 369 | assert!(validate_capacity(Some(-1)).is_err()); |
| 658 | assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err()); | 370 | assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err()); |
| 659 | } | 371 | } |
| 660 | - | ||
| 661 | - // --- the slot reference and the menu row move together --------------- | ||
| 662 | - | ||
| 663 | - async fn school() -> Database { | ||
| 664 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 665 | - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | ||
| 666 | - .await | ||
| 667 | - .unwrap() | ||
| 668 | - .check() | ||
| 669 | - .unwrap(); | ||
| 670 | - db | ||
| 671 | - } | ||
| 672 | - | ||
| 673 | - fn lunch() -> MenuSlot { | ||
| 674 | - MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() | ||
| 675 | - } | ||
| 676 | - | ||
| 677 | - /// The reference count, re-read out of the store — never off a return | ||
| 678 | - /// value, which the in-memory engine forges wins on. | ||
| 679 | - async fn refs(db: &Database) -> i64 { | ||
| 680 | - let mut result = db | ||
| 681 | - .query("SELECT VALUE (count ?? 0) FROM $id") | ||
| 682 | - .bind(("id", slot_ref("lunch"))) | ||
| 683 | - .await | ||
| 684 | - .unwrap() | ||
| 685 | - .check() | ||
| 686 | - .unwrap(); | ||
| 687 | - result | ||
| 688 | - .take::<Vec<i64>>(0) | ||
| 689 | - .unwrap() | ||
| 690 | - .into_iter() | ||
| 691 | - .next() | ||
| 692 | - .unwrap_or(0) | ||
| 693 | - } | ||
| 694 | - | ||
| 695 | - async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> { | ||
| 696 | - Menu::create( | ||
| 697 | - MenuDate::try_new(date).unwrap(), | ||
| 698 | - lunch(), | ||
| 699 | - None, | ||
| 700 | - &UserId::from_key("teacher"), | ||
| 701 | - db, | ||
| 702 | - ) | ||
| 703 | - .await | ||
| 704 | - } | ||
| 705 | - | ||
| 706 | - /// Plant a menu row the pre-check will (or will not) find, without going | ||
| 707 | - /// through the claim — a row published before the counter existed. | ||
| 708 | - async fn plant(id: &MenuId, date: &str, db: &Database) { | ||
| 709 | - db.query( | ||
| 710 | - "CREATE $id SET date = $date, slot = 'lunch', \ | ||
| 711 | - created_by = user:teacher, created_at = 1", | ||
| 712 | - ) | ||
| 713 | - .bind(("id", id.record())) | ||
| 714 | - .bind(("date", date.to_string())) | ||
| 715 | - .await | ||
| 716 | - .unwrap() | ||
| 717 | - .check() | ||
| 718 | - .unwrap(); | ||
| 719 | - } | ||
| 720 | - | ||
| 721 | - #[tokio::test] | ||
| 722 | - async fn publishing_lands_the_menu_and_its_reference_together() { | ||
| 723 | - let db = school().await; | ||
| 724 | - let menu = publish("2026-08-02", &db).await.unwrap(); | ||
| 725 | - assert!(Menu::read(menu.get_id(), &db).await.unwrap().is_some()); | ||
| 726 | - assert_eq!(refs(&db).await, 1); | ||
| 727 | - | ||
| 728 | - // The day+slot pre-check answers the second publish — and a refusal | ||
| 729 | - // may not count the slot, or the menu would outlive its own reference. | ||
| 730 | - let again = publish("2026-08-02", &db) | ||
| 731 | - .await | ||
| 732 | - .expect_err("that day and slot are taken"); | ||
| 733 | - assert!(matches!(again, AppError::Conflict(_)), "got {again:?}"); | ||
| 734 | - assert_eq!(refs(&db).await, 1); | ||
| 735 | - } | ||
| 736 | - | ||
| 737 | - #[tokio::test] | ||
| 738 | - async fn a_retired_slot_refuses_and_writes_nothing() { | ||
| 739 | - let db = school().await; | ||
| 740 | - assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); | ||
| 741 | - | ||
| 742 | - let refused = publish("2026-08-02", &db) | ||
| 743 | - .await | ||
| 744 | - .expect_err("the slot left the settings"); | ||
| 745 | - assert!( | ||
| 746 | - matches!(refused, AppError::ConflictOwned(_)), | ||
| 747 | - "got {refused:?}" | ||
| 748 | - ); | ||
| 749 | - assert_eq!(refs(&db).await, 0); | ||
| 750 | - assert!( | ||
| 751 | - Menu::find(&MenuDate::try_new("2026-08-02").unwrap(), &lunch(), &db) | ||
| 752 | - .await | ||
| 753 | - .unwrap() | ||
| 754 | - .is_none() | ||
| 755 | - ); | ||
| 756 | - } | ||
| 757 | - | ||
| 758 | - /// The race the fold exists for: a rival places the very row this publish | ||
| 759 | - /// is placing, between the pre-check and the write. Only the claim's own | ||
| 760 | - /// gate can answer it, and its answer must cost no reference. | ||
| 761 | - #[tokio::test] | ||
| 762 | - async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { | ||
| 763 | - let db = school().await; | ||
| 764 | - let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); | ||
| 765 | - // Planted under another day, so `find` misses it exactly as it would | ||
| 766 | - // in the instant before the rival's own row was visible. | ||
| 767 | - plant(&id, "1999-01-01", &db).await; | ||
| 768 | - | ||
| 769 | - let taken = publish("2026-08-02", &db) | ||
| 770 | - .await | ||
| 771 | - .expect_err("the id is taken"); | ||
| 772 | - assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); | ||
| 773 | - assert_eq!(refs(&db).await, 0); | ||
| 774 | - } | ||
| 775 | - | ||
| 776 | - /// Menus published before ids were derived keep a ULID key a new publish | ||
| 777 | - /// cannot collide with, so the pre-check is the only thing that can refuse. | ||
| 778 | - #[tokio::test] | ||
| 779 | - async fn a_legacy_ulid_menu_still_answers_taken() { | ||
| 780 | - let db = school().await; | ||
| 781 | - plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; | ||
| 782 | - | ||
| 783 | - let taken = publish("2026-08-02", &db) | ||
| 784 | - .await | ||
| 785 | - .expect_err("that day and slot are taken"); | ||
| 786 | - assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); | ||
| 787 | - assert_eq!(refs(&db).await, 0); | ||
| 788 | - } | ||
| 789 | - | ||
| 790 | - /// The cap and the revision are one write. Nothing single-process can | ||
| 791 | - /// observe the torn state the two-query version left (a bumped revision | ||
| 792 | - /// over a cap that had not moved yet), so what is pinned here is the pair: | ||
| 793 | - /// the revision steps exactly once per cap move, and never for a PATCH that | ||
| 794 | - /// carried no cap at all — a booking re-reads only when something it priced | ||
| 795 | - /// itself against actually changed. | ||
| 796 | - #[tokio::test] | ||
| 797 | - async fn the_cap_and_the_revision_move_together_or_not_at_all() { | ||
| 798 | - let db = school().await; | ||
| 799 | - let menu = publish("2026-08-05", &db).await.unwrap(); | ||
| 800 | - let id = menu.get_id().clone(); | ||
| 801 | - assert_eq!(menu.get_version(), 0); | ||
| 802 | - | ||
| 803 | - let capped = menu.update(Some(Some(5)), &db).await.unwrap(); | ||
| 804 | - assert_eq!(capped.get_capacity(), Some(5)); | ||
| 805 | - assert_eq!(capped.get_version(), 1); | ||
| 806 | - // Re-read out of the store, never off the return value. | ||
| 807 | - let stored = Menu::read(&id, &db).await.unwrap().unwrap(); | ||
| 808 | - assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1)); | ||
| 809 | - | ||
| 810 | - // An empty PATCH moves neither, and reads the row back unchanged. | ||
| 811 | - let same = stored.update(None, &db).await.unwrap(); | ||
| 812 | - assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1)); | ||
| 813 | - | ||
| 814 | - // Clearing the cap is a move like any other. | ||
| 815 | - let uncapped = same.update(Some(None), &db).await.unwrap(); | ||
| 816 | - assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2)); | ||
| 817 | - } | ||
| 818 | - | ||
| 819 | - #[tokio::test] | ||
| 820 | - async fn deleting_hands_the_reference_back_in_the_same_step() { | ||
| 821 | - let db = school().await; | ||
| 822 | - let monday = publish("2026-08-03", &db).await.unwrap(); | ||
| 823 | - publish("2026-08-04", &db).await.unwrap(); | ||
| 824 | - assert_eq!(refs(&db).await, 2); | ||
| 825 | - | ||
| 826 | - let id = monday.get_id().clone(); | ||
| 827 | - let ghost = monday.clone(); | ||
| 828 | - monday.delete(&db).await.unwrap(); | ||
| 829 | - assert!(Menu::read(&id, &db).await.unwrap().is_none()); | ||
| 830 | - assert_eq!(refs(&db).await, 1, "the row and its reference go together"); | ||
| 831 | - | ||
| 832 | - // Deleting what is already gone hands nothing back: a second release | ||
| 833 | - // would leave a slot one menu still uses free to be retired. | ||
| 834 | - let gone = ghost.delete(&db).await.expect_err("already deleted"); | ||
| 835 | - assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); | ||
| 836 | - assert_eq!(refs(&db).await, 1); | ||
| 837 | - assert!( | ||
| 838 | - !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), | ||
| 839 | - "a slot a menu is still published for may not be retired" | ||
| 840 | - ); | ||
| 841 | - | ||
| 842 | - // …and once the last menu goes, it may. | ||
| 843 | - let last = Menu::find(&MenuDate::try_new("2026-08-04").unwrap(), &lunch(), &db) | ||
| 844 | - .await | ||
| 845 | - .unwrap() | ||
| 846 | - .unwrap(); | ||
| 847 | - last.delete(&db).await.unwrap(); | ||
| 848 | - assert_eq!(refs(&db).await, 0); | ||
| 849 | - } | ||
| 850 | - | ||
| 851 | - /// Nothing hanging off a menu may survive the delete that swept it — not a | ||
| 852 | - /// dish, and not an attendance mark. Menu ids are deterministic on | ||
| 853 | - /// (date, slot), so a survivor is not litter: republishing that meal mints | ||
| 854 | - /// the *same* id and the orphan comes back attached to the new menu — the | ||
| 855 | - /// kitchen reading "served" for a student who never came, or pricing the | ||
| 856 | - /// old menu's food. | ||
| 857 | - /// | ||
| 858 | - /// The window is between [`Menu::delete`]'s `DELETE` and its cascade: a | ||
| 859 | - /// child write committing in there is a phantom insert into a range the | ||
| 860 | - /// delete already swept on an older snapshot, so the sweep removes nothing | ||
| 861 | - /// and *both* commit. It is closed by making every child write **write** the | ||
| 862 | - /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two | ||
| 863 | - /// transactions then touch one key and the store refuses to commit both. | ||
| 864 | - /// | ||
| 865 | - /// The window is opened by the database itself rather than by a lucky | ||
| 866 | - /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own | ||
| 867 | - /// transaction, the instant the row goes, so the `SLEEP` lands exactly | ||
| 868 | - /// between the delete and its sweep every single time. Nothing in `src/` | ||
| 869 | - /// knows about it; the seam is the schema. | ||
| 870 | - /// | ||
| 871 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 872 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 873 | - /// it commits both writes and answers `Ok` to each, which would fail this | ||
| 874 | - /// test on correct code (see [`crate::database::init_test_server`]). | ||
| 875 | - /// Mutation-tested: putting `MealAttendance::mark` back on a menu *read* | ||
| 876 | - /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) | ||
| 877 | - /// turns this red at **both** of its two rounds — the mark commits, the | ||
| 878 | - /// sweep misses it, and the row is left pointing at a menu that is gone. | ||
| 879 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 880 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 881 | - async fn a_child_written_inside_a_delete_never_outlives_the_menu() { | ||
| 882 | - use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | ||
| 883 | - use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; | ||
| 884 | - | ||
| 885 | - let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; | ||
| 886 | - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") | ||
| 887 | - .await | ||
| 888 | - .unwrap() | ||
| 889 | - .check() | ||
| 890 | - .unwrap(); | ||
| 891 | - // Hold the delete open for a full second after the row is gone, while | ||
| 892 | - // its cascade still has to run. | ||
| 893 | - db.query( | ||
| 894 | - "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ | ||
| 895 | - THEN { SLEEP 1s; };", | ||
| 896 | - ) | ||
| 897 | - .await | ||
| 898 | - .unwrap() | ||
| 899 | - .check() | ||
| 900 | - .unwrap(); | ||
| 901 | - | ||
| 902 | - let (mut dishes, mut marks, mut swept) = (0, 0, 0); | ||
| 903 | - for round in 0..4 { | ||
| 904 | - let menu = publish(&format!("2026-09-{:02}", round + 1), &db) | ||
| 905 | - .await | ||
| 906 | - .unwrap(); | ||
| 907 | - let id = menu.get_id().clone(); | ||
| 908 | - | ||
| 909 | - let drop_it = { | ||
| 910 | - let db = db.clone(); | ||
| 911 | - tokio::spawn(async move { menu.delete(&db).await }) | ||
| 912 | - }; | ||
| 913 | - // The child starts inside the held window — the delete's row is | ||
| 914 | - // gone but uncommitted, which is exactly what a menu read believes. | ||
| 915 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 916 | - // One child per round, never both: whichever wrote first forces the | ||
| 917 | - // delete to re-send, and its second pass sweeps the other's row — | ||
| 918 | - // which would mask exactly the defect this test exists to catch. | ||
| 919 | - let child = { | ||
| 920 | - let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); | ||
| 921 | - tokio::spawn(async move { | ||
| 922 | - if dish { | ||
| 923 | - MenuDish::create( | ||
| 924 | - &id, | ||
| 925 | - DishName::try_new("Pilav").unwrap(), | ||
| 926 | - None, | ||
| 927 | - DishPrice::try_new(1).unwrap(), | ||
| 928 | - DishTags::try_new(&[], &[]).unwrap(), | ||
| 929 | - &db, | ||
| 930 | - ) | ||
| 931 | - .await | ||
| 932 | - .map(|_| ()) | ||
| 933 | - } else { | ||
| 934 | - MealAttendance::mark( | ||
| 935 | - &id, | ||
| 936 | - &UserId::from_key("teacher"), | ||
| 937 | - MealAttendanceStatus::try_new("served").unwrap(), | ||
| 938 | - &UserId::from_key("teacher"), | ||
| 939 | - &db, | ||
| 940 | - ) | ||
| 941 | - .await | ||
| 942 | - .map(|_| ()) | ||
| 943 | - } | ||
| 944 | - }) | ||
| 945 | - }; | ||
| 946 | - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 947 | - // A 404 for the child, or a 409/NotFound for the delete, is a | ||
| 948 | - // correct answer — the only defect is stored state. | ||
| 949 | - assert!( | ||
| 950 | - !matches!(child, Err(AppError::Db(_))), | ||
| 951 | - "round {round}: a raced child write must be answered, not 500: {child:?}" | ||
| 952 | - ); | ||
| 953 | - | ||
| 954 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 955 | - if Menu::read(&id, &db).await.unwrap().is_none() { | ||
| 956 | - swept += 1; | ||
| 957 | - dishes += MenuDish::list_for_menu(&id, &db).await.unwrap().len(); | ||
| 958 | - marks += MealAttendance::list_for_menu(&id, None, 0, &db) | ||
| 959 | - .await | ||
| 960 | - .unwrap() | ||
| 961 | - .1; | ||
| 962 | - } else if drop_it.is_ok() { | ||
| 963 | - panic!("round {round}: the delete reported success but the menu is still there"); | ||
| 964 | - } | ||
| 965 | - } | ||
| 966 | - eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); | ||
| 967 | - assert!( | ||
| 968 | - swept > 0, | ||
| 969 | - "no round ever deleted the menu, so the window was never reached" | ||
| 970 | - ); | ||
| 971 | - assert_eq!(dishes, 0, "a dish outlived its menu"); | ||
| 972 | - assert_eq!(marks, 0, "a mark outlived its menu"); | ||
| 973 | - } | ||
| 974 | } | 372 | } |
src/domain/menu_dish.rsmodified+14 -173
| @@ -4,20 +4,22 @@ | |||
| 4 | //! Money is **minor units** (kuruş) as `i64` — never a float, never a decimal, | 4 | //! Money is **minor units** (kuruş) as `i64` — never a float, never a decimal, |
| 5 | //! at any layer. `tags` are validated against the school's `dietary_tags` | 5 | //! at any layer. `tags` are validated against the school's `dietary_tags` |
| 6 | //! list, the same contract a menu's `slot` has with `meal_slots`. | 6 | //! list, the same contract a menu's `slot` has with `meal_slots`. |
| 7 | +//! | ||
| 8 | +//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the | ||
| 9 | +//! write lock in [`crate::service::menu`]. | ||
| 7 | 10 | ||
| 8 | use std::sync::LazyLock; | 11 | use std::sync::LazyLock; |
| 9 | 12 | ||
| 10 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | 13 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 11 | use ulid::Generator; | 14 | use ulid::Generator; |
| 12 | 15 | ||
| 13 | use crate::constant::{ | 16 | use crate::constant::{ |
| 14 | MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, | 17 | MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, |
| 15 | - MENU_DISH_TABLE, MENU_VERSION_FIELD, | 18 | + MENU_DISH_TABLE, |
| 16 | }; | 19 | }; |
| 17 | -use crate::database::{Database, transaction_with_retry}; | 20 | +use crate::domain::menu::MenuId; |
| 18 | -use crate::domain::menu::{MenuId, bump_menu_and_write}; | ||
| 19 | use crate::domain::timestamp::Timestamp; | 21 | use crate::domain::timestamp::Timestamp; |
| 20 | -use crate::error::{AppError, ValidationError}; | 22 | +use crate::error::ValidationError; |
| 21 | use crate::validate::{validate_optional, validate_required}; | 23 | use crate::validate::{validate_optional, validate_required}; |
| 22 | 24 | ||
| 23 | /// Mints dish ids in write order — see [`MenuId::generate`]; the listings below | 25 | /// Mints dish ids in write order — see [`MenuId::generate`]; the listings below |
| @@ -146,13 +148,13 @@ impl DishTags { | |||
| 146 | 148 | ||
| 147 | #[derive(Debug, Clone, SurrealValue)] | 149 | #[derive(Debug, Clone, SurrealValue)] |
| 148 | pub struct MenuDish { | 150 | pub struct MenuDish { |
| 149 | - id: MenuDishId, | 151 | + pub(crate) id: MenuDishId, |
| 150 | - menu: MenuId, | 152 | + pub(crate) menu: MenuId, |
| 151 | - name: DishName, | 153 | + pub(crate) name: DishName, |
| 152 | - description: Option<DishDescription>, | 154 | + pub(crate) description: Option<DishDescription>, |
| 153 | - price_minor: DishPrice, | 155 | + pub(crate) price_minor: DishPrice, |
| 154 | - tags: DishTags, | 156 | + pub(crate) tags: DishTags, |
| 155 | - created_at: Timestamp, | 157 | + pub(crate) created_at: Timestamp, |
| 156 | } | 158 | } |
| 157 | 159 | ||
| 158 | impl MenuDish { | 160 | impl MenuDish { |
| @@ -183,167 +185,6 @@ impl MenuDish { | |||
| 183 | pub fn get_created_at(&self) -> Timestamp { | 185 | pub fn get_created_at(&self) -> Timestamp { |
| 184 | self.created_at | 186 | self.created_at |
| 185 | } | 187 | } |
| 186 | - | ||
| 187 | - /// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. | ||
| 188 | - pub async fn create( | ||
| 189 | - menu: &MenuId, | ||
| 190 | - name: DishName, | ||
| 191 | - description: Option<DishDescription>, | ||
| 192 | - price_minor: DishPrice, | ||
| 193 | - tags: DishTags, | ||
| 194 | - db: &Database, | ||
| 195 | - ) -> Result<MenuDish, AppError> { | ||
| 196 | - let dish = MenuDish { | ||
| 197 | - id: MenuDishId::generate(), | ||
| 198 | - menu: menu.clone(), | ||
| 199 | - name, | ||
| 200 | - description, | ||
| 201 | - price_minor, | ||
| 202 | - tags, | ||
| 203 | - created_at: Timestamp::now(), | ||
| 204 | - }; | ||
| 205 | - // The revision bump and the insert are one transaction, and the bump is | ||
| 206 | - // what makes the menu's existence part of it: the `UPDATE` matches | ||
| 207 | - // nothing once the menu row is deleted, and a delete racing this one | ||
| 208 | - // touches the very key this transaction writes, so the two cannot both | ||
| 209 | - // commit. Without that, a dish landing just after `DELETE /menus/{id}` | ||
| 210 | - // removed the row but before its cascade ran outlived its menu. | ||
| 211 | - // Every other dish write bumps the same version key, so a lost round is | ||
| 212 | - // ordinary here; it is re-sent rather than reported. Re-sending is sound | ||
| 213 | - // even with the `CREATE` in the batch — the abort wrote nothing, the id | ||
| 214 | - // is a ULID freshly generated above and never seen by a rival, and | ||
| 215 | - // `menu_dish` carries no UNIQUE index — so the retry cannot answer | ||
| 216 | - // "already exists" (see [`transaction_with_retry`]). | ||
| 217 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 218 | - db, | ||
| 219 | - &format!( | ||
| 220 | - "BEGIN TRANSACTION; | ||
| 221 | - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ | ||
| 222 | - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 223 | - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; | ||
| 224 | - CREATE $id CONTENT $dish; | ||
| 225 | - COMMIT TRANSACTION;" | ||
| 226 | - ), | ||
| 227 | - &[ | ||
| 228 | - ("menu".into(), menu.record().into_value()), | ||
| 229 | - ("id".into(), dish.id.record().into_value()), | ||
| 230 | - ("dish".into(), dish.into_value()), | ||
| 231 | - ], | ||
| 232 | - &["no_menu"], | ||
| 233 | - ) | ||
| 234 | - .await?; | ||
| 235 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 236 | - // executed" — only the THROW's own slot names the reason. | ||
| 237 | - if errors | ||
| 238 | - .values() | ||
| 239 | - .any(|error| error.to_string().contains("no_menu")) | ||
| 240 | - { | ||
| 241 | - return Err(AppError::NotFound); | ||
| 242 | - } | ||
| 243 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 244 | - return Err(error.into()); | ||
| 245 | - } | ||
| 246 | - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. | ||
| 247 | - result | ||
| 248 | - .take::<Vec<MenuDish>>(3)? | ||
| 249 | - .into_iter() | ||
| 250 | - .next() | ||
| 251 | - .ok_or_else(|| AppError::Internal("failed to add the dish".into())) | ||
| 252 | - } | ||
| 253 | - | ||
| 254 | - pub async fn read(id: &MenuDishId, db: &Database) -> Result<Option<MenuDish>, AppError> { | ||
| 255 | - Ok(db.select(id.record()).await?) | ||
| 256 | - } | ||
| 257 | - | ||
| 258 | - /// Every dish on one menu, in the order they were added. | ||
| 259 | - pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result<Vec<MenuDish>, AppError> { | ||
| 260 | - Self::list_for_menus(std::slice::from_ref(menu), db).await | ||
| 261 | - } | ||
| 262 | - | ||
| 263 | - /// Dishes for a whole page of menus in one round trip — the alternative is | ||
| 264 | - /// a query per menu, which is the N+1 the pagination slice exists to avoid. | ||
| 265 | - pub async fn list_for_menus( | ||
| 266 | - menus: &[MenuId], | ||
| 267 | - db: &Database, | ||
| 268 | - ) -> Result<Vec<MenuDish>, AppError> { | ||
| 269 | - if menus.is_empty() { | ||
| 270 | - return Ok(Vec::new()); | ||
| 271 | - } | ||
| 272 | - let mut result = db | ||
| 273 | - .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") | ||
| 274 | - .bind(( | ||
| 275 | - "menus", | ||
| 276 | - menus.iter().map(MenuId::record).collect::<Vec<_>>(), | ||
| 277 | - )) | ||
| 278 | - .await? | ||
| 279 | - .check()?; | ||
| 280 | - Ok(result.take::<Vec<MenuDish>>(0)?) | ||
| 281 | - } | ||
| 282 | - | ||
| 283 | - /// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. | ||
| 284 | - pub async fn count_for_menu(menu: &MenuId, db: &Database) -> Result<usize, AppError> { | ||
| 285 | - Ok(Self::list_for_menu(menu, db).await?.len()) | ||
| 286 | - } | ||
| 287 | - | ||
| 288 | - /// Write only the fields the PATCH carried. `description` is nullable, so | ||
| 289 | - /// it takes the three-way shape: absent = keep, `Some(None)` = clear. | ||
| 290 | - /// | ||
| 291 | - /// The `SET` is built here rather than by | ||
| 292 | - /// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the | ||
| 293 | - /// revision bump lands on *another* row and has to share this write's | ||
| 294 | - /// transaction; the field-by-field scoping — an omitted field is never | ||
| 295 | - /// written, so a concurrent PATCH of another one is not reverted — is the | ||
| 296 | - /// same rule, spelled out. | ||
| 297 | - pub async fn update( | ||
| 298 | - self, | ||
| 299 | - name: Option<DishName>, | ||
| 300 | - description: Option<Option<DishDescription>>, | ||
| 301 | - price_minor: Option<DishPrice>, | ||
| 302 | - tags: Option<DishTags>, | ||
| 303 | - db: &Database, | ||
| 304 | - ) -> Result<MenuDish, AppError> { | ||
| 305 | - let mut sets: Vec<&str> = Vec::new(); | ||
| 306 | - let mut bindings: Vec<(String, Value)> = vec![("id".into(), self.id.record().into_value())]; | ||
| 307 | - let mut set = |field: &'static str, value: Option<Value>| { | ||
| 308 | - if let Some(value) = value { | ||
| 309 | - sets.push(field); | ||
| 310 | - bindings.push((field.into(), value)); | ||
| 311 | - } | ||
| 312 | - }; | ||
| 313 | - set("name", name.map(SurrealValue::into_value)); | ||
| 314 | - set("description", description.map(SurrealValue::into_value)); | ||
| 315 | - set("price_minor", price_minor.map(SurrealValue::into_value)); | ||
| 316 | - set("tags", tags.map(SurrealValue::into_value)); | ||
| 317 | - // A PATCH that carried nothing writes nothing and reads the row back, | ||
| 318 | - // exactly as `FieldUpdate` answers one — but it still moves the | ||
| 319 | - // revision, because "every dish write bumps" is the rule a caller can | ||
| 320 | - // rely on without knowing which fields were on the wire. | ||
| 321 | - let statement = if sets.is_empty() { | ||
| 322 | - "SELECT * FROM $id".to_string() | ||
| 323 | - } else { | ||
| 324 | - format!( | ||
| 325 | - "UPDATE $id SET {} RETURN AFTER", | ||
| 326 | - sets.iter() | ||
| 327 | - .map(|field| format!("{field} = ${field}")) | ||
| 328 | - .collect::<Vec<_>>() | ||
| 329 | - .join(", ") | ||
| 330 | - ) | ||
| 331 | - }; | ||
| 332 | - bump_menu_and_write(&self.menu, &statement, bindings, db) | ||
| 333 | - .await? | ||
| 334 | - .ok_or(AppError::NotFound) | ||
| 335 | - } | ||
| 336 | - | ||
| 337 | - pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> { | ||
| 338 | - bump_menu_and_write( | ||
| 339 | - &self.menu, | ||
| 340 | - "DELETE $id RETURN BEFORE", | ||
| 341 | - vec![("id".into(), self.id.record().into_value())], | ||
| 342 | - db, | ||
| 343 | - ) | ||
| 344 | - .await? | ||
| 345 | - .ok_or(AppError::NotFound) | ||
| 346 | - } | ||
| 347 | } | 188 | } |
| 348 | 189 | ||
| 349 | #[cfg(test)] | 190 | #[cfg(test)] |
src/service/dietary_profile.rsadded+32 -0
| @@ -0,0 +1,32 @@ | |||
| 1 | +//! The dietary-profile reads and saves the meal surfaces drive. The row is | ||
| 2 | +//! one per student, created on first write and patched field-by-field; the | ||
| 3 | +//! queries live in [`crate::db::dietary_profile`], the tag/note newtypes | ||
| 4 | +//! and the pure tag intersection in [`crate::domain::dietary_profile`]. | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::dietary_profile; | ||
| 8 | +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; | ||
| 9 | +use crate::domain::user::UserId; | ||
| 10 | +use crate::error::AppError; | ||
| 11 | + | ||
| 12 | +/// One student's profile, or `None` while the school never recorded one. | ||
| 13 | +pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> { | ||
| 14 | + dietary_profile::read(db, student).await | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// The tags a menu read matches its dishes against: the caller's, or an | ||
| 18 | +/// empty list when they have no profile. | ||
| 19 | +pub async fn tags_of(db: &Database, student: &UserId) -> Result<Vec<String>, AppError> { | ||
| 20 | + dietary_profile::tags_of(db, student).await | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// Write the fields the PATCH carried; creates the row on first write. | ||
| 24 | +pub async fn save( | ||
| 25 | + db: &Database, | ||
| 26 | + student: &UserId, | ||
| 27 | + tags: Option<DietaryTags>, | ||
| 28 | + note: Option<Option<DietaryNote>>, | ||
| 29 | + by: &UserId, | ||
| 30 | +) -> Result<DietaryProfile, AppError> { | ||
| 31 | + dietary_profile::save(db, student, tags, note, by).await | ||
| 32 | +} | ||
src/service/meal_attendance.rsadded+49 -0
| @@ -0,0 +1,49 @@ | |||
| 1 | +//! The attendance-mark workflows: recording who ate off a menu and the two | ||
| 2 | +//! listings the kitchen and the student report read. The mark itself is a | ||
| 3 | +//! single atomic UPSERT that rides the menu's revision bump | ||
| 4 | +//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in | ||
| 5 | +//! [`crate::db::meal_attendance`], the row shape in | ||
| 6 | +//! [`crate::domain::meal_attendance`]. | ||
| 7 | + | ||
| 8 | +use crate::database::Database; | ||
| 9 | +use crate::db::meal_attendance; | ||
| 10 | +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | ||
| 11 | +use crate::domain::menu::MenuDate; | ||
| 12 | +use crate::domain::menu::MenuId; | ||
| 13 | +use crate::domain::user::UserId; | ||
| 14 | +use crate::error::AppError; | ||
| 15 | + | ||
| 16 | +/// Record (or overwrite) whether `student` ate off `menu`. `NotFound` when | ||
| 17 | +/// the menu is gone — the mark was not written. | ||
| 18 | +pub async fn mark( | ||
| 19 | + db: &Database, | ||
| 20 | + menu: &MenuId, | ||
| 21 | + student: &UserId, | ||
| 22 | + status: MealAttendanceStatus, | ||
| 23 | + marked_by: &UserId, | ||
| 24 | +) -> Result<MealAttendance, AppError> { | ||
| 25 | + meal_attendance::mark(db, menu, student, status, marked_by).await | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// The kitchen's list for one menu. | ||
| 29 | +pub async fn list_for_menu( | ||
| 30 | + db: &Database, | ||
| 31 | + menu: &MenuId, | ||
| 32 | + limit: Option<i64>, | ||
| 33 | + offset: i64, | ||
| 34 | +) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 35 | + meal_attendance::list_for_menu(db, menu, limit, offset).await | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// One student's marks, newest first, within inclusive `YYYY-MM-DD` bounds | ||
| 39 | +/// on the menu's day. | ||
| 40 | +pub async fn list_for_student( | ||
| 41 | + db: &Database, | ||
| 42 | + student: &UserId, | ||
| 43 | + from: Option<&MenuDate>, | ||
| 44 | + to: Option<&MenuDate>, | ||
| 45 | + limit: Option<i64>, | ||
| 46 | + offset: i64, | ||
| 47 | +) -> Result<(Vec<MealAttendance>, i64), AppError> { | ||
| 48 | + meal_attendance::list_for_student(db, student, from, to, limit, offset).await | ||
| 49 | +} | ||
src/service/meal_booking.rsmodified+24 -20
| @@ -21,14 +21,17 @@ use crate::constant::{CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS}; | |||
| 21 | use crate::database::{Database, backoff}; | 21 | use crate::database::{Database, backoff}; |
| 22 | use crate::db::cap; | 22 | use crate::db::cap; |
| 23 | use crate::db::meal_booking; | 23 | use crate::db::meal_booking; |
| 24 | +use crate::db::meal_ledger; | ||
| 25 | +use crate::db::menu; | ||
| 24 | use crate::domain::meal_booking::{ | 26 | use crate::domain::meal_booking::{ |
| 25 | MealBooking, MealBookingId, MealBookingStatus, MealCutoff, check_cutoff, check_day_not_past, | 27 | MealBooking, MealBookingId, MealBookingStatus, MealCutoff, check_cutoff, check_day_not_past, |
| 26 | }; | 28 | }; |
| 27 | use crate::domain::meal_ledger::MealLedger; | 29 | use crate::domain::meal_ledger::MealLedger; |
| 28 | -use crate::domain::menu::{Menu, MenuId}; | 30 | +use crate::domain::menu::MenuId; |
| 29 | use crate::domain::timestamp::Timestamp; | 31 | use crate::domain::timestamp::Timestamp; |
| 30 | use crate::domain::user::UserId; | 32 | use crate::domain::user::UserId; |
| 31 | use crate::error::AppError; | 33 | use crate::error::AppError; |
| 34 | +use crate::service::meal_ledger::{charge_booking, reverse_booking}; | ||
| 32 | 35 | ||
| 33 | /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already | 36 | /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already |
| 34 | /// booked is returned as-is, claiming nothing; a cancelled row is revived as | 37 | /// booked is returned as-is, claiming nothing; a cancelled row is revived as |
| @@ -62,7 +65,7 @@ pub async fn book( | |||
| 62 | let seats = menu.record(); | 65 | let seats = menu.record(); |
| 63 | for attempt in 0..CAP_WRITE_TRIES { | 66 | for attempt in 0..CAP_WRITE_TRIES { |
| 64 | backoff(attempt).await; | 67 | backoff(attempt).await; |
| 65 | - let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; | 68 | + let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?; |
| 66 | check_day_not_past(fresh.get_date())?; | 69 | check_day_not_past(fresh.get_date())?; |
| 67 | check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; | 70 | check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; |
| 68 | let existing: Option<MealBooking> = meal_booking::read(db, &id).await?; | 71 | let existing: Option<MealBooking> = meal_booking::read(db, &id).await?; |
| @@ -80,7 +83,7 @@ pub async fn book( | |||
| 80 | .clone() | 83 | .clone() |
| 81 | .filter(|row| row.status == MealBookingStatus::Booked) | 84 | .filter(|row| row.status == MealBookingStatus::Booked) |
| 82 | { | 85 | { |
| 83 | - MealLedger::charge_booking(&held, booked_by, db).await?; | 86 | + charge_booking(db, &held, booked_by).await?; |
| 84 | // Answered off a re-read, never off the row read a round trip | 87 | // Answered off a re-read, never off the row read a round trip |
| 85 | // ago: a cancel committing in that gap has freed the seat, | 88 | // ago: a cancel committing in that gap has freed the seat, |
| 86 | // given the money back and left the row `cancelled`, and | 89 | // given the money back and left the row `cancelled`, and |
| @@ -117,7 +120,7 @@ pub async fn book( | |||
| 117 | // Before the seat: an unchargeable menu (dishes summing past the | 120 | // Before the seat: an unchargeable menu (dishes summing past the |
| 118 | // cap) must refuse the booking outright, never leave a | 121 | // cap) must refuse the booking outright, never leave a |
| 119 | // booked-but-unbilled row behind. | 122 | // booked-but-unbilled row behind. |
| 120 | - let price = MealLedger::price_snapshot(menu, db).await?; | 123 | + let price = meal_ledger::price_snapshot(db, menu).await?; |
| 121 | let fresh_row = MealBooking { | 124 | let fresh_row = MealBooking { |
| 122 | id: id.clone(), | 125 | id: id.clone(), |
| 123 | menu: menu.clone(), | 126 | menu: menu.clone(), |
| @@ -155,7 +158,7 @@ pub async fn book( | |||
| 155 | // reason is re-read rather than guessed. A moved menu is not a | 158 | // reason is re-read rather than guessed. A moved menu is not a |
| 156 | // refusal: the price above is stale, so price and seat are | 159 | // refusal: the price above is stale, so price and seat are |
| 157 | // taken again together. | 160 | // taken again together. |
| 158 | - cap::Claimed::Full => match Menu::read(menu, db).await? { | 161 | + cap::Claimed::Full => match menu::read(db, menu).await? { |
| 159 | None => return Err(AppError::NotFound), | 162 | None => return Err(AppError::NotFound), |
| 160 | Some(now) if now.get_version() != fresh.get_version() => continue, | 163 | Some(now) if now.get_version() != fresh.get_version() => continue, |
| 161 | Some(_) => return Err(AppError::Conflict("the menu is fully booked")), | 164 | Some(_) => return Err(AppError::Conflict("the menu is fully booked")), |
| @@ -228,10 +231,10 @@ pub async fn cancel( | |||
| 228 | .await? | 231 | .await? |
| 229 | .ok_or(AppError::NotFound)?; | 232 | .ok_or(AppError::NotFound)?; |
| 230 | if fresh.status == MealBookingStatus::Cancelled { | 233 | if fresh.status == MealBookingStatus::Cancelled { |
| 231 | - MealLedger::reverse_booking(&fresh, recorded_by, db).await?; | 234 | + reverse_booking(db, &fresh, recorded_by).await?; |
| 232 | return Ok(fresh); | 235 | return Ok(fresh); |
| 233 | } | 236 | } |
| 234 | - let menu = Menu::read(&fresh.menu, db) | 237 | + let menu = menu::read(db, &fresh.menu) |
| 235 | .await? | 238 | .await? |
| 236 | .ok_or(AppError::NotFound)?; | 239 | .ok_or(AppError::NotFound)?; |
| 237 | check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; | 240 | check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; |
| @@ -251,7 +254,7 @@ pub async fn cancel( | |||
| 251 | live | 254 | live |
| 252 | } | 255 | } |
| 253 | }; | 256 | }; |
| 254 | - MealLedger::reverse_booking(&saved, recorded_by, db).await?; | 257 | + reverse_booking(db, &saved, recorded_by).await?; |
| 255 | Ok(saved) | 258 | Ok(saved) |
| 256 | } | 259 | } |
| 257 | 260 | ||
| @@ -288,9 +291,10 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result< | |||
| 288 | mod tests { | 291 | mod tests { |
| 289 | use super::*; | 292 | use super::*; |
| 290 | use crate::database::init_mem; | 293 | use crate::database::init_mem; |
| 294 | + use crate::db::menu_dish; | ||
| 291 | use crate::domain::meal_booking::MealBookingStatus; | 295 | use crate::domain::meal_booking::MealBookingStatus; |
| 292 | use crate::domain::meal_ledger::LedgerAmount; | 296 | use crate::domain::meal_ledger::LedgerAmount; |
| 293 | - use crate::domain::menu::{Menu, MenuDate, MenuSlot}; | 297 | + use crate::domain::menu::{MenuDate, MenuSlot}; |
| 294 | use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; | 298 | use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; |
| 295 | use crate::domain::settings::MealSlotDef; | 299 | use crate::domain::settings::MealSlotDef; |
| 296 | 300 | ||
| @@ -304,12 +308,12 @@ mod tests { | |||
| 304 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { | 308 | async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { |
| 305 | let db = init_mem().await.unwrap(); | 309 | let db = init_mem().await.unwrap(); |
| 306 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; | 310 | let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; |
| 307 | - let menu = Menu::create( | 311 | + let menu = menu::create( |
| 312 | + &db, | ||
| 308 | MenuDate::try_new(date).unwrap(), | 313 | MenuDate::try_new(date).unwrap(), |
| 309 | MenuSlot::try_new("lunch", &slots).unwrap(), | 314 | MenuSlot::try_new("lunch", &slots).unwrap(), |
| 310 | capacity, | 315 | capacity, |
| 311 | &UserId::generate(), | 316 | &UserId::generate(), |
| 312 | - &db, | ||
| 313 | ) | 317 | ) |
| 314 | .await | 318 | .await |
| 315 | .unwrap(); | 319 | .unwrap(); |
| @@ -336,13 +340,13 @@ mod tests { | |||
| 336 | } | 340 | } |
| 337 | 341 | ||
| 338 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { | 342 | async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { |
| 339 | - MenuDish::create( | 343 | + menu_dish::create( |
| 344 | + db, | ||
| 340 | menu, | 345 | menu, |
| 341 | DishName::try_new("çorba").unwrap(), | 346 | DishName::try_new("çorba").unwrap(), |
| 342 | None, | 347 | None, |
| 343 | DishPrice::try_new(price).unwrap(), | 348 | DishPrice::try_new(price).unwrap(), |
| 344 | DishTags::try_new(&[], &[]).unwrap(), | 349 | DishTags::try_new(&[], &[]).unwrap(), |
| 345 | - db, | ||
| 346 | ) | 350 | ) |
| 347 | .await | 351 | .await |
| 348 | .unwrap() | 352 | .unwrap() |
| @@ -391,15 +395,15 @@ mod tests { | |||
| 391 | let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) | 395 | let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) |
| 392 | .await | 396 | .await |
| 393 | .unwrap(); | 397 | .unwrap(); |
| 394 | - let row = Menu::read(&id, &db).await.unwrap().unwrap(); | 398 | + let row = menu::read(&db, &id).await.unwrap().unwrap(); |
| 395 | assert!(matches!( | 399 | assert!(matches!( |
| 396 | - row.clone().delete(&db).await, | 400 | + menu::delete(&db, row.clone()).await, |
| 397 | Err(AppError::Conflict(_)) | 401 | Err(AppError::Conflict(_)) |
| 398 | )); | 402 | )); |
| 399 | cancel(&db, booking, &MealCutoff::default(), &ali) | 403 | cancel(&db, booking, &MealCutoff::default(), &ali) |
| 400 | .await | 404 | .await |
| 401 | .unwrap(); | 405 | .unwrap(); |
| 402 | - assert!(row.delete(&db).await.is_ok()); | 406 | + assert!(menu::delete(&db, row).await.is_ok()); |
| 403 | } | 407 | } |
| 404 | 408 | ||
| 405 | /// A booking placed after a price edit is billed the new price, and one | 409 | /// A booking placed after a price edit is billed the new price, and one |
| @@ -501,7 +505,7 @@ mod tests { | |||
| 501 | Err(AppError::Conflict(_)) | 505 | Err(AppError::Conflict(_)) |
| 502 | )); | 506 | )); |
| 503 | assert_eq!(seats(&menu, &db).await, 0); | 507 | assert_eq!(seats(&menu, &db).await, 0); |
| 504 | - let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) | 508 | + let (lines, total) = meal_ledger::list_for_student(&db, &ali, None, 0) |
| 505 | .await | 509 | .await |
| 506 | .unwrap(); | 510 | .unwrap(); |
| 507 | assert!( | 511 | assert!( |
| @@ -535,8 +539,8 @@ mod tests { | |||
| 535 | // ahead — the shape the create-side check cannot reach. A test cannot | 539 | // ahead — the shape the create-side check cannot reach. A test cannot |
| 536 | // age a menu (`date` is READONLY), so the seat is placed on an | 540 | // age a menu (`date` is READONLY), so the seat is placed on an |
| 537 | // already-past menu by the very transaction `book` places it with. | 541 | // already-past menu by the very transaction `book` places it with. |
| 538 | - let fresh = Menu::read(&menu, &db).await.unwrap().unwrap(); | 542 | + let fresh = menu::read(&db, &menu).await.unwrap().unwrap(); |
| 539 | - let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); | 543 | + let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); |
| 540 | let row = MealBooking { | 544 | let row = MealBooking { |
| 541 | id: MealBookingId::composite(&menu, &ali), | 545 | id: MealBookingId::composite(&menu, &ali), |
| 542 | menu: menu.clone(), | 546 | menu: menu.clone(), |
| @@ -575,7 +579,7 @@ mod tests { | |||
| 575 | .expect("a cancel on a past day still frees the seat"); | 579 | .expect("a cancel on a past day still frees the seat"); |
| 576 | assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled); | 580 | assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled); |
| 577 | assert_eq!(seats(&menu, &db).await, 0); | 581 | assert_eq!(seats(&menu, &db).await, 0); |
| 578 | - let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db) | 582 | + let (lines, _) = meal_ledger::list_for_student(&db, &ali, None, 0) |
| 579 | .await | 583 | .await |
| 580 | .unwrap(); | 584 | .unwrap(); |
| 581 | assert_eq!(lines.len(), 2, "the charge and its reversal"); | 585 | assert_eq!(lines.len(), 2, "the charge and its reversal"); |
src/service/meal_ledger.rsadded+138 -0
| @@ -0,0 +1,138 @@ | |||
| 1 | +//! The money workflows around the append-only meal ledger: the booking | ||
| 2 | +//! charge and its reversal (the ledger halves of the seat workflows in | ||
| 3 | +//! [`crate::service::meal_booking`]) and the recorded credit. The rows, | ||
| 4 | +//! id minters and the sign convention live in | ||
| 5 | +//! [`crate::domain::meal_ledger`]; the writes and the SUM/balance reads in | ||
| 6 | +//! [`crate::db::meal_ledger`]. | ||
| 7 | + | ||
| 8 | +use crate::database::Database; | ||
| 9 | +use crate::db::meal_ledger; | ||
| 10 | +use crate::domain::meal_booking::MealBooking; | ||
| 11 | +use crate::domain::meal_ledger::{ | ||
| 12 | + LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind, | ||
| 13 | +}; | ||
| 14 | +use crate::domain::payment_ledger::PaymentRequestKey; | ||
| 15 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | +use crate::domain::user::UserId; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | + | ||
| 19 | +/// Bill `booking`'s current attempt at the price frozen onto it when that | ||
| 20 | +/// attempt took the seat. | ||
| 21 | +/// | ||
| 22 | +/// The price comes off the *booking row*, never off the menu as it stands | ||
| 23 | +/// now: a seat taken while the menu was free carries `None` forever, so | ||
| 24 | +/// "was free" is a recorded fact and a later dish never bills a seat | ||
| 25 | +/// retroactively. Called from | ||
| 26 | +/// [`book`](crate::service::meal_booking::book) alone, right after the seat | ||
| 27 | +/// was claimed, so the seat and its money move together. | ||
| 28 | +/// | ||
| 29 | +/// Replaying it is free: the id is `(booking, attempt)`, so a duplicate | ||
| 30 | +/// `POST` writes nothing, and an attempt whose charge failed the first time | ||
| 31 | +/// self-heals on the next `POST` of the same seat. | ||
| 32 | +pub async fn charge_booking( | ||
| 33 | + db: &Database, | ||
| 34 | + booking: &MealBooking, | ||
| 35 | + recorded_by: &UserId, | ||
| 36 | +) -> Result<(), AppError> { | ||
| 37 | + let Some(line) = MealLedger::charge_for(booking, recorded_by) else { | ||
| 38 | + return Ok(()); | ||
| 39 | + }; | ||
| 40 | + meal_ledger::append(db, line).await?; | ||
| 41 | + Ok(()) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Give the money back for a cancelled `booking`: a new `reversal` line for | ||
| 45 | +/// the charge's exact amount, pointing at it. The charge is never touched. | ||
| 46 | +/// A booking that was never billed (a free menu) reverses nothing, and | ||
| 47 | +/// neither does one whose charge never landed — the reversal is keyed to | ||
| 48 | +/// the very charge it undoes, so it can only exist alongside it. | ||
| 49 | +/// | ||
| 50 | +/// Keyed by `(booking, attempt)` like the charge, so a retried cancel | ||
| 51 | +/// refunds once. The line normally lands *inside* the flip's own | ||
| 52 | +/// transaction | ||
| 53 | +/// ([`release_seat`](crate::db::meal_booking::release_seat)); this path is what heals a | ||
| 54 | +/// seat flipped before that was true, and it is why | ||
| 55 | +/// [`cancel`](crate::service::meal_booking::cancel) replays it on an already-cancelled row instead | ||
| 56 | +/// of refusing it. Nothing else on the API can append the missing line. | ||
| 57 | +pub async fn reverse_booking( | ||
| 58 | + db: &Database, | ||
| 59 | + booking: &MealBooking, | ||
| 60 | + recorded_by: &UserId, | ||
| 61 | +) -> Result<(), AppError> { | ||
| 62 | + let Some((charge, line)) = MealLedger::reversal_for(booking, recorded_by) else { | ||
| 63 | + return Ok(()); | ||
| 64 | + }; | ||
| 65 | + if meal_ledger::read(db, &charge).await?.is_none() { | ||
| 66 | + return Ok(()); | ||
| 67 | + } | ||
| 68 | + meal_ledger::append(db, line).await?; | ||
| 69 | + Ok(()) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// Money in: a payment received, or an opening balance. | ||
| 73 | +/// | ||
| 74 | +/// With a `request_key` the line is keyed by it (see | ||
| 75 | +/// [`MealLedgerId::for_request`](crate::domain::meal_ledger::MealLedgerId::for_request)) | ||
| 76 | +/// and the call is **retry-safe**: a client | ||
| 77 | +/// resending the identical body after a timeout gets back the line the | ||
| 78 | +/// first attempt wrote, not a second credit — nothing on this API can edit | ||
| 79 | +/// or delete one, so a doubled credit is corrected only by a compensating | ||
| 80 | +/// line. Without one the id is a fresh ulid and two identical calls are two | ||
| 81 | +/// credits, which is what a desk taking the same amount twice really means. | ||
| 82 | +pub async fn credit( | ||
| 83 | + db: &Database, | ||
| 84 | + student: &UserId, | ||
| 85 | + amount_minor: LedgerAmount, | ||
| 86 | + method: Option<LedgerMethod>, | ||
| 87 | + note: Option<LedgerNote>, | ||
| 88 | + request_key: Option<&PaymentRequestKey>, | ||
| 89 | + recorded_by: &UserId, | ||
| 90 | +) -> Result<MealLedger, AppError> { | ||
| 91 | + let line = meal_ledger::append( | ||
| 92 | + db, | ||
| 93 | + MealLedger { | ||
| 94 | + id: match request_key { | ||
| 95 | + Some(key) => MealLedgerId::for_request(student, key), | ||
| 96 | + None => MealLedgerId::generate(), | ||
| 97 | + }, | ||
| 98 | + student: student.clone(), | ||
| 99 | + kind: MealLedgerKind::Credit, | ||
| 100 | + amount_minor, | ||
| 101 | + source: None, | ||
| 102 | + method, | ||
| 103 | + note, | ||
| 104 | + recorded_by: recorded_by.clone(), | ||
| 105 | + created_at: Timestamp::now(), | ||
| 106 | + }, | ||
| 107 | + ) | ||
| 108 | + .await?; | ||
| 109 | + // A replay is answered from the stored line — but only if it is the | ||
| 110 | + // same money. The same key for a different amount is a client bug, and | ||
| 111 | + // handing back the old line would hide it behind a `201`. Checked on | ||
| 112 | + // what `append` gave back rather than on a read before it: two retries | ||
| 113 | + // arriving together both find no row, and only the id decides which | ||
| 114 | + // one's amount is stored, so a check *before* the write would tell the | ||
| 115 | + // loser its own amount landed. | ||
| 116 | + if request_key.is_some() && line.get_amount_minor() != amount_minor { | ||
| 117 | + return Err(AppError::Conflict( | ||
| 118 | + "this request_key was already used for a different amount", | ||
| 119 | + )); | ||
| 120 | + } | ||
| 121 | + Ok(line) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// A student's whole statement, newest first. | ||
| 125 | +pub async fn list_for_student( | ||
| 126 | + db: &Database, | ||
| 127 | + student: &UserId, | ||
| 128 | + limit: Option<i64>, | ||
| 129 | + offset: i64, | ||
| 130 | +) -> Result<(Vec<MealLedger>, i64), AppError> { | ||
| 131 | + meal_ledger::list_for_student(db, student, limit, offset).await | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// The derived balance: `credits + reversals - charges`, in minor units. | ||
| 135 | +/// Negative means the student owes the school. | ||
| 136 | +pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { | ||
| 137 | + meal_ledger::balance_of(db, student).await | ||
| 138 | +} | ||
src/service/menu.rsadded+161 -0
| @@ -0,0 +1,161 @@ | |||
| 1 | +//! The kitchen's workflows: publishing and unpublishing menus, and every | ||
| 2 | +//! dish write — which all hold [`MENU_LOCK`], the lock that makes the | ||
| 3 | +//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB | ||
| 4 | +//! does not conflict-check) more than a wish. The queries live in | ||
| 5 | +//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the | ||
| 6 | +//! date/slot/capacity rules in [`crate::domain::menu`] and | ||
| 7 | +//! [`crate::domain::menu_dish`]. | ||
| 8 | +//! | ||
| 9 | +//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the | ||
| 10 | +//! dishes, write the dish), which is why it lives here and not in the db | ||
| 11 | +//! layer: a single-call atomicity lock would be the store's to own, but | ||
| 12 | +//! count-then-write is write-skew only this process can serialize. | ||
| 13 | +//! | ||
| 14 | +//! **A leaf**: every dish write held under it moves the menu's revision | ||
| 15 | +//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]), | ||
| 16 | +//! so no path under this lock reaches `cap`'s counter lock any more. Should | ||
| 17 | +//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing | ||
| 18 | +//! may take this lock while holding a counter lock: that is the invariant a | ||
| 19 | +//! new caller must keep, and it is what would keep the pair deadlock-free. | ||
| 20 | + | ||
| 21 | +use tokio::sync::Mutex; | ||
| 22 | + | ||
| 23 | +use crate::constant::MAX_DISHES_PER_MENU; | ||
| 24 | +use crate::database::Database; | ||
| 25 | +use crate::db::{menu, menu_dish}; | ||
| 26 | +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; | ||
| 27 | +use crate::domain::menu_dish::{ | ||
| 28 | + DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, | ||
| 29 | +}; | ||
| 30 | +use crate::domain::user::UserId; | ||
| 31 | +use crate::error::AppError; | ||
| 32 | + | ||
| 33 | +/// Serializes what is left that counts rows against one menu: the dish cap | ||
| 34 | +/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not | ||
| 35 | +/// conflict-check). Publishing no longer needs it — the day+slot *is* the | ||
| 36 | +/// record id — and neither does a booking, a menu delete, or the settings | ||
| 37 | +/// slot-removal guard: those went to conditional single-record writes | ||
| 38 | +/// ([`crate::db::cap`]), which the store decides as this lock cannot. | ||
| 39 | +// | ||
| 40 | +// corner-cut: the dish cap therefore rests on this lock alone — a dish write | ||
| 41 | +// added without taking it reopens the count-then-write hole silently. Closing | ||
| 42 | +// it properly is another `cap` counter (`dish_count` on the menu row) plus its | ||
| 43 | +// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was | ||
| 44 | +// not worth the column here. | ||
| 45 | +pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 46 | + | ||
| 47 | +/// Publish a menu for one day and meal slot. The caller has validated the | ||
| 48 | +/// date (a real calendar day, not already over), the slot (one the school | ||
| 49 | +/// serves) and the capacity; the day+slot duplicate refusal is decided by | ||
| 50 | +/// the store ([`menu::create`]). | ||
| 51 | +pub async fn create( | ||
| 52 | + db: &Database, | ||
| 53 | + date: MenuDate, | ||
| 54 | + slot: MenuSlot, | ||
| 55 | + capacity: Option<i64>, | ||
| 56 | + created_by: &UserId, | ||
| 57 | +) -> Result<Menu, AppError> { | ||
| 58 | + menu::create(db, date, slot, capacity, created_by).await | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// The menu, for callers that only inspect it — the web layer's handlers | ||
| 62 | +/// read through here. | ||
| 63 | +pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> { | ||
| 64 | + menu::read(db, id).await | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds. | ||
| 68 | +pub async fn list( | ||
| 69 | + db: &Database, | ||
| 70 | + from: Option<&MenuDate>, | ||
| 71 | + to: Option<&MenuDate>, | ||
| 72 | + limit: Option<i64>, | ||
| 73 | + offset: i64, | ||
| 74 | +) -> Result<(Vec<Menu>, i64), AppError> { | ||
| 75 | + menu::list(db, from, to, limit, offset).await | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Change a menu's seat cap; `None` keeps it, `Some(None)` clears it. | ||
| 79 | +pub async fn update( | ||
| 80 | + db: &Database, | ||
| 81 | + menu_row: Menu, | ||
| 82 | + capacity: Option<Option<i64>>, | ||
| 83 | +) -> Result<Menu, AppError> { | ||
| 84 | + menu::update(db, menu_row, capacity).await | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// Unpublish a menu, sweeping its dishes and attendance marks in the same | ||
| 88 | +/// transaction; refused while a seat is still held. | ||
| 89 | +pub async fn delete(db: &Database, menu_row: Menu) -> Result<Menu, AppError> { | ||
| 90 | + menu::delete(db, menu_row).await | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// Add a dish to a menu, under the dish cap. | ||
| 94 | +/// | ||
| 95 | +/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write | ||
| 96 | +/// is write-skew, so the count and the insert have to be one step. The | ||
| 97 | +/// *price* no longer needs it — a dish write moves the menu's revision, and | ||
| 98 | +/// a booking claims its seat at the revision it priced itself against. | ||
| 99 | +/// The lock is a leaf again: the revision bump rides the dish write's own | ||
| 100 | +/// transaction now, so nothing held under it takes `cap`'s counter lock. It | ||
| 101 | +/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a | ||
| 102 | +/// caller that changes it must keep. | ||
| 103 | +/// | ||
| 104 | +/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` | ||
| 105 | +/// running in the gap takes its cascade with it and this dish lands on a menu | ||
| 106 | +/// that no longer exists. | ||
| 107 | +pub async fn add_dish( | ||
| 108 | + db: &Database, | ||
| 109 | + menu_id: &MenuId, | ||
| 110 | + name: DishName, | ||
| 111 | + description: Option<DishDescription>, | ||
| 112 | + price_minor: DishPrice, | ||
| 113 | + tags: DishTags, | ||
| 114 | +) -> Result<MenuDish, AppError> { | ||
| 115 | + let _guard = MENU_LOCK.lock().await; | ||
| 116 | + let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?; | ||
| 117 | + if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU { | ||
| 118 | + return Err(AppError::Conflict( | ||
| 119 | + "the menu already carries the maximum number of dishes", | ||
| 120 | + )); | ||
| 121 | + } | ||
| 122 | + menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// One dish, for callers that only inspect it. | ||
| 126 | +pub async fn read_dish(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> { | ||
| 127 | + menu_dish::read(db, id).await | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// Every dish on one menu, in the order they were added. | ||
| 131 | +pub async fn list_dishes(db: &Database, menu_id: &MenuId) -> Result<Vec<MenuDish>, AppError> { | ||
| 132 | + menu_dish::list_for_menu(db, menu_id).await | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Dishes for a whole page of menus in one round trip. | ||
| 136 | +pub async fn list_dishes_for_menus( | ||
| 137 | + db: &Database, | ||
| 138 | + menus: &[MenuId], | ||
| 139 | +) -> Result<Vec<MenuDish>, AppError> { | ||
| 140 | + menu_dish::list_for_menus(db, menus).await | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see | ||
| 144 | +/// [`add_dish`]. Only what the request carried is written. | ||
| 145 | +pub async fn update_dish( | ||
| 146 | + db: &Database, | ||
| 147 | + dish: MenuDish, | ||
| 148 | + name: Option<DishName>, | ||
| 149 | + description: Option<Option<DishDescription>>, | ||
| 150 | + price_minor: Option<DishPrice>, | ||
| 151 | + tags: Option<DishTags>, | ||
| 152 | +) -> Result<MenuDish, AppError> { | ||
| 153 | + let _guard = MENU_LOCK.lock().await; | ||
| 154 | + menu_dish::update(db, dish, name, description, price_minor, tags).await | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write. | ||
| 158 | +pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { | ||
| 159 | + let _guard = MENU_LOCK.lock().await; | ||
| 160 | + menu_dish::delete(db, dish).await | ||
| 161 | +} | ||
src/service/mod.rsmodified+4 -1
| @@ -1,16 +1,19 @@ | |||
| 1 | //! Business rules, workflow locks, multi-call orchestration; calls db::*; no | 1 | //! Business rules, workflow locks, multi-call orchestration; calls db::*; no |
| 2 | //! SurrealQL text. | 2 | //! SurrealQL text. |
| 3 | - | ||
| 4 | pub mod appointment; | 3 | pub mod appointment; |
| 5 | pub mod appointment_slot; | 4 | pub mod appointment_slot; |
| 6 | pub mod class_blueprint; | 5 | pub mod class_blueprint; |
| 7 | pub mod course; | 6 | pub mod course; |
| 8 | pub mod course_session; | 7 | pub mod course_session; |
| 8 | +pub mod dietary_profile; | ||
| 9 | pub mod enrollment; | 9 | pub mod enrollment; |
| 10 | pub mod exam; | 10 | pub mod exam; |
| 11 | pub mod exam_attempt; | 11 | pub mod exam_attempt; |
| 12 | pub mod exam_question; | 12 | pub mod exam_question; |
| 13 | +pub mod meal_attendance; | ||
| 13 | pub mod meal_booking; | 14 | pub mod meal_booking; |
| 15 | +pub mod meal_ledger; | ||
| 16 | +pub mod menu; | ||
| 14 | pub mod note; | 17 | pub mod note; |
| 15 | pub mod payment_ledger; | 18 | pub mod payment_ledger; |
| 16 | pub mod session; | 19 | pub mod session; |
src/web/meals.rsmodified+64 -63
| @@ -18,13 +18,12 @@ use utoipa::{IntoParams, ToSchema}; | |||
| 18 | use utoipa_axum::router::OpenApiRouter; | 18 | use utoipa_axum::router::OpenApiRouter; |
| 19 | use utoipa_axum::routes; | 19 | use utoipa_axum::routes; |
| 20 | 20 | ||
| 21 | -use crate::constant::MAX_DISHES_PER_MENU; | ||
| 22 | use crate::database::Database; | 21 | use crate::database::Database; |
| 23 | -use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts}; | 22 | +use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; |
| 24 | use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | 23 | use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; |
| 25 | use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; | 24 | use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; |
| 26 | use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; | 25 | use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; |
| 27 | -use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; | 26 | +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; |
| 28 | use crate::domain::menu_dish::{ | 27 | use crate::domain::menu_dish::{ |
| 29 | DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, | 28 | DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, |
| 30 | }; | 29 | }; |
| @@ -206,9 +205,9 @@ async fn menu_responses( | |||
| 206 | db: &Database, | 205 | db: &Database, |
| 207 | ) -> Result<Vec<MenuResponse>, AppError> { | 206 | ) -> Result<Vec<MenuResponse>, AppError> { |
| 208 | let ids: Vec<MenuId> = menus.iter().map(|menu| menu.get_id().clone()).collect(); | 207 | let ids: Vec<MenuId> = menus.iter().map(|menu| menu.get_id().clone()).collect(); |
| 209 | - let dishes = MenuDish::list_for_menus(&ids, db).await?; | 208 | + let dishes = service::menu::list_dishes_for_menus(db, &ids).await?; |
| 210 | let people = person_map(menus.iter().map(|menu| menu.get_created_by().clone()), db).await?; | 209 | let people = person_map(menus.iter().map(|menu| menu.get_created_by().clone()), db).await?; |
| 211 | - let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; | 210 | + let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; |
| 212 | Ok(menus | 211 | Ok(menus |
| 213 | .iter() | 212 | .iter() |
| 214 | .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags)) | 213 | .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags)) |
| @@ -221,9 +220,9 @@ async fn one_menu( | |||
| 221 | viewer: &UserId, | 220 | viewer: &UserId, |
| 222 | db: &Database, | 221 | db: &Database, |
| 223 | ) -> Result<Json<MenuResponse>, AppError> { | 222 | ) -> Result<Json<MenuResponse>, AppError> { |
| 224 | - let dishes = MenuDish::list_for_menu(menu.get_id(), db).await?; | 223 | + let dishes = service::menu::list_dishes(db, menu.get_id()).await?; |
| 225 | let people = person_map([menu.get_created_by().clone()], db).await?; | 224 | let people = person_map([menu.get_created_by().clone()], db).await?; |
| 226 | - let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; | 225 | + let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; |
| 227 | Ok(Json(MenuResponse::new( | 226 | Ok(Json(MenuResponse::new( |
| 228 | menu, | 227 | menu, |
| 229 | &dishes, | 228 | &dishes, |
| @@ -275,7 +274,7 @@ async fn create_menu( | |||
| 275 | &service::settings::load(&st.db).await?.get_meal_slots(), | 274 | &service::settings::load(&st.db).await?.get_meal_slots(), |
| 276 | )?; | 275 | )?; |
| 277 | validate_capacity(req.capacity)?; | 276 | validate_capacity(req.capacity)?; |
| 278 | - let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?; | 277 | + let menu = service::menu::create(&st.db, date, slot, req.capacity, user.get_id()).await?; |
| 279 | let body = one_menu(&menu, user.get_id(), &st.db).await?; | 278 | let body = one_menu(&menu, user.get_id(), &st.db).await?; |
| 280 | Ok((StatusCode::CREATED, body)) | 279 | Ok((StatusCode::CREATED, body)) |
| 281 | } | 280 | } |
| @@ -306,7 +305,8 @@ async fn list_menus( | |||
| 306 | let (limit, offset) = page.resolve()?; | 305 | let (limit, offset) = page.resolve()?; |
| 307 | let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; | 306 | let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; |
| 308 | let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; | 307 | let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; |
| 309 | - let (menus, total) = Menu::list(from.as_ref(), to.as_ref(), limit, offset, &st.db).await?; | 308 | + let (menus, total) = |
| 309 | + service::menu::list(&st.db, from.as_ref(), to.as_ref(), limit, offset).await?; | ||
| 310 | // The dish/people join runs over the page alone, so it shrinks with it. | 310 | // The dish/people join runs over the page alone, so it shrinks with it. |
| 311 | let items = menu_responses(&menus, user.get_id(), &st.db).await?; | 311 | let items = menu_responses(&menus, user.get_id(), &st.db).await?; |
| 312 | Ok(Json(Page::new(items, total, limit, offset))) | 312 | Ok(Json(Page::new(items, total, limit, offset))) |
| @@ -330,7 +330,7 @@ async fn get_menu( | |||
| 330 | CurrentUser(user): CurrentUser, | 330 | CurrentUser(user): CurrentUser, |
| 331 | Path(id): Path<String>, | 331 | Path(id): Path<String>, |
| 332 | ) -> Result<Json<MenuResponse>, AppError> { | 332 | ) -> Result<Json<MenuResponse>, AppError> { |
| 333 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 333 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 334 | .await? | 334 | .await? |
| 335 | .ok_or(AppError::NotFound)?; | 335 | .ok_or(AppError::NotFound)?; |
| 336 | one_menu(&menu, user.get_id(), &st.db).await | 336 | one_menu(&menu, user.get_id(), &st.db).await |
| @@ -363,10 +363,10 @@ async fn update_menu( | |||
| 363 | if let Some(capacity) = req.capacity { | 363 | if let Some(capacity) = req.capacity { |
| 364 | validate_capacity(capacity)?; | 364 | validate_capacity(capacity)?; |
| 365 | } | 365 | } |
| 366 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 366 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 367 | .await? | 367 | .await? |
| 368 | .ok_or(AppError::NotFound)?; | 368 | .ok_or(AppError::NotFound)?; |
| 369 | - let updated = menu.update(req.capacity, &st.db).await?; | 369 | + let updated = service::menu::update(&st.db, menu, req.capacity).await?; |
| 370 | one_menu(&updated, user.get_id(), &st.db).await | 370 | one_menu(&updated, user.get_id(), &st.db).await |
| 371 | } | 371 | } |
| 372 | 372 | ||
| @@ -392,12 +392,13 @@ async fn delete_menu( | |||
| 392 | RequireManager(_user): RequireManager, | 392 | RequireManager(_user): RequireManager, |
| 393 | Path(id): Path<String>, | 393 | Path(id): Path<String>, |
| 394 | ) -> Result<StatusCode, AppError> { | 394 | ) -> Result<StatusCode, AppError> { |
| 395 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 395 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 396 | .await? | 396 | .await? |
| 397 | .ok_or(AppError::NotFound)?; | 397 | .ok_or(AppError::NotFound)?; |
| 398 | - // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so | 398 | + // The seat check rides in the delete's own `WHERE` (the persistence |
| 399 | - // a concurrent booking cannot slip between the read and the delete. | 399 | + // layer's `menu::delete`), so a concurrent booking cannot slip between |
| 400 | - menu.delete(&st.db).await?; | 400 | + // the read and the delete. |
| 401 | + service::menu::delete(&st.db, menu).await?; | ||
| 401 | Ok(StatusCode::NO_CONTENT) | 402 | Ok(StatusCode::NO_CONTENT) |
| 402 | } | 403 | } |
| 403 | 404 | ||
| @@ -438,28 +439,21 @@ async fn add_dish( | |||
| 438 | &req.tags, | 439 | &req.tags, |
| 439 | &service::settings::load(&st.db).await?.get_dietary_tags(), | 440 | &service::settings::load(&st.db).await?.get_dietary_tags(), |
| 440 | )?; | 441 | )?; |
| 441 | - // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write | 442 | + // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK) |
| 442 | - // is write-skew, so the count and the insert have to be one step. The | 443 | + // lease live in the service: count-then-write is write-skew, so the count |
| 443 | - // *price* no longer needs it — a dish write moves the menu's revision, and | 444 | + // and the insert have to be one step, and the menu is read *inside* the |
| 444 | - // a booking claims its seat at the revision it priced itself against. | 445 | + // lock — read before it, a `DELETE /menus/{id}` running in the gap takes |
| 445 | - // The lock is a leaf again: the revision bump rides the dish write's own | 446 | + // its cascade with it and this dish lands on a menu that no longer exists. |
| 446 | - // transaction now, so nothing held under it takes `cap`'s counter lock. It | 447 | + let dish = service::menu::add_dish( |
| 447 | - // stays a leaf only while that holds — see [`MENU_LOCK`] for the order a | 448 | + &st.db, |
| 448 | - // caller that changes it must keep. | 449 | + &MenuId::from_key(&id), |
| 449 | - let _guard = MENU_LOCK.lock().await; | 450 | + name, |
| 450 | - // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` | 451 | + description, |
| 451 | - // running in the gap takes its cascade with it and this dish lands on a menu | 452 | + price, |
| 452 | - // that no longer exists. | 453 | + tags, |
| 453 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 454 | + ) |
| 454 | - .await? | 455 | + .await?; |
| 455 | - .ok_or(AppError::NotFound)?; | 456 | + let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; |
| 456 | - if MenuDish::count_for_menu(menu.get_id(), &st.db).await? >= MAX_DISHES_PER_MENU { | ||
| 457 | - return Err(AppError::Conflict( | ||
| 458 | - "the menu already carries the maximum number of dishes", | ||
| 459 | - )); | ||
| 460 | - } | ||
| 461 | - let dish = MenuDish::create(menu.get_id(), name, description, price, tags, &st.db).await?; | ||
| 462 | - let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; | ||
| 463 | Ok(( | 457 | Ok(( |
| 464 | StatusCode::CREATED, | 458 | StatusCode::CREATED, |
| 465 | Json(DishResponse::new(&dish, &viewer_tags)), | 459 | Json(DishResponse::new(&dish, &viewer_tags)), |
| @@ -490,7 +484,7 @@ async fn update_dish( | |||
| 490 | Path(did): Path<String>, | 484 | Path(did): Path<String>, |
| 491 | Json(req): Json<UpdateDish>, | 485 | Json(req): Json<UpdateDish>, |
| 492 | ) -> Result<Json<DishResponse>, AppError> { | 486 | ) -> Result<Json<DishResponse>, AppError> { |
| 493 | - let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) | 487 | + let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) |
| 494 | .await? | 488 | .await? |
| 495 | .ok_or(AppError::NotFound)?; | 489 | .ok_or(AppError::NotFound)?; |
| 496 | let name = req.name.as_deref().map(DishName::try_new).transpose()?; | 490 | let name = req.name.as_deref().map(DishName::try_new).transpose()?; |
| @@ -509,10 +503,10 @@ async fn update_dish( | |||
| 509 | )?), | 503 | )?), |
| 510 | None => None, | 504 | None => None, |
| 511 | }; | 505 | }; |
| 512 | - // Under [`MENU_LOCK`] like every dish write — see `add_dish`. | 506 | + // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) |
| 513 | - let _guard = MENU_LOCK.lock().await; | 507 | + // inside the service, like every dish write — see `add_dish`. |
| 514 | - let updated = dish.update(name, description, price, tags, &st.db).await?; | 508 | + let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; |
| 515 | - let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; | 509 | + let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; |
| 516 | Ok(Json(DishResponse::new(&updated, &viewer_tags))) | 510 | Ok(Json(DishResponse::new(&updated, &viewer_tags))) |
| 517 | } | 511 | } |
| 518 | 512 | ||
| @@ -535,12 +529,12 @@ async fn delete_dish( | |||
| 535 | RequireManager(_user): RequireManager, | 529 | RequireManager(_user): RequireManager, |
| 536 | Path(did): Path<String>, | 530 | Path(did): Path<String>, |
| 537 | ) -> Result<StatusCode, AppError> { | 531 | ) -> Result<StatusCode, AppError> { |
| 538 | - let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) | 532 | + let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) |
| 539 | .await? | 533 | .await? |
| 540 | .ok_or(AppError::NotFound)?; | 534 | .ok_or(AppError::NotFound)?; |
| 541 | - // Under [`MENU_LOCK`] like every dish write — see `add_dish`. | 535 | + // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) |
| 542 | - let _guard = MENU_LOCK.lock().await; | 536 | + // inside the service, like every dish write — see `add_dish`. |
| 543 | - dish.delete(&st.db).await?; | 537 | + service::menu::delete_dish(&st.db, dish).await?; |
| 544 | Ok(StatusCode::NO_CONTENT) | 538 | Ok(StatusCode::NO_CONTENT) |
| 545 | } | 539 | } |
| 546 | 540 | ||
| @@ -578,7 +572,7 @@ async fn profile_response( | |||
| 578 | student: &UserId, | 572 | student: &UserId, |
| 579 | db: &Database, | 573 | db: &Database, |
| 580 | ) -> Result<Json<DietaryProfileResponse>, AppError> { | 574 | ) -> Result<Json<DietaryProfileResponse>, AppError> { |
| 581 | - let profile = DietaryProfile::read(student, db).await?; | 575 | + let profile = service::dietary_profile::read(db, student).await?; |
| 582 | let people = person_map( | 576 | let people = person_map( |
| 583 | std::iter::once(student.clone()) | 577 | std::iter::once(student.clone()) |
| 584 | .chain(profile.as_ref().map(|row| row.get_updated_by().clone())), | 578 | .chain(profile.as_ref().map(|row| row.get_updated_by().clone())), |
| @@ -701,7 +695,7 @@ async fn update_profile( | |||
| 701 | Some(None) => Some(None), | 695 | Some(None) => Some(None), |
| 702 | Some(Some(text)) => Some(DietaryNote::try_new(&text)?), | 696 | Some(Some(text)) => Some(DietaryNote::try_new(&text)?), |
| 703 | }; | 697 | }; |
| 704 | - DietaryProfile::save(&target, tags, note, manager.get_id(), &st.db).await?; | 698 | + service::dietary_profile::save(&st.db, &target, tags, note, manager.get_id()).await?; |
| 705 | profile_response(&target, &st.db).await | 699 | profile_response(&target, &st.db).await |
| 706 | } | 700 | } |
| 707 | 701 | ||
| @@ -939,7 +933,7 @@ async fn list_menu_bookings( | |||
| 939 | Query(page): Query<PageParams>, | 933 | Query(page): Query<PageParams>, |
| 940 | ) -> Result<Json<Page<BookingResponse>>, AppError> { | 934 | ) -> Result<Json<Page<BookingResponse>>, AppError> { |
| 941 | let (limit, offset) = page.resolve()?; | 935 | let (limit, offset) = page.resolve()?; |
| 942 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 936 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 943 | .await? | 937 | .await? |
| 944 | .ok_or(AppError::NotFound)?; | 938 | .ok_or(AppError::NotFound)?; |
| 945 | let (rows, total) = | 939 | let (rows, total) = |
| @@ -1139,25 +1133,30 @@ async fn mark_attendance( | |||
| 1139 | Path(id): Path<String>, | 1133 | Path(id): Path<String>, |
| 1140 | Json(req): Json<MarkMealAttendance>, | 1134 | Json(req): Json<MarkMealAttendance>, |
| 1141 | ) -> Result<Json<MealAttendanceResponse>, AppError> { | 1135 | ) -> Result<Json<MealAttendanceResponse>, AppError> { |
| 1142 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 1136 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 1143 | .await? | 1137 | .await? |
| 1144 | .ok_or(AppError::NotFound)?; | 1138 | .ok_or(AppError::NotFound)?; |
| 1145 | let status = MealAttendanceStatus::try_new(&req.status)?; | 1139 | let status = MealAttendanceStatus::try_new(&req.status)?; |
| 1146 | let student = UserId::from_key(&req.student_id); | 1140 | let student = UserId::from_key(&req.student_id); |
| 1147 | // The target must exist; no booking is required, since a walk-in was still | 1141 | // The target must exist; no booking is required, since a walk-in was still |
| 1148 | // served and the record is operationally true. | 1142 | // served and the record is operationally true. |
| 1149 | - if crate::service::user::read(&st.db, &student).await?.is_none() { | 1143 | + if crate::service::user::read(&st.db, &student) |
| 1144 | + .await? | ||
| 1145 | + .is_none() | ||
| 1146 | + { | ||
| 1150 | return Err(AppError::Validation(ValidationError::Invalid { | 1147 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1151 | field: "student_id", | 1148 | field: "student_id", |
| 1152 | reason: "target user does not exist", | 1149 | reason: "target user does not exist", |
| 1153 | })); | 1150 | })); |
| 1154 | } | 1151 | } |
| 1155 | - // The write moves the menu's own revision (see [`MealAttendance::mark`]), so | 1152 | + // The write moves the menu's own revision (see the persistence layer's |
| 1153 | + // `meal_attendance::mark`), so | ||
| 1156 | // a delete landing between the read above and this write cannot commit | 1154 | // a delete landing between the read above and this write cannot commit |
| 1157 | // alongside it — one of the two loses its round, and this one then answers | 1155 | // alongside it — one of the two loses its round, and this one then answers |
| 1158 | // 404 with no mark behind it, exactly as the read would have. | 1156 | // 404 with no mark behind it, exactly as the read would have. |
| 1159 | let row = | 1157 | let row = |
| 1160 | - MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?; | 1158 | + service::meal_attendance::mark(&st.db, menu.get_id(), &student, status, marker.get_id()) |
| 1159 | + .await?; | ||
| 1161 | let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; | 1160 | let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; |
| 1162 | Ok(Json( | 1161 | Ok(Json( |
| 1163 | items.into_iter().next().expect("one mark in, one out"), | 1162 | items.into_iter().next().expect("one mark in, one out"), |
| @@ -1187,10 +1186,11 @@ async fn list_menu_attendance( | |||
| 1187 | ) -> Result<Json<Page<MealAttendanceResponse>>, AppError> { | 1186 | ) -> Result<Json<Page<MealAttendanceResponse>>, AppError> { |
| 1188 | let (limit, offset) = page.resolve()?; | 1187 | let (limit, offset) = page.resolve()?; |
| 1189 | // Menu must exist — a missing menu is a 404, not an empty list. | 1188 | // Menu must exist — a missing menu is a 404, not an empty list. |
| 1190 | - let menu = Menu::read(&MenuId::from_key(&id), &st.db) | 1189 | + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) |
| 1191 | .await? | 1190 | .await? |
| 1192 | .ok_or(AppError::NotFound)?; | 1191 | .ok_or(AppError::NotFound)?; |
| 1193 | - let (rows, total) = MealAttendance::list_for_menu(menu.get_id(), limit, offset, &st.db).await?; | 1192 | + let (rows, total) = |
| 1193 | + service::meal_attendance::list_for_menu(&st.db, menu.get_id(), limit, offset).await?; | ||
| 1194 | let items = attendance_responses(&rows, &st.db).await?; | 1194 | let items = attendance_responses(&rows, &st.db).await?; |
| 1195 | Ok(Json(Page::new(items, total, limit, offset))) | 1195 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1196 | } | 1196 | } |
| @@ -1225,13 +1225,13 @@ async fn user_attendance( | |||
| 1225 | ensure_can_read_student(&caller, &target, &st.db).await?; | 1225 | ensure_can_read_student(&caller, &target, &st.db).await?; |
| 1226 | let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; | 1226 | let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; |
| 1227 | let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; | 1227 | let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; |
| 1228 | - let (rows, total) = MealAttendance::list_for_student( | 1228 | + let (rows, total) = service::meal_attendance::list_for_student( |
| 1229 | + &st.db, | ||
| 1229 | &target, | 1230 | &target, |
| 1230 | from.as_ref(), | 1231 | from.as_ref(), |
| 1231 | to.as_ref(), | 1232 | to.as_ref(), |
| 1232 | limit, | 1233 | limit, |
| 1233 | offset, | 1234 | offset, |
| 1234 | - &st.db, | ||
| 1235 | ) | 1235 | ) |
| 1236 | .await?; | 1236 | .await?; |
| 1237 | let items = attendance_responses(&rows, &st.db).await?; | 1237 | let items = attendance_responses(&rows, &st.db).await?; |
| @@ -1311,7 +1311,7 @@ async fn balance_response( | |||
| 1311 | let people = person_map(std::iter::once(student.clone()), db).await?; | 1311 | let people = person_map(std::iter::once(student.clone()), db).await?; |
| 1312 | Ok(Json(BalanceResponse { | 1312 | Ok(Json(BalanceResponse { |
| 1313 | student: PersonRef::resolve(&people, student), | 1313 | student: PersonRef::resolve(&people, student), |
| 1314 | - balance_minor: MealLedger::balance_of(student, db).await?, | 1314 | + balance_minor: service::meal_ledger::balance_of(db, student).await?, |
| 1315 | })) | 1315 | })) |
| 1316 | } | 1316 | } |
| 1317 | 1317 | ||
| @@ -1431,7 +1431,8 @@ async fn user_ledger( | |||
| 1431 | let (limit, offset) = page.resolve()?; | 1431 | let (limit, offset) = page.resolve()?; |
| 1432 | let target = UserId::from_key(&user); | 1432 | let target = UserId::from_key(&user); |
| 1433 | ensure_can_read_money(&caller, &target, &st.db).await?; | 1433 | ensure_can_read_money(&caller, &target, &st.db).await?; |
| 1434 | - let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?; | 1434 | + let (rows, total) = |
| 1435 | + service::meal_ledger::list_for_student(&st.db, &target, limit, offset).await?; | ||
| 1435 | let items = ledger_responses(&rows, &st.db).await?; | 1436 | let items = ledger_responses(&rows, &st.db).await?; |
| 1436 | Ok(Json(Page::new(items, total, limit, offset))) | 1437 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1437 | } | 1438 | } |
| @@ -1504,7 +1505,7 @@ async fn record_credit( | |||
| 1504 | .ok_or(AppError::NotFound)? | 1505 | .ok_or(AppError::NotFound)? |
| 1505 | .get_role() | 1506 | .get_role() |
| 1506 | != Role::Student | 1507 | != Role::Student |
| 1507 | - && MealLedger::list_for_student(&student, Some(1), 0, &st.db) | 1508 | + && service::meal_ledger::list_for_student(&st.db, &student, Some(1), 0) |
| 1508 | .await? | 1509 | .await? |
| 1509 | .0 | 1510 | .0 |
| 1510 | .is_empty() | 1511 | .is_empty() |
| @@ -1519,7 +1520,8 @@ async fn record_credit( | |||
| 1519 | .as_deref() | 1520 | .as_deref() |
| 1520 | .map(PaymentRequestKey::try_new) | 1521 | .map(PaymentRequestKey::try_new) |
| 1521 | .transpose()?; | 1522 | .transpose()?; |
| 1522 | - let line = MealLedger::credit( | 1523 | + let line = service::meal_ledger::credit( |
| 1524 | + &st.db, | ||
| 1523 | &student, | 1525 | &student, |
| 1524 | LedgerAmount::try_new(req.amount_minor)?, | 1526 | LedgerAmount::try_new(req.amount_minor)?, |
| 1525 | req.method | 1527 | req.method |
| @@ -1534,7 +1536,6 @@ async fn record_credit( | |||
| 1534 | .flatten(), | 1536 | .flatten(), |
| 1535 | request_key.as_ref(), | 1537 | request_key.as_ref(), |
| 1536 | admin.get_id(), | 1538 | admin.get_id(), |
| 1537 | - &st.db, | ||
| 1538 | ) | 1539 | ) |
| 1539 | .await?; | 1540 | .await?; |
| 1540 | let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?; | 1541 | let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?; |
tests/integration.rsmodified+8 -7
| @@ -22187,8 +22187,9 @@ async fn concurrent_duplicate_menu_publishes_conflict_not_500() { | |||
| 22187 | /// writers before they can ever collide. | 22187 | /// writers before they can ever collide. |
| 22188 | #[tokio::test] | 22188 | #[tokio::test] |
| 22189 | async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { | 22189 | async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { |
| 22190 | + use hezarfen_backend::db::meal_ledger; | ||
| 22190 | use hezarfen_backend::domain::meal_booking::MealBookingId; | 22191 | use hezarfen_backend::domain::meal_booking::MealBookingId; |
| 22191 | - use hezarfen_backend::domain::meal_ledger::MealLedger; | 22192 | + use hezarfen_backend::service::meal_ledger as ledger_service; |
| 22192 | 22193 | ||
| 22193 | let (app, db) = app_and_db().await; | 22194 | let (app, db) = app_and_db().await; |
| 22194 | let mgr = login_as(&app, &db, "ledger_race_mgr", "manager").await; | 22195 | let mgr = login_as(&app, &db, "ledger_race_mgr", "manager").await; |
| @@ -22233,14 +22234,14 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { | |||
| 22233 | .expect("the booking exists"); | 22234 | .expect("the booking exists"); |
| 22234 | let student = booking.get_student().clone(); | 22235 | let student = booking.get_student().clone(); |
| 22235 | assert_eq!( | 22236 | assert_eq!( |
| 22236 | - MealLedger::balance_of(&student, &db).await.unwrap(), | 22237 | + meal_ledger::balance_of(&db, &student).await.unwrap(), |
| 22237 | -1000, | 22238 | -1000, |
| 22238 | "the seat was charged once" | 22239 | "the seat was charged once" |
| 22239 | ); | 22240 | ); |
| 22240 | 22241 | ||
| 22241 | let (first, second) = tokio::join!( | 22242 | let (first, second) = tokio::join!( |
| 22242 | - MealLedger::reverse_booking(&booking, &student, &db), | 22243 | + ledger_service::reverse_booking(&db, &booking, &student), |
| 22243 | - MealLedger::reverse_booking(&booking, &student, &db), | 22244 | + ledger_service::reverse_booking(&db, &booking, &student), |
| 22244 | ); | 22245 | ); |
| 22245 | assert!(first.is_ok(), "the winner appended: {first:?}"); | 22246 | assert!(first.is_ok(), "the winner appended: {first:?}"); |
| 22246 | assert!( | 22247 | assert!( |
| @@ -22248,12 +22249,12 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { | |||
| 22248 | "the loser must read back the winner's line, not fail: {second:?}" | 22249 | "the loser must read back the winner's line, not fail: {second:?}" |
| 22249 | ); | 22250 | ); |
| 22250 | 22251 | ||
| 22251 | - let (lines, _) = MealLedger::list_for_student(&student, None, 0, &db) | 22252 | + let (lines, _) = meal_ledger::list_for_student(&db, &student, None, 0) |
| 22252 | .await | 22253 | .await |
| 22253 | .unwrap(); | 22254 | .unwrap(); |
| 22254 | assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); | 22255 | assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); |
| 22255 | assert_eq!( | 22256 | assert_eq!( |
| 22256 | - MealLedger::balance_of(&student, &db).await.unwrap(), | 22257 | + meal_ledger::balance_of(&db, &student).await.unwrap(), |
| 22257 | 0, | 22258 | 0, |
| 22258 | "the money moved back exactly once" | 22259 | "the money moved back exactly once" |
| 22259 | ); | 22260 | ); |
| @@ -23941,7 +23942,7 @@ async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { | |||
| 23941 | /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of | 23942 | /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of |
| 23942 | /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the | 23943 | /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the |
| 23943 | /// concurrent claim lives where the store can testify about it — | 23944 | /// concurrent claim lives where the store can testify about it — |
| 23944 | -/// `domain::menu::tests::a_child_written_inside_a_delete_never_outlives_the_menu`, | 23945 | +/// `db::menu::tests::a_child_written_inside_a_delete_never_outlives_the_menu`, |
| 23945 | /// `#[ignore]`d and run against a real server — and what stays here is the | 23946 | /// `#[ignore]`d and run against a real server — and what stays here is the |
| 23946 | /// logic, pinned deterministically. | 23947 | /// logic, pinned deterministically. |
| 23947 | #[tokio::test] | 23948 | #[tokio::test] |
tests/regress_meals.rsmodified+9 -7
| @@ -11,8 +11,10 @@ mod common; | |||
| 11 | 11 | ||
| 12 | use axum::http::StatusCode; | 12 | use axum::http::StatusCode; |
| 13 | use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; | 13 | use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; |
| 14 | -use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | 14 | +use hezarfen_backend::db::meal_attendance; |
| 15 | -use hezarfen_backend::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; | 15 | +use hezarfen_backend::db::menu; |
| 16 | +use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus; | ||
| 17 | +use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot}; | ||
| 16 | use hezarfen_backend::domain::settings::MealSlotDef; | 18 | use hezarfen_backend::domain::settings::MealSlotDef; |
| 17 | use hezarfen_backend::domain::user::UserId; | 19 | use hezarfen_backend::domain::user::UserId; |
| 18 | use hezarfen_backend::error::AppError; | 20 | use hezarfen_backend::error::AppError; |
| @@ -108,12 +110,12 @@ async fn a_menu_behind_the_calendar_is_neither_publishable_nor_bookable() { | |||
| 108 | // Half two: the menu the create-side check cannot reach — published while | 110 | // Half two: the menu the create-side check cannot reach — published while |
| 109 | // its day was still ahead, written here as the store holds it, since no | 111 | // its day was still ahead, written here as the store holds it, since no |
| 110 | // route publishes one any more. | 112 | // route publishes one any more. |
| 111 | - let stale = Menu::create( | 113 | + let stale = menu::create( |
| 114 | + &db, | ||
| 112 | MenuDate::try_new("2020-01-02").unwrap(), | 115 | MenuDate::try_new("2020-01-02").unwrap(), |
| 113 | MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap(), | 116 | MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap(), |
| 114 | None, | 117 | None, |
| 115 | &UserId::from_key(&me_id(&app, &mgr).await), | 118 | &UserId::from_key(&me_id(&app, &mgr).await), |
| 116 | - &db, | ||
| 117 | ) | 119 | ) |
| 118 | .await | 120 | .await |
| 119 | .expect("the domain still writes what the volume may hold"); | 121 | .expect("the domain still writes what the volume may hold"); |
| @@ -467,12 +469,12 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() { | |||
| 467 | .await; | 469 | .await; |
| 468 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | 470 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 469 | 471 | ||
| 470 | - let marked = MealAttendance::mark( | 472 | + let marked = meal_attendance::mark( |
| 473 | + &db, | ||
| 471 | &menu, | 474 | &menu, |
| 472 | &ali_id, | 475 | &ali_id, |
| 473 | MealAttendanceStatus::try_new("served").unwrap(), | 476 | MealAttendanceStatus::try_new("served").unwrap(), |
| 474 | &mgr_id, | 477 | &mgr_id, |
| 475 | - &db, | ||
| 476 | ) | 478 | ) |
| 477 | .await | 479 | .await |
| 478 | .expect_err("the mark is refused"); | 480 | .expect_err("the mark is refused"); |
| @@ -481,7 +483,7 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() { | |||
| 481 | "no menu, no mark: {marked:?}" | 483 | "no menu, no mark: {marked:?}" |
| 482 | ); | 484 | ); |
| 483 | assert_eq!( | 485 | assert_eq!( |
| 484 | - MealAttendance::list_for_menu(&menu, None, 0, &db) | 486 | + meal_attendance::list_for_menu(&db, &menu, None, 0) |
| 485 | .await | 487 | .await |
| 486 | .unwrap() | 488 | .unwrap() |
| 487 | .1, | 489 | .1, |