From d5481204ffd92d42643485074f2096a4e5fd4e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 14:41:15 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20meal=5Fattendan?= =?UTF-8?q?ce,=20meal=5Fledger,=20menu,=20menu=5Fdish,=20dietary=5Fprofile?= =?UTF-8?q?=20into=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - db/: menu (publish/read/find/list/CAS cap update/cascading delete + bump_menu_and_write), menu_dish (create/read/listings/count/patch/delete), meal_attendance (mark/list_for_menu/list_for_student), meal_ledger (append/read/price_snapshot/list_for_student/balance_of + KindTotal), dietary_profile (read/tags_of/save). Bodies byte-identical; entity fields pub(crate) for cross-layer construction (exam precedent). - service/: menu owns MENU_LOCK (multi-call count-then-write span) and every dish write (add_dish with the MAX_DISHES_PER_MENU gate, update_dish/delete_dish) plus menu/dish read pass-throughs; meal_ledger owns charge_booking/reverse_booking/credit orchestration; meal_attendance and dietary_profile are read-through pass-throughs. - domain/: pure remnants only — ids, newtypes, getters, sign convention, charge_for/reversal_for row builders, conflicts; ULID IDS minters stay; persistence tests ride with their fns into db/. - web/meals.rs: handlers call service::* only; MENU_LOCK leases and the dish-cap gate moved out; validation order preserved. - re-pointed merged callers (service/meal_booking, db/meal_booking, db/exam_attempt doc link) and test imports (integration, regress_meals). cargo check --all-targets clean; cargo test --lib 577 passed 0 failed; cargo test --test regress_meals 18 passed 0 failed. --- src/db/dietary_profile.rs | 73 ++++ src/db/exam_attempt.rs | 2 +- src/db/meal_attendance.rs | 114 ++++++ src/db/meal_booking.rs | 71 ++-- src/db/meal_ledger.rs | 195 ++++++++++ src/db/menu.rs | 608 +++++++++++++++++++++++++++++++ src/db/menu_dish.rs | 175 +++++++++ src/db/mod.rs | 6 +- src/domain/dietary_profile.rs | 82 +---- src/domain/meal_attendance.rs | 117 +----- src/domain/meal_ledger.rs | 332 ++--------------- src/domain/menu.rs | 644 ++------------------------------- src/domain/menu_dish.rs | 187 +--------- src/service/dietary_profile.rs | 32 ++ src/service/meal_attendance.rs | 49 +++ src/service/meal_booking.rs | 44 ++- src/service/meal_ledger.rs | 138 +++++++ src/service/menu.rs | 161 +++++++++ src/service/mod.rs | 5 +- src/web/meals.rs | 127 +++---- tests/integration.rs | 15 +- tests/regress_meals.rs | 16 +- 22 files changed, 1783 insertions(+), 1410 deletions(-) create mode 100644 src/db/dietary_profile.rs create mode 100644 src/db/meal_attendance.rs create mode 100644 src/db/meal_ledger.rs create mode 100644 src/db/menu.rs create mode 100644 src/db/menu_dish.rs create mode 100644 src/service/dietary_profile.rs create mode 100644 src/service/meal_attendance.rs create mode 100644 src/service/meal_ledger.rs create mode 100644 src/service/menu.rs diff --git a/src/db/dietary_profile.rs b/src/db/dietary_profile.rs new file mode 100644 index 0000000..80f8ce4 --- /dev/null +++ b/src/db/dietary_profile.rs @@ -0,0 +1,73 @@ +//! The `dietary_profile` table: one row per student (the record key *is* +//! the student's key), created on first write and afterwards patched +//! field-by-field. The tag/note newtypes and the pure tag intersection live +//! in [`crate::domain::dietary_profile`]; the web layer reads through +//! [`crate::service::dietary_profile`]. + +use crate::database::Database; +use crate::db::field_update::FieldUpdate; +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// One student's profile, or `None` while the school never recorded one. +/// A single `SELECT` by record id — this is what a menu read joins on. +pub async fn read(db: &Database, student: &UserId) -> Result, AppError> { + Ok(db.select(DietaryProfileId::of(student).record()).await?) +} + +/// The tags a menu read matches its dishes against: the caller's, or an +/// empty list when they have no profile (every manager, every teacher). +pub async fn tags_of(db: &Database, student: &UserId) -> Result, AppError> { + Ok(read(db, student) + .await? + .map(|profile| profile.get_tags().as_slice().to_vec()) + .unwrap_or_default()) +} + +/// Write the fields the PATCH carried. Creates the row on first write; +/// afterwards only the named fields move, because `student` is `READONLY` +/// and a whole-row save would also revert a concurrent edit of the other +/// field (see [`FieldUpdate`]). +pub async fn save( + db: &Database, + student: &UserId, + tags: Option, + note: Option>, + by: &UserId, +) -> Result { + if read(db, student).await?.is_none() { + let profile = DietaryProfile { + id: DietaryProfileId::of(student), + student: student.clone(), + tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), + note: note.clone().flatten(), + updated_by: by.clone(), + updated_at: Timestamp::now(), + }; + match db.create(profile.id.record()).content(profile).await { + Ok(Some(created)) => return Ok(created), + Ok(None) => { + return Err(AppError::Internal("failed to save the profile".into())); + } + // A rival first `PATCH` created the row in the round trip since + // the read above (the `dietary_profile_student` UNIQUE index + // catches the same collision), and `CREATE` leaves that row + // untouched — so this call is a plain field write after all, + // exactly as it would have been a moment later. Propagated, it + // was a 500 on a legitimate request. Same shape as + // [`crate::db::meal_ledger::append`], which + // reads the winner back rather than failing. + Err(err) if err.is_already_exists() => {} + Err(err) => return Err(err.into()), + } + } + FieldUpdate::new(DietaryProfileId::of(student).record()) + .set("tags", tags) + .set("note", note) + .set("updated_by", Some(by.clone())) + .set("updated_at", Some(Timestamp::now())) + .run::(db) + .await +} diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0e07a1b..a86bd2a 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -172,7 +172,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result Result { + let row = MealAttendance { + id: MealAttendanceId::composite(menu, student), + menu: menu.clone(), + student: student.clone(), + status, + marked_by: marked_by.clone(), + marked_at: Timestamp::now(), + }; + // Admissible for the retry loop inside: the id is bijective with the + // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` + // resolves onto the row that index already points at instead of + // colliding with it — it can never answer "already exists", and a + // re-sent round writes the identical row. + bump_menu_and_write( + menu, + "UPSERT $id CONTENT $row RETURN AFTER", + vec![ + ("id".into(), row.id.record().into_value()), + ("row".into(), row.into_value()), + ], + db, + ) + .await? + .ok_or_else(|| AppError::Internal("failed to record the mark".into())) +} + +/// The kitchen's list for one menu. +pub async fn list_for_menu( + db: &Database, + menu: &MenuId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_attendance WHERE menu = $menu", + "ORDER BY marked_at DESC, id DESC", + ) + .bind("menu", menu.record()) + .run(limit, offset, db) + .await +} + +/// One student's marks, newest first. `from`/`to` are inclusive +/// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, +/// which is chronological for that format (see [`MenuDate`]), and the link +/// is followed rather than denormalized so a row can never disagree with +/// the menu it belongs to. +pub async fn list_for_student( + db: &Database, + student: &UserId, + from: Option<&MenuDate>, + to: Option<&MenuDate>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_attendance WHERE student = $usr \ + AND ($from = NONE OR menu.date >= $from) \ + AND ($to = NONE OR menu.date <= $to)", + "ORDER BY marked_at DESC, id DESC", + ) + .bind("usr", student.record()) + .bind("from", from.map(|date| date.as_str().to_string())) + .bind("to", to.map(|date| date.as_str().to_string())) + .run(limit, offset, db) + .await +} diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index 34d3c4f..3fa6a17 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -306,8 +306,11 @@ mod tests { use super::*; use crate::database::init_mem; use crate::db::cap; + use crate::db::meal_ledger; + use crate::db::menu; + use crate::db::menu_dish; use crate::domain::meal_booking::{MealBookingStatus, MealCutoff}; - use crate::domain::menu::{Menu, MenuDate, MenuSlot}; + use crate::domain::menu::{MenuDate, MenuSlot}; use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; use crate::domain::settings::MealSlotDef; use crate::service::meal_booking; @@ -322,12 +325,12 @@ mod tests { async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { let db = init_mem().await.unwrap(); let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; - let menu = Menu::create( + let menu = menu::create( + &db, MenuDate::try_new(date).unwrap(), MenuSlot::try_new("lunch", &slots).unwrap(), capacity, &UserId::generate(), - &db, ) .await .unwrap(); @@ -354,13 +357,13 @@ mod tests { } async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { - MenuDish::create( + menu_dish::create( + db, menu, DishName::try_new("çorba").unwrap(), None, DishPrice::try_new(price).unwrap(), DishTags::try_new(&[], &[]).unwrap(), - db, ) .await .unwrap() @@ -374,7 +377,7 @@ mod tests { async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { let (db, menu) = menu(None).await; let ali = UserId::generate(); - let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); // A dish lands: the price a booking read a moment ago is now stale. add_dish(&menu, 1_000, &db).await; let row = MealBooking { @@ -404,7 +407,7 @@ mod tests { ); // Re-read, and the same seat is taken with the row it belongs to. - let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + let now = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); assert!(now > seen); assert!(matches!(place(now).await, Claimed::Made(_))); assert_eq!(seats(&menu, &db).await, 1); @@ -426,7 +429,7 @@ mod tests { let (db, id) = menu(None).await; let mut seen = 0; let mut moved = async |db: &Database| { - let now = Menu::read(&id, db).await.unwrap().unwrap().get_version(); + let now = menu::read(db, &id).await.unwrap().unwrap().get_version(); let stepped = now > seen; seen = now; stepped @@ -435,26 +438,26 @@ mod tests { let dish = add_dish(&id, 1_000, &db).await; assert!(moved(&db).await, "a dish added"); - let dish = dish - .update( - None, - None, - Some(DishPrice::try_new(2_000).unwrap()), - None, - &db, - ) - .await - .unwrap(); + let dish = menu_dish::update( + &db, + dish, + None, + None, + Some(DishPrice::try_new(2_000).unwrap()), + None, + ) + .await + .unwrap(); assert!(moved(&db).await, "a dish re-priced"); - dish.delete(&db).await.unwrap(); + menu_dish::delete(&db, dish).await.unwrap(); assert!(moved(&db).await, "a dish removed"); - Menu::read(&id, &db) - .await - .unwrap() - .unwrap() - .update(Some(Some(5)), &db) - .await - .unwrap(); + menu::update( + &db, + menu::read(&db, &id).await.unwrap().unwrap(), + Some(Some(5)), + ) + .await + .unwrap(); assert!(moved(&db).await, "the capacity moved"); } @@ -493,7 +496,7 @@ mod tests { assert_eq!(stored.get_attempt(), live.get_attempt()); assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); assert_eq!( - MealLedger::balance_of(&ali, &db).await.unwrap(), + meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000, "the live attempt's charge stands: it was never cancelled" ); @@ -530,7 +533,7 @@ mod tests { assert_eq!(freed.get_status(), MealBookingStatus::Cancelled); assert_eq!(seats(&menu, &db).await, 0); assert_eq!( - MealLedger::balance_of(&ali, &db).await.unwrap(), + meal_ledger::balance_of(&db, &ali).await.unwrap(), 0, "the reversal must have committed with the flip, not after it" ); @@ -540,7 +543,7 @@ mod tests { meal_booking::book(&db, &menu, &ali, &ali, &open) .await .unwrap(); - assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); + assert_eq!(meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000); } /// The seat may not be held without its money. Driven against @@ -555,8 +558,8 @@ mod tests { let (db, menu) = menu(None).await; let ali = UserId::generate(); add_dish(&menu, 1_000, &db).await; - let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); - let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); + let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); let row = MealBooking { id: MealBookingId::composite(&menu, &ali), menu: menu.clone(), @@ -586,7 +589,7 @@ mod tests { assert!(matches!(place().await, Claimed::Made(_))); assert_eq!(seats(&menu, &db).await, 1); assert_eq!( - MealLedger::balance_of(&ali, &db).await.unwrap(), + meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000, "the charge must have committed with the claim, not after it" ); @@ -595,7 +598,7 @@ mod tests { // back — no second seat and, just as importantly, no second charge. assert!(matches!(place().await, Claimed::Duplicate)); assert_eq!(seats(&menu, &db).await, 1); - assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); + assert_eq!(meal_ledger::balance_of(&db, &ali).await.unwrap(), -1_000); } /// A free menu owes no refund, so the flip must carry no ledger line at all @@ -613,7 +616,7 @@ mod tests { .unwrap() .expect("a free seat is still a seat"); assert_eq!(seats(&menu, &db).await, 0); - let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) + let (lines, total) = meal_ledger::list_for_student(&db, &ali, None, 0) .await .unwrap(); assert!(lines.is_empty() && total == 0, "a free seat moves no money"); diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs new file mode 100644 index 0000000..dc0ea5e --- /dev/null +++ b/src/db/meal_ledger.rs @@ -0,0 +1,195 @@ +//! The `meal_ledger` table: the append-only money writes and reads. The +//! row/newtype shapes, the deterministic id minters and the sign +//! convention live in [`crate::domain::meal_ledger`]; the charge/reversal +//! and credit workflows that sequence these in [`crate::service::meal_ledger`]. + +use surrealdb::types::{AlreadyExistsError, SurrealValue}; + +use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE}; +use crate::database::{Database, lost_the_race}; +use crate::db::menu_dish; +use crate::db::page::PagedList; +use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind}; +use crate::domain::menu::MenuId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Did this `CREATE` fail *only* because the row is already there? Matched on +/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text +/// and never on "any database error", because swallowing a real fault in money +/// code would be far worse than the 500 it saves. +fn is_duplicate_record(error: &surrealdb::Error) -> bool { + matches!( + error.already_exists_details(), + Some(AlreadyExistsError::Record { .. }) + ) +} + +/// The only writer: one `CREATE`, no update path anywhere in this module. +/// +/// A line whose id already exists is left exactly as it is — the row wins, +/// the write is dropped. That is what makes a deterministic id (see +/// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same +/// append is a no-op, never a second line and never an edit of the first. +/// The point read is on the id itself, so unlike a scan it cannot miss a +/// row a concurrent writer just made — but it is only a fast path. The +/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves +/// the row untouched, so the writer that lost the race reads back the +/// winner's line instead of failing the request with a 500. +/// +/// A *write conflict* is the same race decided one layer down — two +/// appends of one id arriving together are no longer serialized by a +/// process-wide lock, so the store aborts one as retryable instead of +/// answering it "already exists". Both are read back the same way, and a +/// conflict that turns out to have written nothing is simply tried again; +/// no path here can write a second line, since the id is the key. +pub(crate) async fn append(db: &Database, row: MealLedger) -> Result { + if let Some(existing) = read(db, &row.id).await? { + return Ok(existing); + } + let id = row.id.clone(); + for _ in 0..CAS_UPDATE_RETRIES { + match db.create(id.record()).content(row.clone()).await { + Ok(Some(created)) => return Ok(created), + Ok(None) => break, + Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { + if let Some(existing) = read(db, &id).await? { + return Ok(existing); + } + } + Err(e) => return Err(e.into()), + } + } + Err(AppError::Internal("failed to write the ledger line".into())) +} + +pub async fn read(db: &Database, id: &MealLedgerId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// What a seat on `menu` costs *right now*: the sum of its dishes. `None` +/// when the menu is free (or empty) — a zero line is noise, not history. +/// +/// Called before the seat is taken so an unchargeable menu (one summing +/// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of +/// leaving a booked-but-unbilled row behind. +pub async fn price_snapshot( + db: &Database, + menu: &MenuId, +) -> Result, AppError> { + let total = menu_dish::list_for_menu(db, menu) + .await? + .iter() + .fold(0i64, |sum, dish| { + sum.saturating_add(dish.get_price_minor().as_minor()) + }); + if total == 0 { + return Ok(None); + } + Ok(Some(LedgerAmount::try_new(total)?)) +} + +/// A student's whole statement, newest first. +pub async fn list_for_student( + db: &Database, + student: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "meal_ledger WHERE student = $student", + "ORDER BY created_at DESC, id DESC", + ) + .bind("student", student.record()) + .run(limit, offset, db) + .await +} + +/// The derived balance: `credits + reversals - charges`, in minor units. +/// Negative means the student owes the school. Never stored anywhere. +/// +/// **The sum is taken per kind by the database** and only the three totals +/// come back, so a balance read costs the same whether the statement holds +/// four lines or forty thousand. It used to decode and fold every line, and +/// nothing bounds a statement's length but the cycle ceiling +/// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS)) +/// added alongside this: every book/cancel +/// pair appends two permanent rows, and each one was paid for again by +/// every later `GET /meals/balance/*`. +/// +/// **The signs stay on the kind**, applied by the very +/// [`MealLedgerKind::sign`] +/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN +/// -amount …` in SQL would have folded the whole balance in one statement +/// and forked the one rule that decides what money means into a second +/// language, where nothing would fail the day the two disagreed. Grouping +/// instead keeps the aggregate ignorant of signs: it counts kinds, and +/// Rust still says what a kind does. A stored running total was the third +/// option and is a counter that can drift — a bug class this repo closes, +/// not one it opens. +pub async fn balance_of(db: &Database, student: &UserId) -> Result { + let totals: Vec = db + .query(format!( + "SELECT kind, math::sum(amount_minor) AS total \ + FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" + )) + .bind(("student", student.record())) + .await? + .check()? + .take(0)?; + Ok(totals + .iter() + .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) +} + +/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands +/// it back — at most three rows, never the lines behind them. +#[derive(Debug, SurrealValue)] +struct KindTotal { + kind: MealLedgerKind, + total: i64, +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The balance aggregate **against a real server**, and `#[ignore]`d for + /// it: `init_mem`'s embedded engine is not the store this runs on, and an + /// aggregate is exactly where the two are known to differ — a `count()` + /// over an indexed field comes back `{count: N}` from the server and a + /// bare int from memory, and `student` here *is* indexed. This asserts the + /// `GROUP BY` really decodes into [`KindTotal`] and folds to the + /// documented figure, per kind, scoped to one student. + #[tokio::test] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn the_balance_aggregate_decodes_on_a_real_server() { + let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; + db.query( + "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ + amount_minor = 10000, recorded_by = user:adm, created_at = 1; + CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ + amount_minor = 4500, recorded_by = user:adm, created_at = 2; + CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ + amount_minor = 1500, recorded_by = user:adm, created_at = 3; + CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ + amount_minor = 4500, recorded_by = user:adm, created_at = 4; + CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ + amount_minor = 777, recorded_by = user:adm, created_at = 5;", + ) + .await + .unwrap() + .check() + .unwrap(); + let ali = UserId::from_key("ali"); + assert_eq!( + balance_of(&db, &ali).await.unwrap(), + 10_000 - 4_500 - 1_500 + 4_500 + ); + // Somebody with no lines at all: no groups come back, not an error. + assert_eq!( + balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), + 0 + ); + } +} diff --git a/src/db/menu.rs b/src/db/menu.rs new file mode 100644 index 0000000..b95956c --- /dev/null +++ b/src/db/menu.rs @@ -0,0 +1,608 @@ +//! The `menu` table: publishing (the slot reference claimed inside the +//! write's own transaction), row reads and listings, the compare-and-set +//! every cap PATCH writes through, the cascading delete, and +//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every +//! child write (a dish, an attendance mark) uses so nothing can outlive its +//! menu. The kitchen workflows — the dish cap under +//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in +//! [`crate::service::menu`]. + +use surrealdb::types::{SurrealValue, Value}; + +use crate::constant::{ + MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, + REF_COUNT_FIELD, +}; +use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Move the menu's revision **and** run `statement` — a write to something +/// hanging off a menu — in one transaction, handing back the row it returned. +/// +/// What a seat on that menu costs, or who is recorded against it, is about to +/// change, so any booking that priced itself against the old revision has to +/// re-read. The bump cannot be a query of its own: in the gap the menu row +/// carries the *new* revision with the *old* price, and a booking reading there +/// passes the very CAS that exists to refuse it — a seat billed a price the +/// menu had already left, or admitted past a capacity that had already shrunk. +/// +/// The bump is also what makes the menu's **existence** part of the write +/// ([`crate::db::menu_dish::create`] leans on +/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, +/// and a delete racing this one touches the very key this transaction writes, +/// so the two cannot both commit. Reading the menu instead — even as the write +/// statement's own target — does not survive that race: the read sees a row the +/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot +/// predating this insert, so both commit and the child outlives its menu +/// (measured 378 of 3600 raced rounds before this shape was shared). +/// +/// Deliberately on every such write, not only the ones that move +/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies +/// to every write cannot be forgotten by the next one added. +/// +/// Admissible for [`transaction_with_retry`] as long as `statement` is: an +/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never +/// answer "already exists", and neither can an `UPSERT` whose id is bijective +/// with every unique tuple its table indexes — a lost round wrote nothing, so +/// re-sending it is the recovery. +pub(crate) async fn bump_menu_and_write( + menu: &MenuId, + statement: &str, + mut bindings: Vec<(String, Value)>, + db: &Database, +) -> Result, AppError> { + bindings.push(("menu".into(), menu.record().into_value())); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; + LET $row = ({statement}); + RETURN $row; + COMMIT TRANSACTION;" + ), + &bindings, + &["no_menu"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_menu")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. + Ok(result.take::>(4)?.into_iter().next()) +} + +/// Publish a menu. Refused (409) when the day+slot already carries one. +/// +/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the +/// refusal is decided by the store rather than by a check a concurrent +/// publish can outrun: two publishes of the same meal write one id, and the loser's +/// "already exists" becomes the same 409. The pre-check stays for the +/// ordinary case — and for menus published before ids were derived, whose +/// ULID key no new publish can collide with. +pub async fn create( + db: &Database, + date: MenuDate, + slot: MenuSlot, + capacity: Option, + created_by: &UserId, +) -> Result { + let taken = AppError::Conflict("a menu is already published for that date and slot"); + if find(db, &date, &slot).await?.is_some() { + return Err(taken); + } + // The menu takes a reference on its slot, which is what stops the slot + // being dropped from the settings while this menu (whose slot is only + // snapshotted text) still points at it. Claimed *inside* the write's own + // transaction: a claim of its own could land and the row then fail to, + // leaving the slot counted by a menu that does not exist — a slot + // nobody can ever retire, and no crash window is small enough for that. + let counter = slot_ref(slot.as_str()); + let menu = Menu { + id: MenuId::for_slot(&date, &slot), + date, + slot, + capacity, + version: Some(0), + created_by: created_by.clone(), + created_at: Timestamp::now(), + }; + let id = menu.id.record(); + match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { + cap::ClaimedRef::Made(created) => Ok(created), + cap::ClaimedRef::Duplicate => Err(taken), + cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( + "the '{}' meal slot has been removed from the school's settings", + menu.slot.as_str() + ))), + } +} + +pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// The menu for one day and slot, if any — the uniqueness check. +pub async fn find( + db: &Database, + date: &MenuDate, + slot: &MenuSlot, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") + .bind(("date", date.as_str().to_string())) + .bind(("slot", slot.as_str().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; +/// either may be omitted. The comparison is lexical, which is chronological +/// for this format. +pub async fn list( + db: &Database, + from: Option<&MenuDate>, + to: Option<&MenuDate>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", + "ORDER BY date DESC, slot ASC, id DESC", + ) + .bind("from", from.map(|date| date.as_str().to_string())) + .bind("to", to.map(|date| date.as_str().to_string())) + .run(limit, offset, db) + .await +} + +/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, +/// because moving a published menu to another day is a different menu. +/// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. +/// +/// The revision moves **in the same statement** as the cap, indivisibly: a +/// booking claims its seat against the revision +/// it read the cap at, so a shrink that bumped in a query of its own left a +/// window where the row carried the *new* revision and the *old* cap — and +/// a booking arriving there passes a CAS meant to refuse it, over-admitting +/// by exactly the seats in flight. +pub async fn update( + db: &Database, + menu: Menu, + capacity: Option>, +) -> Result { + let Some(capacity) = capacity else { + // A PATCH carrying nothing writes nothing and bumps nothing: no + // booking's price or cap has moved, so none owes a re-read. + return read(db, &menu.id).await?.ok_or(AppError::NotFound); + }; + let sql = format!( + "UPDATE $id SET capacity = $capacity, \ + {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" + ); + // One counter write in flight at a time, like every other one. + let _guard = cap::counter_lock().await; + write_with_retry::( + db, + &sql, + &[ + ("id".into(), menu.id.record().into_value()), + ("capacity".into(), capacity.into_value()), + ], + ) + .await? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Delete the menu and the dishes on it — a dish has no meaning without +/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. +/// +/// Refused (409) while a seat is still held, and the *row itself* decides +/// that: the delete carries the seat counter in its `WHERE`, so a booking +/// landing at that instant either takes its seat before +/// the delete (which then finds a non-zero counter and refuses) or after it +/// (and finds no menu). A read-then-delete pair had a window where both +/// happened — a paid seat on a menu that no longer exists. +/// +/// The slot gets its reference back in that same transaction — a slot no +/// menu is published for any more may leave the settings again, and the +/// `FOR` runs only over a row the guard actually took. Released afterwards +/// in a query of its own, a crash between the two left the slot counted by +/// a menu that no longer exists: a slot nobody can retire. +/// +/// The marks go in that same `FOR`, for a sharper reason than tidiness: +/// [`MenuId::for_slot`] is deterministic, so republishing the same day and +/// slot mints the *same* record id. A mark left behind would come back as a +/// mark on the new menu — the kitchen reading "served" for a student who +/// never came — and until then the student's own report cites a menu that +/// is gone. Attendance carries no money and no counter, so it is safe to +/// drop; cancelled *bookings* deliberately stay, because their `attempt` +/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut +/// those and a re-book on a republished menu would reuse a charge id the +/// ledger already holds, and the append (idempotent by design) would bill +/// the seat nothing. +/// +/// The dishes ride in that `FOR` too, and for the same reason as the marks: +/// run after the transaction committed, a crash between the two orphaned +/// them on a record id republishing the day and slot mints again — a new +/// menu serving (and pricing) the old one's food. +pub async fn delete(db: &Database, menu: Menu) -> Result { + let sql = format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); + FOR $row IN ($gone ?? []) {{ + UPSERT $counter SET {REF_COUNT_FIELD} = \ + math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); + DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; + DELETE {MENU_DISH_TABLE} WHERE menu = $id; + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ); + // `slot` is a `READONLY` column, so this counter is the one the deleted + // row carries. Nothing here can answer "already exists" — the `UPSERT` + // is keyed by a slot name on a table with no `UNIQUE` index, so it + // resolves onto the row it names ([`transaction_with_retry`]). + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("id".into(), menu.id.record().into_value()), + ("counter".into(), slot_ref(menu.slot.as_str()).into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN, the LET and the FOR take a slot each. + let Some(deleted) = result.take::>(3)?.into_iter().next() else { + // Nothing back: either seats are held, or the menu is already gone. + return Err(match read(db, &menu.id).await? { + Some(_) => AppError::Conflict("the menu still has live bookings"), + None => AppError::NotFound, + }); + }; + Ok(deleted) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::db::meal_attendance; + use crate::db::menu_dish; + use crate::domain::meal_attendance::MealAttendanceStatus; + use crate::domain::menu_dish::{DishName, DishPrice, DishTags}; + use crate::domain::settings::MealSlotDef; + + async fn school() -> Database { + let db = init_mem().await.unwrap(); + db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + db + } + + fn lunch() -> MenuSlot { + MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() + } + + /// The reference count, re-read out of the store — never off a return + /// value, which the in-memory engine forges wins on. + async fn refs(db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE (count ?? 0) FROM $id") + .bind(("id", slot_ref("lunch"))) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } + + async fn publish(date: &str, db: &Database) -> Result { + create( + db, + MenuDate::try_new(date).unwrap(), + lunch(), + None, + &UserId::from_key("teacher"), + ) + .await + } + + /// Plant a menu row the pre-check will (or will not) find, without going + /// through the claim — a row published before the counter existed. + async fn plant(id: &MenuId, date: &str, db: &Database) { + db.query( + "CREATE $id SET date = $date, slot = 'lunch', \ + created_by = user:teacher, created_at = 1", + ) + .bind(("id", id.record())) + .bind(("date", date.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + + #[tokio::test] + async fn publishing_lands_the_menu_and_its_reference_together() { + let db = school().await; + let menu = publish("2026-08-02", &db).await.unwrap(); + assert!(read(&db, menu.get_id()).await.unwrap().is_some()); + assert_eq!(refs(&db).await, 1); + + // The day+slot pre-check answers the second publish — and a refusal + // may not count the slot, or the menu would outlive its own reference. + let again = publish("2026-08-02", &db) + .await + .expect_err("that day and slot are taken"); + assert!(matches!(again, AppError::Conflict(_)), "got {again:?}"); + assert_eq!(refs(&db).await, 1); + } + + #[tokio::test] + async fn a_retired_slot_refuses_and_writes_nothing() { + let db = school().await; + assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); + + let refused = publish("2026-08-02", &db) + .await + .expect_err("the slot left the settings"); + assert!( + matches!(refused, AppError::ConflictOwned(_)), + "got {refused:?}" + ); + assert_eq!(refs(&db).await, 0); + assert!( + find(&db, &MenuDate::try_new("2026-08-02").unwrap(), &lunch(),) + .await + .unwrap() + .is_none() + ); + } + + /// The race the fold exists for: a rival places the very row this publish + /// is placing, between the pre-check and the write. Only the claim's own + /// gate can answer it, and its answer must cost no reference. + #[tokio::test] + async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { + let db = school().await; + let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); + // Planted under another day, so `find` misses it exactly as it would + // in the instant before the rival's own row was visible. + plant(&id, "1999-01-01", &db).await; + + let taken = publish("2026-08-02", &db) + .await + .expect_err("the id is taken"); + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); + assert_eq!(refs(&db).await, 0); + } + + /// Menus published before ids were derived keep a ULID key a new publish + /// cannot collide with, so the pre-check is the only thing that can refuse. + #[tokio::test] + async fn a_legacy_ulid_menu_still_answers_taken() { + let db = school().await; + plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; + + let taken = publish("2026-08-02", &db) + .await + .expect_err("that day and slot are taken"); + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); + assert_eq!(refs(&db).await, 0); + } + + /// The cap and the revision are one write. Nothing single-process can + /// observe the torn state the two-query version left (a bumped revision + /// over a cap that had not moved yet), so what is pinned here is the pair: + /// the revision steps exactly once per cap move, and never for a PATCH that + /// carried no cap at all — a booking re-reads only when something it priced + /// itself against actually changed. + #[tokio::test] + async fn the_cap_and_the_revision_move_together_or_not_at_all() { + let db = school().await; + let menu = publish("2026-08-05", &db).await.unwrap(); + let id = menu.get_id().clone(); + assert_eq!(menu.get_version(), 0); + + let capped = update(&db, menu, Some(Some(5))).await.unwrap(); + assert_eq!(capped.get_capacity(), Some(5)); + assert_eq!(capped.get_version(), 1); + // Re-read out of the store, never off the return value. + let stored = read(&db, &id).await.unwrap().unwrap(); + assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1)); + + // An empty PATCH moves neither, and reads the row back unchanged. + let same = update(&db, stored, None).await.unwrap(); + assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1)); + + // Clearing the cap is a move like any other. + let uncapped = update(&db, same, Some(None)).await.unwrap(); + assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2)); + } + + #[tokio::test] + async fn deleting_hands_the_reference_back_in_the_same_step() { + let db = school().await; + let monday = publish("2026-08-03", &db).await.unwrap(); + publish("2026-08-04", &db).await.unwrap(); + assert_eq!(refs(&db).await, 2); + + let id = monday.get_id().clone(); + let ghost = monday.clone(); + delete(&db, monday).await.unwrap(); + assert!(read(&db, &id).await.unwrap().is_none()); + assert_eq!(refs(&db).await, 1, "the row and its reference go together"); + + // Deleting what is already gone hands nothing back: a second release + // would leave a slot one menu still uses free to be retired. + let gone = delete(&db, ghost).await.expect_err("already deleted"); + assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); + assert_eq!(refs(&db).await, 1); + assert!( + !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), + "a slot a menu is still published for may not be retired" + ); + + // …and once the last menu goes, it may. + let last = find(&db, &MenuDate::try_new("2026-08-04").unwrap(), &lunch()) + .await + .unwrap() + .unwrap(); + delete(&db, last).await.unwrap(); + assert_eq!(refs(&db).await, 0); + } + + /// Nothing hanging off a menu may survive the delete that swept it — not a + /// dish, and not an attendance mark. Menu ids are deterministic on + /// (date, slot), so a survivor is not litter: republishing that meal mints + /// the *same* id and the orphan comes back attached to the new menu — the + /// kitchen reading "served" for a student who never came, or pricing the + /// old menu's food. + /// + /// The window is between [`delete`]'s `DELETE` and its cascade: a + /// child write committing in there is a phantom insert into a range the + /// delete already swept on an older snapshot, so the sweep removes nothing + /// and *both* commit. It is closed by making every child write **write** the + /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two + /// transactions then touch one key and the store refuses to commit both. + /// + /// The window is opened by the database itself rather than by a lucky + /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own + /// transaction, the instant the row goes, so the `SLEEP` lands exactly + /// between the delete and its sweep every single time. Nothing in `src/` + /// knows about it; the seam is the schema. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, which would fail this + /// test on correct code (see [`crate::database::init_test_server`]). + /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read* + /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) + /// turns this red at **both** of its two rounds — the mark commits, the + /// sweep misses it, and the row is left pointing at a menu that is gone. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_child_written_inside_a_delete_never_outlives_the_menu() { + use crate::domain::menu_dish::DishDescription; + + let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; + db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + // Hold the delete open for a full second after the row is gone, while + // its cascade still has to run. + db.query( + "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut dishes, mut marks, mut swept) = (0, 0, 0); + for round in 0..4 { + let menu = publish(&format!("2026-09-{:02}", round + 1), &db) + .await + .unwrap(); + let id = menu.get_id().clone(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, menu).await }) + }; + // The child starts inside the held window — the delete's row is + // gone but uncommitted, which is exactly what a menu read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // One child per round, never both: whichever wrote first forces the + // delete to re-send, and its second pass sweeps the other's row — + // which would mask exactly the defect this test exists to catch. + let child = { + let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); + tokio::spawn(async move { + if dish { + menu_dish::create( + &db, + &id, + DishName::try_new("Pilav").unwrap(), + None::, + DishPrice::try_new(1).unwrap(), + DishTags::try_new(&[], &[]).unwrap(), + ) + .await + .map(|_| ()) + } else { + meal_attendance::mark( + &db, + &id, + &UserId::from_key("teacher"), + MealAttendanceStatus::try_new("served").unwrap(), + &UserId::from_key("teacher"), + ) + .await + .map(|_| ()) + } + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the child, or a 409/NotFound for the delete, is a + // correct answer — the only defect is stored state. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced child write must be answered, not 500: {child:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + dishes += menu_dish::list_for_menu(&db, &id).await.unwrap().len(); + marks += meal_attendance::list_for_menu(&db, &id, None, 0) + .await + .unwrap() + .1; + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the menu is still there"); + } + } + eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); + assert!( + swept > 0, + "no round ever deleted the menu, so the window was never reached" + ); + assert_eq!(dishes, 0, "a dish outlived its menu"); + assert_eq!(marks, 0, "a mark outlived its menu"); + } +} diff --git a/src/db/menu_dish.rs b/src/db/menu_dish.rs new file mode 100644 index 0000000..8f988e3 --- /dev/null +++ b/src/db/menu_dish.rs @@ -0,0 +1,175 @@ +//! The `menu_dish` table: the dishes on a menu — the insert and the field +//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the +//! reads and listings, and the delete. The dish-cap gate and the +//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in +//! [`crate::service::menu`]. + +use surrealdb::types::{SurrealValue, Value}; + +use crate::constant::MENU_VERSION_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::db::menu::bump_menu_and_write; +use crate::domain::menu::MenuId; +use crate::domain::menu_dish::{ + DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, +}; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; + +/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. +pub async fn create( + db: &Database, + menu: &MenuId, + name: DishName, + description: Option, + price_minor: DishPrice, + tags: DishTags, +) -> Result { + let dish = MenuDish { + id: MenuDishId::generate(), + menu: menu.clone(), + name, + description, + price_minor, + tags, + created_at: Timestamp::now(), + }; + // The revision bump and the insert are one transaction, and the bump is + // what makes the menu's existence part of it: the `UPDATE` matches + // nothing once the menu row is deleted, and a delete racing this one + // touches the very key this transaction writes, so the two cannot both + // commit. Without that, a dish landing just after `DELETE /menus/{id}` + // removed the row but before its cascade ran outlived its menu. + // Every other dish write bumps the same version key, so a lost round is + // ordinary here; it is re-sent rather than reported. Re-sending is sound + // even with the `CREATE` in the batch — the abort wrote nothing, the id + // is a ULID freshly generated above and never seen by a rival, and + // `menu_dish` carries no UNIQUE index — so the retry cannot answer + // "already exists" (see [`transaction_with_retry`]). + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; + CREATE $id CONTENT $dish; + COMMIT TRANSACTION;" + ), + &[ + ("menu".into(), menu.record().into_value()), + ("id".into(), dish.id.record().into_value()), + ("dish".into(), dish.into_value()), + ], + &["no_menu"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_menu")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. + result + .take::>(3)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to add the dish".into())) +} + +pub async fn read(db: &Database, id: &MenuDishId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every dish on one menu, in the order they were added. +pub async fn list_for_menu(db: &Database, menu: &MenuId) -> Result, AppError> { + list_for_menus(db, std::slice::from_ref(menu)).await +} + +/// Dishes for a whole page of menus in one round trip — the alternative is +/// a query per menu, which is the N+1 the pagination slice exists to avoid. +pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result, AppError> { + if menus.is_empty() { + return Ok(Vec::new()); + } + let mut result = db + .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") + .bind(( + "menus", + menus.iter().map(MenuId::record).collect::>(), + )) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. +pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result { + Ok(list_for_menu(db, menu).await?.len()) +} + +/// Write only the fields the PATCH carried. `description` is nullable, so +/// it takes the three-way shape: absent = keep, `Some(None)` = clear. +/// +/// The `SET` is built here rather than by +/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the +/// revision bump lands on *another* row and has to share this write's +/// transaction; the field-by-field scoping — an omitted field is never +/// written, so a concurrent PATCH of another one is not reverted — is the +/// same rule, spelled out. +pub async fn update( + db: &Database, + dish: MenuDish, + name: Option, + description: Option>, + price_minor: Option, + tags: Option, +) -> Result { + let mut sets: Vec<&str> = Vec::new(); + let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())]; + let mut set = |field: &'static str, value: Option| { + if let Some(value) = value { + sets.push(field); + bindings.push((field.into(), value)); + } + }; + set("name", name.map(SurrealValue::into_value)); + set("description", description.map(SurrealValue::into_value)); + set("price_minor", price_minor.map(SurrealValue::into_value)); + set("tags", tags.map(SurrealValue::into_value)); + // A PATCH that carried nothing writes nothing and reads the row back, + // exactly as `FieldUpdate` answers one — but it still moves the + // revision, because "every dish write bumps" is the rule a caller can + // rely on without knowing which fields were on the wire. + let statement = if sets.is_empty() { + "SELECT * FROM $id".to_string() + } else { + format!( + "UPDATE $id SET {} RETURN AFTER", + sets.iter() + .map(|field| format!("{field} = ${field}")) + .collect::>() + .join(", ") + ) + }; + bump_menu_and_write(&dish.menu, &statement, bindings, db) + .await? + .ok_or(AppError::NotFound) +} + +pub async fn delete(db: &Database, dish: MenuDish) -> Result { + bump_menu_and_write( + &dish.menu, + "DELETE $id RETURN BEFORE", + vec![("id".into(), dish.id.record().into_value())], + db, + ) + .await? + .ok_or(AppError::NotFound) +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..b3da377 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,17 +1,21 @@ //! The only layer that executes queries. - pub mod appointment; pub mod appointment_slot; pub mod cap; pub mod class_blueprint; pub mod course; pub mod course_session; +pub mod dietary_profile; pub mod enrollment; pub mod exam; pub mod exam_attempt; pub mod exam_question; pub mod field_update; +pub mod meal_attendance; pub mod meal_booking; +pub mod meal_ledger; +pub mod menu; +pub mod menu_dish; pub mod note; pub mod page; pub mod payment_ledger; diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs index 87051b9..be77d4a 100644 --- a/src/domain/dietary_profile.rs +++ b/src/domain/dietary_profile.rs @@ -8,16 +8,17 @@ //! student" answerable as a set intersection, without the backend knowing any //! nutrition. //! +//! The queries live in [`crate::db::dietary_profile`]; the web layer reads +//! through [`crate::service::dietary_profile`]. +//! //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; -use crate::database::Database; -use crate::db::field_update::FieldUpdate; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_optional; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -46,7 +47,7 @@ impl DietaryProfileId { /// list — the same vocabulary a dish is tagged from, deduplicated and in the /// order given. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct DietaryTags(Vec); +pub struct DietaryTags(pub(crate) Vec); impl DietaryTags { pub fn try_new(values: &[String], allowed: &[String]) -> Result { @@ -97,12 +98,12 @@ impl DietaryNote { #[derive(Debug, Clone, SurrealValue)] pub struct DietaryProfile { - id: DietaryProfileId, - student: UserId, - tags: DietaryTags, - note: Option, - updated_by: UserId, - updated_at: Timestamp, + pub(crate) id: DietaryProfileId, + pub(crate) student: UserId, + pub(crate) tags: DietaryTags, + pub(crate) note: Option, + pub(crate) updated_by: UserId, + pub(crate) updated_at: Timestamp, } impl DietaryProfile { @@ -125,67 +126,6 @@ impl DietaryProfile { pub fn get_updated_at(&self) -> Timestamp { self.updated_at } - - /// One student's profile, or `None` while the school never recorded one. - /// A single `SELECT` by record id — this is what a menu read joins on. - pub async fn read(student: &UserId, db: &Database) -> Result, AppError> { - Ok(db.select(DietaryProfileId::of(student).record()).await?) - } - - /// The tags a menu read matches its dishes against: the caller's, or an - /// empty list when they have no profile (every manager, every teacher). - pub async fn tags_of(student: &UserId, db: &Database) -> Result, AppError> { - Ok(Self::read(student, db) - .await? - .map(|profile| profile.tags.as_slice().to_vec()) - .unwrap_or_default()) - } - - /// Write the fields the PATCH carried. Creates the row on first write; - /// afterwards only the named fields move, because `student` is `READONLY` - /// and a whole-row save would also revert a concurrent edit of the other - /// field (see [`FieldUpdate`]). - pub async fn save( - student: &UserId, - tags: Option, - note: Option>, - by: &UserId, - db: &Database, - ) -> Result { - if Self::read(student, db).await?.is_none() { - let profile = Self { - id: DietaryProfileId::of(student), - student: student.clone(), - tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), - note: note.clone().flatten(), - updated_by: by.clone(), - updated_at: Timestamp::now(), - }; - match db.create(profile.id.record()).content(profile).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => { - return Err(AppError::Internal("failed to save the profile".into())); - } - // A rival first `PATCH` created the row in the round trip since - // the read above (the `dietary_profile_student` UNIQUE index - // catches the same collision), and `CREATE` leaves that row - // untouched — so this call is a plain field write after all, - // exactly as it would have been a moment later. Propagated, it - // was a 500 on a legitimate request. Same shape as - // [`MealLedger::append`](crate::domain::meal_ledger), which - // reads the winner back rather than failing. - Err(err) if err.is_already_exists() => {} - Err(err) => return Err(err.into()), - } - } - FieldUpdate::new(DietaryProfileId::of(student).record()) - .set("tags", tags) - .set("note", note) - .set("updated_by", Some(by.clone())) - .set("updated_at", Some(Timestamp::now())) - .run::(db) - .await - } } /// Which of a dish's tags the reader's own profile flags. Empty when there is diff --git a/src/domain/meal_attendance.rs b/src/domain/meal_attendance.rs index 4855e60..5fb267b 100644 --- a/src/domain/meal_attendance.rs +++ b/src/domain/meal_attendance.rs @@ -14,16 +14,17 @@ //! The statuses are the fixed [`MEAL_ATTENDANCE_STATUSES`] pair, deliberately //! *not* the school's editable `attendance_statuses`: a canteen line has no //! "late" or "excused". +//! +//! The queries live in [`crate::db::meal_attendance`]; the web layer reads +//! through [`crate::service::meal_attendance`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; -use crate::database::Database; -use crate::domain::menu::{MenuDate, MenuId, bump_menu_and_write}; -use crate::db::page::PagedList; +use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct MealAttendanceId(RecordId); @@ -74,12 +75,12 @@ impl MealAttendanceStatus { #[derive(Debug, Clone, SurrealValue)] pub struct MealAttendance { - id: MealAttendanceId, - menu: MenuId, - student: UserId, - status: MealAttendanceStatus, - marked_by: UserId, - marked_at: Timestamp, + pub(crate) id: MealAttendanceId, + pub(crate) menu: MenuId, + pub(crate) student: UserId, + pub(crate) status: MealAttendanceStatus, + pub(crate) marked_by: UserId, + pub(crate) marked_at: Timestamp, } impl MealAttendance { @@ -106,102 +107,6 @@ impl MealAttendance { pub fn get_marked_at(&self) -> Timestamp { self.marked_at } - - /// Record (or overwrite) whether `student` ate off `menu`. One row per - /// pair by construction, so a correction is the same UPSERT flipping the - /// status. No ledger line, ever — see the module header. - /// - /// `NotFound` = the menu is gone, and the mark was *not* written. The mark - /// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to - /// the menu row rather than a read the write then trusts: a delete racing - /// this one touches the very key this transaction bumps, and the store - /// refuses to commit both. Guarding by reading the menu — even as the - /// `UPSERT`'s own target — did not survive that race: the read saw a row - /// [`Menu::delete`](crate::domain::menu::Menu::delete) had deleted but not - /// yet committed, its sweep ran on a snapshot predating this insert, and the - /// mark outlived its menu with neither caller told anything (measured 378 of - /// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, - /// republishing that day and slot then resurrected it as a mark on the new - /// menu. - /// - /// The bump costs a booking in flight one re-read (its seat claim asserts - /// the revision it priced against) — the same tax every dish write already - /// levies, and it lands after the cutoff on a meal being served, where - /// bookings are rare. - pub async fn mark( - menu: &MenuId, - student: &UserId, - status: MealAttendanceStatus, - marked_by: &UserId, - db: &Database, - ) -> Result { - let row = MealAttendance { - id: MealAttendanceId::composite(menu, student), - menu: menu.clone(), - student: student.clone(), - status, - marked_by: marked_by.clone(), - marked_at: Timestamp::now(), - }; - // Admissible for the retry loop inside: the id is bijective with the - // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` - // resolves onto the row that index already points at instead of - // colliding with it — it can never answer "already exists", and a - // re-sent round writes the identical row. - bump_menu_and_write( - menu, - "UPSERT $id CONTENT $row RETURN AFTER", - vec![ - ("id".into(), row.id.record().into_value()), - ("row".into(), row.into_value()), - ], - db, - ) - .await? - .ok_or_else(|| AppError::Internal("failed to record the mark".into())) - } - - /// The kitchen's list for one menu. - pub async fn list_for_menu( - menu: &MenuId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "meal_attendance WHERE menu = $menu", - "ORDER BY marked_at DESC, id DESC", - ) - .bind("menu", menu.record()) - .run(limit, offset, db) - .await - } - - /// One student's marks, newest first. `from`/`to` are inclusive - /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, - /// which is chronological for that format (see [`MenuDate`]), and the link - /// is followed rather than denormalized so a row can never disagree with - /// the menu it belongs to. - pub async fn list_for_student( - student: &UserId, - from: Option<&MenuDate>, - to: Option<&MenuDate>, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "meal_attendance WHERE student = $usr \ - AND ($from = NONE OR menu.date >= $from) \ - AND ($to = NONE OR menu.date <= $to)", - "ORDER BY marked_at DESC, id DESC", - ) - .bind("usr", student.record()) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) - .run(limit, offset, db) - .await - } } #[cfg(test)] diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index cbc56d6..bde0eeb 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -49,27 +49,25 @@ //! here: the seat was reserved and the food was cooked. //! //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. +//! +//! The writes and the SUM/balance reads live in [`crate::db::meal_ledger`]; +//! the charge/reversal and credit workflows in +//! [`crate::service::meal_ledger`]. use std::sync::LazyLock; -use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Generator; use crate::constant::{ - CAS_UPDATE_RETRIES, MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, - MEAL_LEDGER_TABLE, + MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, }; -use crate::database::{Database, lost_the_race}; -use crate::domain::meal_booking::{MealBooking, MealBookingId}; -use crate::domain::menu::MenuId; -use crate::domain::menu_dish::MenuDish; -use crate::db::page::PagedList; // The client-chosen idempotence key both ledgers take — one grammar, one // validator, one type, rather than a second newtype that could drift from it. use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_optional; /// Mints ledger ids in write order — `Ulid::new()`'s random low bits sort @@ -95,13 +93,18 @@ impl MealLedgerId { } /// The one line a booking attempt may ever write of this `kind` — a - /// deterministic id, exactly like [`MealBookingId::composite`]. Two racing + /// deterministic id, exactly like [`MealBookingId::composite`](crate::domain::meal_booking::MealBookingId::composite). + /// Two racing /// `POST`s of one seat derive the *same* id and so cannot become two /// charges: idempotence rests on identity, never on a scan that a /// concurrent writer can slip past. The `attempt` counter is what keeps a /// re-book after a cancel a genuinely fresh charge. Booking keys are /// `_`, so the `c`/`r` marker keeps the two kinds apart. - pub fn for_attempt(booking: &MealBookingId, attempt: i64, kind: MealLedgerKind) -> Self { + pub fn for_attempt( + booking: &crate::domain::meal_booking::MealBookingId, + attempt: i64, + kind: MealLedgerKind, + ) -> Self { let marker = match kind { MealLedgerKind::Charge => 'c', MealLedgerKind::Reversal => 'r', @@ -143,17 +146,6 @@ impl MealLedgerId { } } -/// Did this `CREATE` fail *only* because the row is already there? Matched on -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text -/// and never on "any database error", because swallowing a real fault in money -/// code would be far worse than the 500 it saves. -fn is_duplicate_record(error: &surrealdb::Error) -> bool { - matches!( - error.already_exists_details(), - Some(AlreadyExistsError::Record { .. }) - ) -} - /// The bare key of a record id — how every id leaves this API. fn key_of(record: &RecordId) -> &str { match &record.key { @@ -184,7 +176,7 @@ impl MealLedgerKind { /// How the line folds into the balance: a charge is the only thing that /// takes money away. This is the *single* place the sign convention lives. - fn sign(self) -> i64 { + pub(crate) fn sign(self) -> i64 { match self { MealLedgerKind::Charge => -1, MealLedgerKind::Credit | MealLedgerKind::Reversal => 1, @@ -249,17 +241,17 @@ impl LedgerNote { #[derive(Debug, Clone, SurrealValue)] pub struct MealLedger { - id: MealLedgerId, - student: UserId, - kind: MealLedgerKind, - amount_minor: LedgerAmount, + pub(crate) id: MealLedgerId, + pub(crate) student: UserId, + pub(crate) kind: MealLedgerKind, + pub(crate) amount_minor: LedgerAmount, /// What caused the line: a charge points at its `meal_booking`, a reversal /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. - source: Option, - method: Option, - note: Option, - recorded_by: UserId, - created_at: Timestamp, + pub(crate) source: Option, + pub(crate) method: Option, + pub(crate) note: Option, + pub(crate) recorded_by: UserId, + pub(crate) created_at: Timestamp, } impl MealLedger { @@ -300,95 +292,6 @@ impl MealLedger { self.created_at } - /// The only writer: one `CREATE`, no update path anywhere in this module. - /// - /// A line whose id already exists is left exactly as it is — the row wins, - /// the write is dropped. That is what makes a deterministic id (see - /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same - /// append is a no-op, never a second line and never an edit of the first. - /// The point read is on the id itself, so unlike a scan it cannot miss a - /// row a concurrent writer just made — but it is only a fast path. The - /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves - /// the row untouched, so the writer that lost the race reads back the - /// winner's line instead of failing the request with a 500. - /// - /// A *write conflict* is the same race decided one layer down — two - /// appends of one id arriving together are no longer serialized by a - /// process-wide lock, so the store aborts one as retryable instead of - /// answering it "already exists". Both are read back the same way, and a - /// conflict that turns out to have written nothing is simply tried again; - /// no path here can write a second line, since the id is the key. - async fn append(row: MealLedger, db: &Database) -> Result { - if let Some(existing) = Self::read(&row.id, db).await? { - return Ok(existing); - } - let id = row.id.clone(); - for _ in 0..CAS_UPDATE_RETRIES { - match db.create(id.record()).content(row.clone()).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => break, - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { - if let Some(existing) = Self::read(&id, db).await? { - return Ok(existing); - } - } - Err(e) => return Err(e.into()), - } - } - Err(AppError::Internal("failed to write the ledger line".into())) - } - - pub async fn read(id: &MealLedgerId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// What a seat on `menu` costs *right now*: the sum of its dishes. `None` - /// when the menu is free (or empty) — a zero line is noise, not history. - /// - /// Called before the seat is taken so an unchargeable menu (one summing - /// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of - /// leaving a booked-but-unbilled row behind. - pub async fn price_snapshot( - menu: &MenuId, - db: &Database, - ) -> Result, AppError> { - let total = MenuDish::list_for_menu(menu, db) - .await? - .iter() - .fold(0i64, |sum, dish| { - sum.saturating_add(dish.get_price_minor().as_minor()) - }); - if total == 0 { - return Ok(None); - } - Ok(Some(LedgerAmount::try_new(total)?)) - } - - /// Bill `booking`'s current attempt at the price frozen onto it when that - /// attempt took the seat. - /// - /// The price comes off the *booking row*, never off the menu as it stands - /// now: a seat taken while the menu was free carries `None` forever, so - /// "was free" is a recorded fact and a later dish never bills a seat - /// retroactively. Called from - /// [`book`](crate::service::meal_booking::book) alone, right after the seat - /// was claimed, so the seat and its money move together. - /// - /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate - /// `POST` writes nothing, and an attempt whose charge failed the first time - /// self-heals on the next `POST` of the same seat. - pub async fn charge_booking( - booking: &MealBooking, - recorded_by: &UserId, - db: &Database, - ) -> Result<(), AppError> { - let Some(line) = Self::charge_for(booking, recorded_by) else { - return Ok(()); - }; - Self::append(line, db).await?; - Ok(()) - } - /// The charge `booking`'s current attempt owes — the line /// [`claim_and_place`](crate::db::meal_booking::claim_and_place) appends inside the very transaction that /// takes the seat. `None` when the menu was free, which owes no line. @@ -397,7 +300,10 @@ impl MealLedger { /// the caller that writes in one transaction has to make it there. Note the /// attempt has to be settled *before* the SQL runs, which is why the claim /// mints the number itself rather than letting the revival increment it. - pub(crate) fn charge_for(booking: &MealBooking, recorded_by: &UserId) -> Option { + pub(crate) fn charge_for( + booking: &crate::domain::meal_booking::MealBooking, + recorded_by: &UserId, + ) -> Option { let amount = booking.get_price_minor()?; Some(MealLedger { id: MealLedgerId::for_attempt( @@ -416,34 +322,6 @@ impl MealLedger { }) } - /// Give the money back for a cancelled `booking`: a new `reversal` line for - /// the charge's exact amount, pointing at it. The charge is never touched. - /// A booking that was never billed (a free menu) reverses nothing, and - /// neither does one whose charge never landed — the reversal is keyed to - /// the very charge it undoes, so it can only exist alongside it. - /// - /// Keyed by `(booking, attempt)` like the charge, so a retried cancel - /// refunds once. The line normally lands *inside* the flip's own - /// transaction - /// ([`release_seat`](crate::db::meal_booking::release_seat)); this path is what heals a - /// seat flipped before that was true, and it is why - /// [`cancel`](crate::service::meal_booking::cancel) replays it on an already-cancelled row instead - /// of refusing it. Nothing else on the API can append the missing line. - pub async fn reverse_booking( - booking: &MealBooking, - recorded_by: &UserId, - db: &Database, - ) -> Result<(), AppError> { - let Some((charge, line)) = Self::reversal_for(booking, recorded_by) else { - return Ok(()); - }; - if Self::read(&charge, db).await?.is_none() { - return Ok(()); - } - Self::append(line, db).await?; - Ok(()) - } - /// The refund `booking`'s current attempt owes, as `(the charge it undoes, /// the reversal line)` — the two ids /// [`release_seat`](crate::db::meal_booking::release_seat) needs to @@ -454,7 +332,7 @@ impl MealLedger { /// read, and the caller that writes in one transaction has to make it there /// rather than a round trip earlier. pub(crate) fn reversal_for( - booking: &MealBooking, + booking: &crate::domain::meal_booking::MealBooking, recorded_by: &UserId, ) -> Option<(MealLedgerId, MealLedger)> { let amount = booking.get_price_minor()?; @@ -480,117 +358,6 @@ impl MealLedger { }; Some((charge, line)) } - - /// Money in: a payment received, or an opening balance. - /// - /// With a `request_key` the line is keyed by it (see - /// [`MealLedgerId::for_request`]) and the call is **retry-safe**: a client - /// resending the identical body after a timeout gets back the line the - /// first attempt wrote, not a second credit — nothing on this API can edit - /// or delete one, so a doubled credit is corrected only by a compensating - /// line. Without one the id is a fresh ulid and two identical calls are two - /// credits, which is what a desk taking the same amount twice really means. - pub async fn credit( - student: &UserId, - amount_minor: LedgerAmount, - method: Option, - note: Option, - request_key: Option<&PaymentRequestKey>, - recorded_by: &UserId, - db: &Database, - ) -> Result { - let line = Self::append( - MealLedger { - id: match request_key { - Some(key) => MealLedgerId::for_request(student, key), - None => MealLedgerId::generate(), - }, - student: student.clone(), - kind: MealLedgerKind::Credit, - amount_minor, - source: None, - method, - note, - recorded_by: recorded_by.clone(), - created_at: Timestamp::now(), - }, - db, - ) - .await?; - // A replay is answered from the stored line — but only if it is the - // same money. The same key for a different amount is a client bug, and - // handing back the old line would hide it behind a `201`. Checked on - // what `append` gave back rather than on a read before it: two retries - // arriving together both find no row, and only the id decides which - // one's amount is stored, so a check *before* the write would tell the - // loser its own amount landed. - if request_key.is_some() && line.amount_minor != amount_minor { - return Err(AppError::Conflict( - "this request_key was already used for a different amount", - )); - } - Ok(line) - } - - /// A student's whole statement, newest first. - pub async fn list_for_student( - student: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "meal_ledger WHERE student = $student", - "ORDER BY created_at DESC, id DESC", - ) - .bind("student", student.record()) - .run(limit, offset, db) - .await - } - - /// The derived balance: `credits + reversals - charges`, in minor units. - /// Negative means the student owes the school. Never stored anywhere. - /// - /// **The sum is taken per kind by the database** and only the three totals - /// come back, so a balance read costs the same whether the statement holds - /// four lines or forty thousand. It used to decode and fold every line, and - /// nothing bounds a statement's length but the cycle ceiling - /// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS)) - /// added alongside this: every book/cancel - /// pair appends two permanent rows, and each one was paid for again by - /// every later `GET /meals/balance/*`. - /// - /// **The signs stay here**, applied by the very [`MealLedgerKind::sign`] - /// the documented formula is spelled in. Summing `IF kind = 'charge' THEN - /// -amount …` in SQL would have folded the whole balance in one statement - /// and forked the one rule that decides what money means into a second - /// language, where nothing would fail the day the two disagreed. Grouping - /// instead keeps the aggregate ignorant of signs: it counts kinds, and - /// Rust still says what a kind does. A stored running total was the third - /// option and is a counter that can drift — a bug class this repo closes, - /// not one it opens. - pub async fn balance_of(student: &UserId, db: &Database) -> Result { - let totals: Vec = db - .query(format!( - "SELECT kind, math::sum(amount_minor) AS total \ - FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" - )) - .bind(("student", student.record())) - .await? - .check()? - .take(0)?; - Ok(totals - .iter() - .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) - } -} - -/// One kind's whole sum, as the `GROUP BY` in [`MealLedger::balance_of`] hands -/// it back — at most three rows, never the lines behind them. -#[derive(Debug, SurrealValue)] -struct KindTotal { - kind: MealLedgerKind, - total: i64, } #[cfg(test)] @@ -634,47 +401,6 @@ mod tests { assert_eq!(balance, 10_000); } - /// The balance aggregate **against a real server**, and `#[ignore]`d for - /// it: `init_mem`'s embedded engine is not the store this runs on, and an - /// aggregate is exactly where the two are known to differ — a `count()` - /// over an indexed field comes back `{count: N}` from the server and a - /// bare int from memory, and `student` here *is* indexed. This asserts the - /// `GROUP BY` really decodes into [`KindTotal`] and folds to the - /// documented figure, per kind, scoped to one student. - #[tokio::test] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn the_balance_aggregate_decodes_on_a_real_server() { - let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; - db.query( - "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ - amount_minor = 10000, recorded_by = user:adm, created_at = 1; - CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ - amount_minor = 4500, recorded_by = user:adm, created_at = 2; - CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ - amount_minor = 1500, recorded_by = user:adm, created_at = 3; - CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ - amount_minor = 4500, recorded_by = user:adm, created_at = 4; - CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ - amount_minor = 777, recorded_by = user:adm, created_at = 5;", - ) - .await - .unwrap() - .check() - .unwrap(); - let ali = UserId::from_key("ali"); - assert_eq!( - MealLedger::balance_of(&ali, &db).await.unwrap(), - 10_000 - 4_500 - 1_500 + 4_500 - ); - // Somebody with no lines at all: no groups come back, not an error. - assert_eq!( - MealLedger::balance_of(&UserId::from_key("nobody"), &db) - .await - .unwrap(), - 0 - ); - } - #[test] fn an_amount_is_positive_and_capped() { assert!(LedgerAmount::try_new(0).is_err()); diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 2412872..48419ab 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -1,6 +1,6 @@ //! A published menu: what the kitchen serves on one calendar day in one meal //! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)), -//! and bookings will hang off its `capacity`. +//! and bookings hang off its `capacity`. //! //! Two things are deliberate: //! @@ -9,43 +9,17 @@ //! day is only one school's day. //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must //! never rewrite a menu already published under it. +//! +//! The queries live in [`crate::db::menu`]; the kitchen workflows (and the +//! dish-cap lock) in [`crate::service::menu`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; -use tokio::sync::Mutex; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - MAX_MENU_CAPACITY, MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_TABLE, - MENU_VERSION_FIELD, REF_COUNT_FIELD, SLOT_REF_TABLE, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE, SLOT_REF_TABLE}; use crate::domain::settings::MealSlotDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; - -/// Serializes what is left that counts rows against one menu: the dish cap -/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not -/// conflict-check). Publishing no longer needs it — the day+slot *is* the -/// record id — and neither does a booking, a menu delete, or the settings -/// slot-removal guard: those went to conditional single-record writes -/// ([`crate::db::cap`]), which the store decides as this lock cannot. -// -// corner-cut: the dish cap therefore rests on this lock alone — a dish write -// added without taking it reopens the count-then-write hole silently. Closing -// it properly is another `cap` counter (`dish_count` on the menu row) plus its -// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was -// not worth the column here. -/// -/// **A leaf**: every dish write held under it moves the menu's revision inside -/// its *own* transaction ([`bump_menu_and_write`]), -/// so no path under this lock reaches `cap`'s counter lock any more — it did -/// while the bump was a `cap` call of its own. Should one ever need both, the -/// order is `MENU_LOCK` → `CLAIM_LOCK` and nothing may take this lock while -/// holding a counter lock: that is the invariant a new caller must keep, and it -/// is what would keep the pair deadlock-free. -pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); +use crate::error::ValidationError; /// The reference counter for one meal slot — how many menus are published under /// that name, and whether the school has retired it (see @@ -57,72 +31,6 @@ pub(crate) fn slot_ref(slot: &str) -> RecordId { RecordId::new(SLOT_REF_TABLE, slot) } -/// Move the menu's revision **and** run `statement` — a write to something -/// hanging off a menu — in one transaction, handing back the row it returned. -/// -/// What a seat on that menu costs, or who is recorded against it, is about to -/// change, so any booking that priced itself against the old revision has to -/// re-read. The bump cannot be a query of its own: in the gap the menu row -/// carries the *new* revision with the *old* price, and a booking reading there -/// passes the very CAS that exists to refuse it — a seat billed a price the -/// menu had already left, or admitted past a capacity that had already shrunk. -/// -/// The bump is also what makes the menu's **existence** part of the write -/// ([`MenuDish::create`](crate::domain::menu_dish::MenuDish::create) leans on -/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, -/// and a delete racing this one touches the very key this transaction writes, -/// so the two cannot both commit. Reading the menu instead — even as the write -/// statement's own target — does not survive that race: the read sees a row the -/// delete has not committed yet, and [`Menu::delete`]'s sweep ran on a snapshot -/// predating this insert, so both commit and the child outlives its menu -/// (measured 378 of 3600 raced rounds before this shape was shared). -/// -/// Deliberately on every such write, not only the ones that move -/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies -/// to every write cannot be forgotten by the next one added. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: an -/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never -/// answer "already exists", and neither can an `UPSERT` whose id is bijective -/// with every unique tuple its table indexes — a lost round wrote nothing, so -/// re-sending it is the recovery. -pub(crate) async fn bump_menu_and_write( - menu: &MenuId, - statement: &str, - mut bindings: Vec<(String, Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("menu".into(), menu.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_menu"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. - Ok(result.take::>(4)?.into_iter().next()) -} - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct MenuId(RecordId); @@ -276,18 +184,19 @@ pub fn validate_capacity(value: Option) -> Result<(), ValidationError> { #[derive(Debug, Clone, SurrealValue)] pub struct Menu { - id: MenuId, - date: MenuDate, - slot: MenuSlot, - capacity: Option, - /// The menu's revision (see [`MENU_VERSION_FIELD`]). Absent on rows written - /// before the column existed, which reads as revision zero — the same thing - /// `(version ?? 0)` says in the claim's `WHERE`. The seat counter is - /// deliberately *not* here: it is the database's to own, and a whole-row - /// save must never carry a stale copy of it. - version: Option, - created_by: UserId, - created_at: Timestamp, + pub(crate) id: MenuId, + pub(crate) date: MenuDate, + pub(crate) slot: MenuSlot, + pub(crate) capacity: Option, + /// The menu's revision (see [`MENU_VERSION_FIELD`](crate::constant::MENU_VERSION_FIELD)). + /// Absent on rows written before the column existed, which reads as + /// revision zero — the same thing `(version ?? 0)` says in the claim's + /// `WHERE`. The seat counter is deliberately *not* here: it is the + /// database's to own, and a whole-row save must never carry a stale copy + /// of it. + pub(crate) version: Option, + pub(crate) created_by: UserId, + pub(crate) created_at: Timestamp, } impl Menu { @@ -321,209 +230,12 @@ impl Menu { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - /// Publish a menu. Refused (409) when the day+slot already carries one. - /// - /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the - /// refusal is decided by the store rather than by a check a concurrent - /// publish can outrun: two publishes of the same meal write one id, and the loser's - /// "already exists" becomes the same 409. The pre-check stays for the - /// ordinary case — and for menus published before ids were derived, whose - /// ULID key no new publish can collide with. - pub async fn create( - date: MenuDate, - slot: MenuSlot, - capacity: Option, - created_by: &UserId, - db: &Database, - ) -> Result { - let taken = AppError::Conflict("a menu is already published for that date and slot"); - if Self::find(&date, &slot, db).await?.is_some() { - return Err(taken); - } - // The menu takes a reference on its slot, which is what stops the slot - // being dropped from the settings while this menu (whose slot is only - // snapshotted text) still points at it. Claimed *inside* the write's own - // transaction: a claim of its own could land and the row then fail to, - // leaving the slot counted by a menu that does not exist — a slot - // nobody can ever retire, and no crash window is small enough for that. - let counter = slot_ref(slot.as_str()); - let menu = Menu { - id: MenuId::for_slot(&date, &slot), - date, - slot, - capacity, - version: Some(0), - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let id = menu.id.record(); - match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { - cap::ClaimedRef::Made(created) => Ok(created), - cap::ClaimedRef::Duplicate => Err(taken), - cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( - "the '{}' meal slot has been removed from the school's settings", - menu.slot.as_str() - ))), - } - } - - pub async fn read(id: &MenuId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// The menu for one day and slot, if any — the uniqueness check. - pub async fn find( - date: &MenuDate, - slot: &MenuSlot, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") - .bind(("date", date.as_str().to_string())) - .bind(("slot", slot.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; - /// either may be omitted. The comparison is lexical, which is chronological - /// for this format. - pub async fn list( - from: Option<&MenuDate>, - to: Option<&MenuDate>, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", - "ORDER BY date DESC, slot ASC, id DESC", - ) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) - .run(limit, offset, db) - .await - } - - /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, - /// because moving a published menu to another day is a different menu. - /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. - /// - /// The revision moves **in the same statement** as the cap, indivisibly: a - /// booking claims its seat against the revision - /// it read the cap at, so a shrink that bumped in a query of its own left a - /// window where the row carried the *new* revision and the *old* cap — and - /// a booking arriving there passes a CAS meant to refuse it, over-admitting - /// by exactly the seats in flight. - pub async fn update( - self, - capacity: Option>, - db: &Database, - ) -> Result { - let Some(capacity) = capacity else { - // A PATCH carrying nothing writes nothing and bumps nothing: no - // booking's price or cap has moved, so none owes a re-read. - return Self::read(&self.id, db).await?.ok_or(AppError::NotFound); - }; - let sql = format!( - "UPDATE $id SET capacity = $capacity, \ - {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" - ); - // One counter write in flight at a time, like every other one. - let _guard = cap::counter_lock().await; - write_with_retry::( - db, - &sql, - &[ - ("id".into(), self.id.record().into_value()), - ("capacity".into(), capacity.into_value()), - ], - ) - .await? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Delete the menu and the dishes on it — a dish has no meaning without - /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. - /// - /// Refused (409) while a seat is still held, and the *row itself* decides - /// that: the delete carries the seat counter in its `WHERE`, so a booking - /// landing at that instant either takes its seat before - /// the delete (which then finds a non-zero counter and refuses) or after it - /// (and finds no menu). A read-then-delete pair had a window where both - /// happened — a paid seat on a menu that no longer exists. - /// - /// The slot gets its reference back in that same transaction — a slot no - /// menu is published for any more may leave the settings again, and the - /// `FOR` runs only over a row the guard actually took. Released afterwards - /// in a query of its own, a crash between the two left the slot counted by - /// a menu that no longer exists: a slot nobody can retire. - /// - /// The marks go in that same `FOR`, for a sharper reason than tidiness: - /// [`MenuId::for_slot`] is deterministic, so republishing the same day and - /// slot mints the *same* record id. A mark left behind would come back as a - /// mark on the new menu — the kitchen reading "served" for a student who - /// never came — and until then the student's own report cites a menu that - /// is gone. Attendance carries no money and no counter, so it is safe to - /// drop; cancelled *bookings* deliberately stay, because their `attempt` - /// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut - /// those and a re-book on a republished menu would reuse a charge id the - /// ledger already holds, and the append (idempotent by design) would bill - /// the seat nothing. - /// - /// The dishes ride in that `FOR` too, and for the same reason as the marks: - /// run after the transaction committed, a crash between the two orphaned - /// them on a record id republishing the day and slot mints again — a new - /// menu serving (and pricing) the old one's food. - pub async fn delete(self, db: &Database) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - FOR $row IN ($gone ?? []) {{ - UPSERT $counter SET {REF_COUNT_FIELD} = \ - math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); - DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; - DELETE {MENU_DISH_TABLE} WHERE menu = $id; - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ); - // `slot` is a `READONLY` column, so this counter is the one the deleted - // row carries. Nothing here can answer "already exists" — the `UPSERT` - // is keyed by a slot name on a table with no `UNIQUE` index, so it - // resolves onto the row it names ([`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("id".into(), self.id.record().into_value()), - ("counter".into(), slot_ref(self.slot.as_str()).into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN, the LET and the FOR take a slot each. - let Some(deleted) = result.take::>(3)?.into_iter().next() else { - // Nothing back: either seats are held, or the menu is already gone. - return Err(match Self::read(&self.id, db).await? { - Some(_) => AppError::Conflict("the menu still has live bookings"), - None => AppError::NotFound, - }); - }; - Ok(deleted) - } } #[cfg(test)] mod tests { use super::*; + use surrealdb::types::Value; #[test] fn date_accepts_only_padded_calendar_days() { @@ -657,318 +369,4 @@ mod tests { assert!(validate_capacity(Some(-1)).is_err()); assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err()); } - - // --- the slot reference and the menu row move together --------------- - - async fn school() -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - db - } - - fn lunch() -> MenuSlot { - MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() - } - - /// The reference count, re-read out of the store — never off a return - /// value, which the in-memory engine forges wins on. - async fn refs(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE (count ?? 0) FROM $id") - .bind(("id", slot_ref("lunch"))) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() - .unwrap_or(0) - } - - async fn publish(date: &str, db: &Database) -> Result { - Menu::create( - MenuDate::try_new(date).unwrap(), - lunch(), - None, - &UserId::from_key("teacher"), - db, - ) - .await - } - - /// Plant a menu row the pre-check will (or will not) find, without going - /// through the claim — a row published before the counter existed. - async fn plant(id: &MenuId, date: &str, db: &Database) { - db.query( - "CREATE $id SET date = $date, slot = 'lunch', \ - created_by = user:teacher, created_at = 1", - ) - .bind(("id", id.record())) - .bind(("date", date.to_string())) - .await - .unwrap() - .check() - .unwrap(); - } - - #[tokio::test] - async fn publishing_lands_the_menu_and_its_reference_together() { - let db = school().await; - let menu = publish("2026-08-02", &db).await.unwrap(); - assert!(Menu::read(menu.get_id(), &db).await.unwrap().is_some()); - assert_eq!(refs(&db).await, 1); - - // The day+slot pre-check answers the second publish — and a refusal - // may not count the slot, or the menu would outlive its own reference. - let again = publish("2026-08-02", &db) - .await - .expect_err("that day and slot are taken"); - assert!(matches!(again, AppError::Conflict(_)), "got {again:?}"); - assert_eq!(refs(&db).await, 1); - } - - #[tokio::test] - async fn a_retired_slot_refuses_and_writes_nothing() { - let db = school().await; - assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); - - let refused = publish("2026-08-02", &db) - .await - .expect_err("the slot left the settings"); - assert!( - matches!(refused, AppError::ConflictOwned(_)), - "got {refused:?}" - ); - assert_eq!(refs(&db).await, 0); - assert!( - Menu::find(&MenuDate::try_new("2026-08-02").unwrap(), &lunch(), &db) - .await - .unwrap() - .is_none() - ); - } - - /// The race the fold exists for: a rival places the very row this publish - /// is placing, between the pre-check and the write. Only the claim's own - /// gate can answer it, and its answer must cost no reference. - #[tokio::test] - async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { - let db = school().await; - let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); - // Planted under another day, so `find` misses it exactly as it would - // in the instant before the rival's own row was visible. - plant(&id, "1999-01-01", &db).await; - - let taken = publish("2026-08-02", &db) - .await - .expect_err("the id is taken"); - assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); - assert_eq!(refs(&db).await, 0); - } - - /// Menus published before ids were derived keep a ULID key a new publish - /// cannot collide with, so the pre-check is the only thing that can refuse. - #[tokio::test] - async fn a_legacy_ulid_menu_still_answers_taken() { - let db = school().await; - plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; - - let taken = publish("2026-08-02", &db) - .await - .expect_err("that day and slot are taken"); - assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); - assert_eq!(refs(&db).await, 0); - } - - /// The cap and the revision are one write. Nothing single-process can - /// observe the torn state the two-query version left (a bumped revision - /// over a cap that had not moved yet), so what is pinned here is the pair: - /// the revision steps exactly once per cap move, and never for a PATCH that - /// carried no cap at all — a booking re-reads only when something it priced - /// itself against actually changed. - #[tokio::test] - async fn the_cap_and_the_revision_move_together_or_not_at_all() { - let db = school().await; - let menu = publish("2026-08-05", &db).await.unwrap(); - let id = menu.get_id().clone(); - assert_eq!(menu.get_version(), 0); - - let capped = menu.update(Some(Some(5)), &db).await.unwrap(); - assert_eq!(capped.get_capacity(), Some(5)); - assert_eq!(capped.get_version(), 1); - // Re-read out of the store, never off the return value. - let stored = Menu::read(&id, &db).await.unwrap().unwrap(); - assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1)); - - // An empty PATCH moves neither, and reads the row back unchanged. - let same = stored.update(None, &db).await.unwrap(); - assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1)); - - // Clearing the cap is a move like any other. - let uncapped = same.update(Some(None), &db).await.unwrap(); - assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2)); - } - - #[tokio::test] - async fn deleting_hands_the_reference_back_in_the_same_step() { - let db = school().await; - let monday = publish("2026-08-03", &db).await.unwrap(); - publish("2026-08-04", &db).await.unwrap(); - assert_eq!(refs(&db).await, 2); - - let id = monday.get_id().clone(); - let ghost = monday.clone(); - monday.delete(&db).await.unwrap(); - assert!(Menu::read(&id, &db).await.unwrap().is_none()); - assert_eq!(refs(&db).await, 1, "the row and its reference go together"); - - // Deleting what is already gone hands nothing back: a second release - // would leave a slot one menu still uses free to be retired. - let gone = ghost.delete(&db).await.expect_err("already deleted"); - assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); - assert_eq!(refs(&db).await, 1); - assert!( - !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), - "a slot a menu is still published for may not be retired" - ); - - // …and once the last menu goes, it may. - let last = Menu::find(&MenuDate::try_new("2026-08-04").unwrap(), &lunch(), &db) - .await - .unwrap() - .unwrap(); - last.delete(&db).await.unwrap(); - assert_eq!(refs(&db).await, 0); - } - - /// Nothing hanging off a menu may survive the delete that swept it — not a - /// dish, and not an attendance mark. Menu ids are deterministic on - /// (date, slot), so a survivor is not litter: republishing that meal mints - /// the *same* id and the orphan comes back attached to the new menu — the - /// kitchen reading "served" for a student who never came, or pricing the - /// old menu's food. - /// - /// The window is between [`Menu::delete`]'s `DELETE` and its cascade: a - /// child write committing in there is a phantom insert into a range the - /// delete already swept on an older snapshot, so the sweep removes nothing - /// and *both* commit. It is closed by making every child write **write** the - /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two - /// transactions then touch one key and the store refuses to commit both. - /// - /// The window is opened by the database itself rather than by a lucky - /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own - /// transaction, the instant the row goes, so the `SLEEP` lands exactly - /// between the delete and its sweep every single time. Nothing in `src/` - /// knows about it; the seam is the schema. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, which would fail this - /// test on correct code (see [`crate::database::init_test_server`]). - /// Mutation-tested: putting `MealAttendance::mark` back on a menu *read* - /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with) - /// turns this red at **both** of its two rounds — the mark commits, the - /// sweep misses it, and the row is left pointing at a menu that is gone. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_child_written_inside_a_delete_never_outlives_the_menu() { - use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; - use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; - - let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await; - db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - // Hold the delete open for a full second after the row is gone, while - // its cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut dishes, mut marks, mut swept) = (0, 0, 0); - for round in 0..4 { - let menu = publish(&format!("2026-09-{:02}", round + 1), &db) - .await - .unwrap(); - let id = menu.get_id().clone(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { menu.delete(&db).await }) - }; - // The child starts inside the held window — the delete's row is - // gone but uncommitted, which is exactly what a menu read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - // One child per round, never both: whichever wrote first forces the - // delete to re-send, and its second pass sweeps the other's row — - // which would mask exactly the defect this test exists to catch. - let child = { - let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0); - tokio::spawn(async move { - if dish { - MenuDish::create( - &id, - DishName::try_new("Pilav").unwrap(), - None, - DishPrice::try_new(1).unwrap(), - DishTags::try_new(&[], &[]).unwrap(), - &db, - ) - .await - .map(|_| ()) - } else { - MealAttendance::mark( - &id, - &UserId::from_key("teacher"), - MealAttendanceStatus::try_new("served").unwrap(), - &UserId::from_key("teacher"), - &db, - ) - .await - .map(|_| ()) - } - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the child, or a 409/NotFound for the delete, is a - // correct answer — the only defect is stored state. - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced child write must be answered, not 500: {child:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if Menu::read(&id, &db).await.unwrap().is_none() { - swept += 1; - dishes += MenuDish::list_for_menu(&id, &db).await.unwrap().len(); - marks += MealAttendance::list_for_menu(&id, None, 0, &db) - .await - .unwrap() - .1; - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the menu is still there"); - } - } - eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); - assert!( - swept > 0, - "no round ever deleted the menu, so the window was never reached" - ); - assert_eq!(dishes, 0, "a dish outlived its menu"); - assert_eq!(marks, 0, "a mark outlived its menu"); - } } diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 853dfec..3694cdb 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -4,20 +4,22 @@ //! Money is **minor units** (kuruş) as `i64` — never a float, never a decimal, //! at any layer. `tags` are validated against the school's `dietary_tags` //! list, the same contract a menu's `slot` has with `meal_slots`. +//! +//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the +//! write lock in [`crate::service::menu`]. use std::sync::LazyLock; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Generator; use crate::constant::{ MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, - MENU_DISH_TABLE, MENU_VERSION_FIELD, + MENU_DISH_TABLE, }; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::menu::{MenuId, bump_menu_and_write}; +use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; /// Mints dish ids in write order — see [`MenuId::generate`]; the listings below @@ -146,13 +148,13 @@ impl DishTags { #[derive(Debug, Clone, SurrealValue)] pub struct MenuDish { - id: MenuDishId, - menu: MenuId, - name: DishName, - description: Option, - price_minor: DishPrice, - tags: DishTags, - created_at: Timestamp, + pub(crate) id: MenuDishId, + pub(crate) menu: MenuId, + pub(crate) name: DishName, + pub(crate) description: Option, + pub(crate) price_minor: DishPrice, + pub(crate) tags: DishTags, + pub(crate) created_at: Timestamp, } impl MenuDish { @@ -183,167 +185,6 @@ impl MenuDish { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - /// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. - pub async fn create( - menu: &MenuId, - name: DishName, - description: Option, - price_minor: DishPrice, - tags: DishTags, - db: &Database, - ) -> Result { - let dish = MenuDish { - id: MenuDishId::generate(), - menu: menu.clone(), - name, - description, - price_minor, - tags, - created_at: Timestamp::now(), - }; - // The revision bump and the insert are one transaction, and the bump is - // what makes the menu's existence part of it: the `UPDATE` matches - // nothing once the menu row is deleted, and a delete racing this one - // touches the very key this transaction writes, so the two cannot both - // commit. Without that, a dish landing just after `DELETE /menus/{id}` - // removed the row but before its cascade ran outlived its menu. - // Every other dish write bumps the same version key, so a lost round is - // ordinary here; it is re-sent rather than reported. Re-sending is sound - // even with the `CREATE` in the batch — the abort wrote nothing, the id - // is a ULID freshly generated above and never seen by a rival, and - // `menu_dish` carries no UNIQUE index — so the retry cannot answer - // "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - CREATE $id CONTENT $dish; - COMMIT TRANSACTION;" - ), - &[ - ("menu".into(), menu.record().into_value()), - ("id".into(), dish.id.record().into_value()), - ("dish".into(), dish.into_value()), - ], - &["no_menu"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to add the dish".into())) - } - - pub async fn read(id: &MenuDishId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every dish on one menu, in the order they were added. - pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result, AppError> { - Self::list_for_menus(std::slice::from_ref(menu), db).await - } - - /// Dishes for a whole page of menus in one round trip — the alternative is - /// a query per menu, which is the N+1 the pagination slice exists to avoid. - pub async fn list_for_menus( - menus: &[MenuId], - db: &Database, - ) -> Result, AppError> { - if menus.is_empty() { - return Ok(Vec::new()); - } - let mut result = db - .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") - .bind(( - "menus", - menus.iter().map(MenuId::record).collect::>(), - )) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. - pub async fn count_for_menu(menu: &MenuId, db: &Database) -> Result { - Ok(Self::list_for_menu(menu, db).await?.len()) - } - - /// Write only the fields the PATCH carried. `description` is nullable, so - /// it takes the three-way shape: absent = keep, `Some(None)` = clear. - /// - /// The `SET` is built here rather than by - /// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the - /// revision bump lands on *another* row and has to share this write's - /// transaction; the field-by-field scoping — an omitted field is never - /// written, so a concurrent PATCH of another one is not reverted — is the - /// same rule, spelled out. - pub async fn update( - self, - name: Option, - description: Option>, - price_minor: Option, - tags: Option, - db: &Database, - ) -> Result { - let mut sets: Vec<&str> = Vec::new(); - let mut bindings: Vec<(String, Value)> = vec![("id".into(), self.id.record().into_value())]; - let mut set = |field: &'static str, value: Option| { - if let Some(value) = value { - sets.push(field); - bindings.push((field.into(), value)); - } - }; - set("name", name.map(SurrealValue::into_value)); - set("description", description.map(SurrealValue::into_value)); - set("price_minor", price_minor.map(SurrealValue::into_value)); - set("tags", tags.map(SurrealValue::into_value)); - // A PATCH that carried nothing writes nothing and reads the row back, - // exactly as `FieldUpdate` answers one — but it still moves the - // revision, because "every dish write bumps" is the rule a caller can - // rely on without knowing which fields were on the wire. - let statement = if sets.is_empty() { - "SELECT * FROM $id".to_string() - } else { - format!( - "UPDATE $id SET {} RETURN AFTER", - sets.iter() - .map(|field| format!("{field} = ${field}")) - .collect::>() - .join(", ") - ) - }; - bump_menu_and_write(&self.menu, &statement, bindings, db) - .await? - .ok_or(AppError::NotFound) - } - - pub async fn delete(self, db: &Database) -> Result { - bump_menu_and_write( - &self.menu, - "DELETE $id RETURN BEFORE", - vec![("id".into(), self.id.record().into_value())], - db, - ) - .await? - .ok_or(AppError::NotFound) - } } #[cfg(test)] diff --git a/src/service/dietary_profile.rs b/src/service/dietary_profile.rs new file mode 100644 index 0000000..7ef5ca6 --- /dev/null +++ b/src/service/dietary_profile.rs @@ -0,0 +1,32 @@ +//! The dietary-profile reads and saves the meal surfaces drive. The row is +//! one per student, created on first write and patched field-by-field; the +//! queries live in [`crate::db::dietary_profile`], the tag/note newtypes +//! and the pure tag intersection in [`crate::domain::dietary_profile`]. + +use crate::database::Database; +use crate::db::dietary_profile; +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// One student's profile, or `None` while the school never recorded one. +pub async fn read(db: &Database, student: &UserId) -> Result, AppError> { + dietary_profile::read(db, student).await +} + +/// The tags a menu read matches its dishes against: the caller's, or an +/// empty list when they have no profile. +pub async fn tags_of(db: &Database, student: &UserId) -> Result, AppError> { + dietary_profile::tags_of(db, student).await +} + +/// Write the fields the PATCH carried; creates the row on first write. +pub async fn save( + db: &Database, + student: &UserId, + tags: Option, + note: Option>, + by: &UserId, +) -> Result { + dietary_profile::save(db, student, tags, note, by).await +} diff --git a/src/service/meal_attendance.rs b/src/service/meal_attendance.rs new file mode 100644 index 0000000..c0d78d0 --- /dev/null +++ b/src/service/meal_attendance.rs @@ -0,0 +1,49 @@ +//! The attendance-mark workflows: recording who ate off a menu and the two +//! listings the kitchen and the student report read. The mark itself is a +//! single atomic UPSERT that rides the menu's revision bump +//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in +//! [`crate::db::meal_attendance`], the row shape in +//! [`crate::domain::meal_attendance`]. + +use crate::database::Database; +use crate::db::meal_attendance; +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; +use crate::domain::menu::MenuDate; +use crate::domain::menu::MenuId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Record (or overwrite) whether `student` ate off `menu`. `NotFound` when +/// the menu is gone — the mark was not written. +pub async fn mark( + db: &Database, + menu: &MenuId, + student: &UserId, + status: MealAttendanceStatus, + marked_by: &UserId, +) -> Result { + meal_attendance::mark(db, menu, student, status, marked_by).await +} + +/// The kitchen's list for one menu. +pub async fn list_for_menu( + db: &Database, + menu: &MenuId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + meal_attendance::list_for_menu(db, menu, limit, offset).await +} + +/// One student's marks, newest first, within inclusive `YYYY-MM-DD` bounds +/// on the menu's day. +pub async fn list_for_student( + db: &Database, + student: &UserId, + from: Option<&MenuDate>, + to: Option<&MenuDate>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + meal_attendance::list_for_student(db, student, from, to, limit, offset).await +} diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index dd595de..2443fbd 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -21,14 +21,17 @@ use crate::constant::{CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS}; use crate::database::{Database, backoff}; use crate::db::cap; use crate::db::meal_booking; +use crate::db::meal_ledger; +use crate::db::menu; use crate::domain::meal_booking::{ MealBooking, MealBookingId, MealBookingStatus, MealCutoff, check_cutoff, check_day_not_past, }; use crate::domain::meal_ledger::MealLedger; -use crate::domain::menu::{Menu, MenuId}; +use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use crate::service::meal_ledger::{charge_booking, reverse_booking}; /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already /// booked is returned as-is, claiming nothing; a cancelled row is revived as @@ -62,7 +65,7 @@ pub async fn book( let seats = menu.record(); for attempt in 0..CAP_WRITE_TRIES { backoff(attempt).await; - let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; + let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?; check_day_not_past(fresh.get_date())?; check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; let existing: Option = meal_booking::read(db, &id).await?; @@ -80,7 +83,7 @@ pub async fn book( .clone() .filter(|row| row.status == MealBookingStatus::Booked) { - MealLedger::charge_booking(&held, booked_by, db).await?; + charge_booking(db, &held, booked_by).await?; // Answered off a re-read, never off the row read a round trip // ago: a cancel committing in that gap has freed the seat, // given the money back and left the row `cancelled`, and @@ -117,7 +120,7 @@ pub async fn book( // Before the seat: an unchargeable menu (dishes summing past the // cap) must refuse the booking outright, never leave a // booked-but-unbilled row behind. - let price = MealLedger::price_snapshot(menu, db).await?; + let price = meal_ledger::price_snapshot(db, menu).await?; let fresh_row = MealBooking { id: id.clone(), menu: menu.clone(), @@ -155,7 +158,7 @@ pub async fn book( // reason is re-read rather than guessed. A moved menu is not a // refusal: the price above is stale, so price and seat are // taken again together. - cap::Claimed::Full => match Menu::read(menu, db).await? { + cap::Claimed::Full => match menu::read(db, menu).await? { None => return Err(AppError::NotFound), Some(now) if now.get_version() != fresh.get_version() => continue, Some(_) => return Err(AppError::Conflict("the menu is fully booked")), @@ -228,10 +231,10 @@ pub async fn cancel( .await? .ok_or(AppError::NotFound)?; if fresh.status == MealBookingStatus::Cancelled { - MealLedger::reverse_booking(&fresh, recorded_by, db).await?; + reverse_booking(db, &fresh, recorded_by).await?; return Ok(fresh); } - let menu = Menu::read(&fresh.menu, db) + let menu = menu::read(db, &fresh.menu) .await? .ok_or(AppError::NotFound)?; check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; @@ -251,7 +254,7 @@ pub async fn cancel( live } }; - MealLedger::reverse_booking(&saved, recorded_by, db).await?; + reverse_booking(db, &saved, recorded_by).await?; Ok(saved) } @@ -288,9 +291,10 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result< mod tests { use super::*; use crate::database::init_mem; + use crate::db::menu_dish; use crate::domain::meal_booking::MealBookingStatus; use crate::domain::meal_ledger::LedgerAmount; - use crate::domain::menu::{Menu, MenuDate, MenuSlot}; + use crate::domain::menu::{MenuDate, MenuSlot}; use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; use crate::domain::settings::MealSlotDef; @@ -304,12 +308,12 @@ mod tests { async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { let db = init_mem().await.unwrap(); let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; - let menu = Menu::create( + let menu = menu::create( + &db, MenuDate::try_new(date).unwrap(), MenuSlot::try_new("lunch", &slots).unwrap(), capacity, &UserId::generate(), - &db, ) .await .unwrap(); @@ -336,13 +340,13 @@ mod tests { } async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { - MenuDish::create( + menu_dish::create( + db, menu, DishName::try_new("çorba").unwrap(), None, DishPrice::try_new(price).unwrap(), DishTags::try_new(&[], &[]).unwrap(), - db, ) .await .unwrap() @@ -391,15 +395,15 @@ mod tests { let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) .await .unwrap(); - let row = Menu::read(&id, &db).await.unwrap().unwrap(); + let row = menu::read(&db, &id).await.unwrap().unwrap(); assert!(matches!( - row.clone().delete(&db).await, + menu::delete(&db, row.clone()).await, Err(AppError::Conflict(_)) )); cancel(&db, booking, &MealCutoff::default(), &ali) .await .unwrap(); - assert!(row.delete(&db).await.is_ok()); + assert!(menu::delete(&db, row).await.is_ok()); } /// A booking placed after a price edit is billed the new price, and one @@ -501,7 +505,7 @@ mod tests { Err(AppError::Conflict(_)) )); assert_eq!(seats(&menu, &db).await, 0); - let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) + let (lines, total) = meal_ledger::list_for_student(&db, &ali, None, 0) .await .unwrap(); assert!( @@ -535,8 +539,8 @@ mod tests { // ahead — the shape the create-side check cannot reach. A test cannot // age a menu (`date` is READONLY), so the seat is placed on an // already-past menu by the very transaction `book` places it with. - let fresh = Menu::read(&menu, &db).await.unwrap().unwrap(); - let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); + let fresh = menu::read(&db, &menu).await.unwrap().unwrap(); + let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); let row = MealBooking { id: MealBookingId::composite(&menu, &ali), menu: menu.clone(), @@ -575,7 +579,7 @@ mod tests { .expect("a cancel on a past day still frees the seat"); assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled); assert_eq!(seats(&menu, &db).await, 0); - let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db) + let (lines, _) = meal_ledger::list_for_student(&db, &ali, None, 0) .await .unwrap(); assert_eq!(lines.len(), 2, "the charge and its reversal"); diff --git a/src/service/meal_ledger.rs b/src/service/meal_ledger.rs new file mode 100644 index 0000000..ae6dad7 --- /dev/null +++ b/src/service/meal_ledger.rs @@ -0,0 +1,138 @@ +//! The money workflows around the append-only meal ledger: the booking +//! charge and its reversal (the ledger halves of the seat workflows in +//! [`crate::service::meal_booking`]) and the recorded credit. The rows, +//! id minters and the sign convention live in +//! [`crate::domain::meal_ledger`]; the writes and the SUM/balance reads in +//! [`crate::db::meal_ledger`]. + +use crate::database::Database; +use crate::db::meal_ledger; +use crate::domain::meal_booking::MealBooking; +use crate::domain::meal_ledger::{ + LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind, +}; +use crate::domain::payment_ledger::PaymentRequestKey; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Bill `booking`'s current attempt at the price frozen onto it when that +/// attempt took the seat. +/// +/// The price comes off the *booking row*, never off the menu as it stands +/// now: a seat taken while the menu was free carries `None` forever, so +/// "was free" is a recorded fact and a later dish never bills a seat +/// retroactively. Called from +/// [`book`](crate::service::meal_booking::book) alone, right after the seat +/// was claimed, so the seat and its money move together. +/// +/// Replaying it is free: the id is `(booking, attempt)`, so a duplicate +/// `POST` writes nothing, and an attempt whose charge failed the first time +/// self-heals on the next `POST` of the same seat. +pub async fn charge_booking( + db: &Database, + booking: &MealBooking, + recorded_by: &UserId, +) -> Result<(), AppError> { + let Some(line) = MealLedger::charge_for(booking, recorded_by) else { + return Ok(()); + }; + meal_ledger::append(db, line).await?; + Ok(()) +} + +/// Give the money back for a cancelled `booking`: a new `reversal` line for +/// the charge's exact amount, pointing at it. The charge is never touched. +/// A booking that was never billed (a free menu) reverses nothing, and +/// neither does one whose charge never landed — the reversal is keyed to +/// the very charge it undoes, so it can only exist alongside it. +/// +/// Keyed by `(booking, attempt)` like the charge, so a retried cancel +/// refunds once. The line normally lands *inside* the flip's own +/// transaction +/// ([`release_seat`](crate::db::meal_booking::release_seat)); this path is what heals a +/// seat flipped before that was true, and it is why +/// [`cancel`](crate::service::meal_booking::cancel) replays it on an already-cancelled row instead +/// of refusing it. Nothing else on the API can append the missing line. +pub async fn reverse_booking( + db: &Database, + booking: &MealBooking, + recorded_by: &UserId, +) -> Result<(), AppError> { + let Some((charge, line)) = MealLedger::reversal_for(booking, recorded_by) else { + return Ok(()); + }; + if meal_ledger::read(db, &charge).await?.is_none() { + return Ok(()); + } + meal_ledger::append(db, line).await?; + Ok(()) +} + +/// Money in: a payment received, or an opening balance. +/// +/// With a `request_key` the line is keyed by it (see +/// [`MealLedgerId::for_request`](crate::domain::meal_ledger::MealLedgerId::for_request)) +/// and the call is **retry-safe**: a client +/// resending the identical body after a timeout gets back the line the +/// first attempt wrote, not a second credit — nothing on this API can edit +/// or delete one, so a doubled credit is corrected only by a compensating +/// line. Without one the id is a fresh ulid and two identical calls are two +/// credits, which is what a desk taking the same amount twice really means. +pub async fn credit( + db: &Database, + student: &UserId, + amount_minor: LedgerAmount, + method: Option, + note: Option, + request_key: Option<&PaymentRequestKey>, + recorded_by: &UserId, +) -> Result { + let line = meal_ledger::append( + db, + MealLedger { + id: match request_key { + Some(key) => MealLedgerId::for_request(student, key), + None => MealLedgerId::generate(), + }, + student: student.clone(), + kind: MealLedgerKind::Credit, + amount_minor, + source: None, + method, + note, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + ) + .await?; + // A replay is answered from the stored line — but only if it is the + // same money. The same key for a different amount is a client bug, and + // handing back the old line would hide it behind a `201`. Checked on + // what `append` gave back rather than on a read before it: two retries + // arriving together both find no row, and only the id decides which + // one's amount is stored, so a check *before* the write would tell the + // loser its own amount landed. + if request_key.is_some() && line.get_amount_minor() != amount_minor { + return Err(AppError::Conflict( + "this request_key was already used for a different amount", + )); + } + Ok(line) +} + +/// A student's whole statement, newest first. +pub async fn list_for_student( + db: &Database, + student: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + meal_ledger::list_for_student(db, student, limit, offset).await +} + +/// The derived balance: `credits + reversals - charges`, in minor units. +/// Negative means the student owes the school. +pub async fn balance_of(db: &Database, student: &UserId) -> Result { + meal_ledger::balance_of(db, student).await +} diff --git a/src/service/menu.rs b/src/service/menu.rs new file mode 100644 index 0000000..52f2439 --- /dev/null +++ b/src/service/menu.rs @@ -0,0 +1,161 @@ +//! The kitchen's workflows: publishing and unpublishing menus, and every +//! dish write — which all hold [`MENU_LOCK`], the lock that makes the +//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB +//! does not conflict-check) more than a wish. The queries live in +//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the +//! date/slot/capacity rules in [`crate::domain::menu`] and +//! [`crate::domain::menu_dish`]. +//! +//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the +//! dishes, write the dish), which is why it lives here and not in the db +//! layer: a single-call atomicity lock would be the store's to own, but +//! count-then-write is write-skew only this process can serialize. +//! +//! **A leaf**: every dish write held under it moves the menu's revision +//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]), +//! so no path under this lock reaches `cap`'s counter lock any more. Should +//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing +//! may take this lock while holding a counter lock: that is the invariant a +//! new caller must keep, and it is what would keep the pair deadlock-free. + +use tokio::sync::Mutex; + +use crate::constant::MAX_DISHES_PER_MENU; +use crate::database::Database; +use crate::db::{menu, menu_dish}; +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; +use crate::domain::menu_dish::{ + DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, +}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Serializes what is left that counts rows against one menu: the dish cap +/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not +/// conflict-check). Publishing no longer needs it — the day+slot *is* the +/// record id — and neither does a booking, a menu delete, or the settings +/// slot-removal guard: those went to conditional single-record writes +/// ([`crate::db::cap`]), which the store decides as this lock cannot. +// +// corner-cut: the dish cap therefore rests on this lock alone — a dish write +// added without taking it reopens the count-then-write hole silently. Closing +// it properly is another `cap` counter (`dish_count` on the menu row) plus its +// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was +// not worth the column here. +pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); + +/// Publish a menu for one day and meal slot. The caller has validated the +/// date (a real calendar day, not already over), the slot (one the school +/// serves) and the capacity; the day+slot duplicate refusal is decided by +/// the store ([`menu::create`]). +pub async fn create( + db: &Database, + date: MenuDate, + slot: MenuSlot, + capacity: Option, + created_by: &UserId, +) -> Result { + menu::create(db, date, slot, capacity, created_by).await +} + +/// The menu, for callers that only inspect it — the web layer's handlers +/// read through here. +pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> { + menu::read(db, id).await +} + +/// Menus, newest day first, within inclusive `YYYY-MM-DD` bounds. +pub async fn list( + db: &Database, + from: Option<&MenuDate>, + to: Option<&MenuDate>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + menu::list(db, from, to, limit, offset).await +} + +/// Change a menu's seat cap; `None` keeps it, `Some(None)` clears it. +pub async fn update( + db: &Database, + menu_row: Menu, + capacity: Option>, +) -> Result { + menu::update(db, menu_row, capacity).await +} + +/// Unpublish a menu, sweeping its dishes and attendance marks in the same +/// transaction; refused while a seat is still held. +pub async fn delete(db: &Database, menu_row: Menu) -> Result { + menu::delete(db, menu_row).await +} + +/// Add a dish to a menu, under the dish cap. +/// +/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write +/// is write-skew, so the count and the insert have to be one step. The +/// *price* no longer needs it — a dish write moves the menu's revision, and +/// a booking claims its seat at the revision it priced itself against. +/// The lock is a leaf again: the revision bump rides the dish write's own +/// transaction now, so nothing held under it takes `cap`'s counter lock. It +/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a +/// caller that changes it must keep. +/// +/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` +/// running in the gap takes its cascade with it and this dish lands on a menu +/// that no longer exists. +pub async fn add_dish( + db: &Database, + menu_id: &MenuId, + name: DishName, + description: Option, + price_minor: DishPrice, + tags: DishTags, +) -> Result { + let _guard = MENU_LOCK.lock().await; + let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?; + if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU { + return Err(AppError::Conflict( + "the menu already carries the maximum number of dishes", + )); + } + menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await +} + +/// One dish, for callers that only inspect it. +pub async fn read_dish(db: &Database, id: &MenuDishId) -> Result, AppError> { + menu_dish::read(db, id).await +} + +/// Every dish on one menu, in the order they were added. +pub async fn list_dishes(db: &Database, menu_id: &MenuId) -> Result, AppError> { + menu_dish::list_for_menu(db, menu_id).await +} + +/// Dishes for a whole page of menus in one round trip. +pub async fn list_dishes_for_menus( + db: &Database, + menus: &[MenuId], +) -> Result, AppError> { + menu_dish::list_for_menus(db, menus).await +} + +/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see +/// [`add_dish`]. Only what the request carried is written. +pub async fn update_dish( + db: &Database, + dish: MenuDish, + name: Option, + description: Option>, + price_minor: Option, + tags: Option, +) -> Result { + let _guard = MENU_LOCK.lock().await; + menu_dish::update(db, dish, name, description, price_minor, tags).await +} + +/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write. +pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result { + let _guard = MENU_LOCK.lock().await; + menu_dish::delete(db, dish).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..7628477 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,16 +1,19 @@ //! Business rules, workflow locks, multi-call orchestration; calls db::*; no //! SurrealQL text. - pub mod appointment; pub mod appointment_slot; pub mod class_blueprint; pub mod course; pub mod course_session; +pub mod dietary_profile; pub mod enrollment; pub mod exam; pub mod exam_attempt; pub mod exam_question; +pub mod meal_attendance; pub mod meal_booking; +pub mod meal_ledger; +pub mod menu; pub mod note; pub mod payment_ledger; pub mod session; diff --git a/src/web/meals.rs b/src/web/meals.rs index 08398d9..1861bfe 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -18,13 +18,12 @@ use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::MAX_DISHES_PER_MENU; use crate::database::Database; -use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts}; +use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; -use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, }; @@ -206,9 +205,9 @@ async fn menu_responses( db: &Database, ) -> Result, AppError> { let ids: Vec = menus.iter().map(|menu| menu.get_id().clone()).collect(); - let dishes = MenuDish::list_for_menus(&ids, db).await?; + let dishes = service::menu::list_dishes_for_menus(db, &ids).await?; let people = person_map(menus.iter().map(|menu| menu.get_created_by().clone()), db).await?; - let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; + let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; Ok(menus .iter() .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags)) @@ -221,9 +220,9 @@ async fn one_menu( viewer: &UserId, db: &Database, ) -> Result, AppError> { - let dishes = MenuDish::list_for_menu(menu.get_id(), db).await?; + let dishes = service::menu::list_dishes(db, menu.get_id()).await?; let people = person_map([menu.get_created_by().clone()], db).await?; - let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; + let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; Ok(Json(MenuResponse::new( menu, &dishes, @@ -275,7 +274,7 @@ async fn create_menu( &service::settings::load(&st.db).await?.get_meal_slots(), )?; validate_capacity(req.capacity)?; - let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?; + let menu = service::menu::create(&st.db, date, slot, req.capacity, user.get_id()).await?; let body = one_menu(&menu, user.get_id(), &st.db).await?; Ok((StatusCode::CREATED, body)) } @@ -306,7 +305,8 @@ async fn list_menus( let (limit, offset) = page.resolve()?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; - let (menus, total) = Menu::list(from.as_ref(), to.as_ref(), limit, offset, &st.db).await?; + let (menus, total) = + service::menu::list(&st.db, from.as_ref(), to.as_ref(), limit, offset).await?; // The dish/people join runs over the page alone, so it shrinks with it. let items = menu_responses(&menus, user.get_id(), &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) @@ -330,7 +330,7 @@ async fn get_menu( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; one_menu(&menu, user.get_id(), &st.db).await @@ -363,10 +363,10 @@ async fn update_menu( if let Some(capacity) = req.capacity { validate_capacity(capacity)?; } - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - let updated = menu.update(req.capacity, &st.db).await?; + let updated = service::menu::update(&st.db, menu, req.capacity).await?; one_menu(&updated, user.get_id(), &st.db).await } @@ -392,12 +392,13 @@ async fn delete_menu( RequireManager(_user): RequireManager, Path(id): Path, ) -> Result { - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so - // a concurrent booking cannot slip between the read and the delete. - menu.delete(&st.db).await?; + // The seat check rides in the delete's own `WHERE` (the persistence + // layer's `menu::delete`), so a concurrent booking cannot slip between + // the read and the delete. + service::menu::delete(&st.db, menu).await?; Ok(StatusCode::NO_CONTENT) } @@ -438,28 +439,21 @@ async fn add_dish( &req.tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?; - // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write - // is write-skew, so the count and the insert have to be one step. The - // *price* no longer needs it — a dish write moves the menu's revision, and - // a booking claims its seat at the revision it priced itself against. - // The lock is a leaf again: the revision bump rides the dish write's own - // transaction now, so nothing held under it takes `cap`'s counter lock. It - // stays a leaf only while that holds — see [`MENU_LOCK`] for the order a - // caller that changes it must keep. - let _guard = MENU_LOCK.lock().await; - // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` - // running in the gap takes its cascade with it and this dish lands on a menu - // that no longer exists. - let menu = Menu::read(&MenuId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; - if MenuDish::count_for_menu(menu.get_id(), &st.db).await? >= MAX_DISHES_PER_MENU { - return Err(AppError::Conflict( - "the menu already carries the maximum number of dishes", - )); - } - let dish = MenuDish::create(menu.get_id(), name, description, price, tags, &st.db).await?; - let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; + // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK) + // lease live in the service: count-then-write is write-skew, so the count + // and the insert have to be one step, and the menu is read *inside* the + // lock — read before it, a `DELETE /menus/{id}` running in the gap takes + // its cascade with it and this dish lands on a menu that no longer exists. + let dish = service::menu::add_dish( + &st.db, + &MenuId::from_key(&id), + name, + description, + price, + tags, + ) + .await?; + let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(( StatusCode::CREATED, Json(DishResponse::new(&dish, &viewer_tags)), @@ -490,7 +484,7 @@ async fn update_dish( Path(did): Path, Json(req): Json, ) -> Result, AppError> { - let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) + let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; let name = req.name.as_deref().map(DishName::try_new).transpose()?; @@ -509,10 +503,10 @@ async fn update_dish( )?), None => None, }; - // Under [`MENU_LOCK`] like every dish write — see `add_dish`. - let _guard = MENU_LOCK.lock().await; - let updated = dish.update(name, description, price, tags, &st.db).await?; - let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; + // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) + // inside the service, like every dish write — see `add_dish`. + let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; + let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(Json(DishResponse::new(&updated, &viewer_tags))) } @@ -535,12 +529,12 @@ async fn delete_dish( RequireManager(_user): RequireManager, Path(did): Path, ) -> Result { - let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) + let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; - // Under [`MENU_LOCK`] like every dish write — see `add_dish`. - let _guard = MENU_LOCK.lock().await; - dish.delete(&st.db).await?; + // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) + // inside the service, like every dish write — see `add_dish`. + service::menu::delete_dish(&st.db, dish).await?; Ok(StatusCode::NO_CONTENT) } @@ -578,7 +572,7 @@ async fn profile_response( student: &UserId, db: &Database, ) -> Result, AppError> { - let profile = DietaryProfile::read(student, db).await?; + let profile = service::dietary_profile::read(db, student).await?; let people = person_map( std::iter::once(student.clone()) .chain(profile.as_ref().map(|row| row.get_updated_by().clone())), @@ -701,7 +695,7 @@ async fn update_profile( Some(None) => Some(None), Some(Some(text)) => Some(DietaryNote::try_new(&text)?), }; - DietaryProfile::save(&target, tags, note, manager.get_id(), &st.db).await?; + service::dietary_profile::save(&st.db, &target, tags, note, manager.get_id()).await?; profile_response(&target, &st.db).await } @@ -939,7 +933,7 @@ async fn list_menu_bookings( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let (rows, total) = @@ -1139,25 +1133,30 @@ async fn mark_attendance( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let status = MealAttendanceStatus::try_new(&req.status)?; let student = UserId::from_key(&req.student_id); // The target must exist; no booking is required, since a walk-in was still // served and the record is operationally true. - if crate::service::user::read(&st.db, &student).await?.is_none() { + if crate::service::user::read(&st.db, &student) + .await? + .is_none() + { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", reason: "target user does not exist", })); } - // The write moves the menu's own revision (see [`MealAttendance::mark`]), so + // The write moves the menu's own revision (see the persistence layer's + // `meal_attendance::mark`), so // a delete landing between the read above and this write cannot commit // alongside it — one of the two loses its round, and this one then answers // 404 with no mark behind it, exactly as the read would have. let row = - MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?; + service::meal_attendance::mark(&st.db, menu.get_id(), &student, status, marker.get_id()) + .await?; let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; Ok(Json( items.into_iter().next().expect("one mark in, one out"), @@ -1187,10 +1186,11 @@ async fn list_menu_attendance( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Menu must exist — a missing menu is a 404, not an empty list. - let menu = Menu::read(&MenuId::from_key(&id), &st.db) + let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; - let (rows, total) = MealAttendance::list_for_menu(menu.get_id(), limit, offset, &st.db).await?; + let (rows, total) = + service::meal_attendance::list_for_menu(&st.db, menu.get_id(), limit, offset).await?; let items = attendance_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -1225,13 +1225,13 @@ async fn user_attendance( ensure_can_read_student(&caller, &target, &st.db).await?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; - let (rows, total) = MealAttendance::list_for_student( + let (rows, total) = service::meal_attendance::list_for_student( + &st.db, &target, from.as_ref(), to.as_ref(), limit, offset, - &st.db, ) .await?; let items = attendance_responses(&rows, &st.db).await?; @@ -1311,7 +1311,7 @@ async fn balance_response( let people = person_map(std::iter::once(student.clone()), db).await?; Ok(Json(BalanceResponse { student: PersonRef::resolve(&people, student), - balance_minor: MealLedger::balance_of(student, db).await?, + balance_minor: service::meal_ledger::balance_of(db, student).await?, })) } @@ -1431,7 +1431,8 @@ async fn user_ledger( let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); ensure_can_read_money(&caller, &target, &st.db).await?; - let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?; + let (rows, total) = + service::meal_ledger::list_for_student(&st.db, &target, limit, offset).await?; let items = ledger_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -1504,7 +1505,7 @@ async fn record_credit( .ok_or(AppError::NotFound)? .get_role() != Role::Student - && MealLedger::list_for_student(&student, Some(1), 0, &st.db) + && service::meal_ledger::list_for_student(&st.db, &student, Some(1), 0) .await? .0 .is_empty() @@ -1519,7 +1520,8 @@ async fn record_credit( .as_deref() .map(PaymentRequestKey::try_new) .transpose()?; - let line = MealLedger::credit( + let line = service::meal_ledger::credit( + &st.db, &student, LedgerAmount::try_new(req.amount_minor)?, req.method @@ -1534,7 +1536,6 @@ async fn record_credit( .flatten(), request_key.as_ref(), admin.get_id(), - &st.db, ) .await?; let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?; diff --git a/tests/integration.rs b/tests/integration.rs index 65a4ac1..e1320f3 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -22187,8 +22187,9 @@ async fn concurrent_duplicate_menu_publishes_conflict_not_500() { /// writers before they can ever collide. #[tokio::test] async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { + use hezarfen_backend::db::meal_ledger; use hezarfen_backend::domain::meal_booking::MealBookingId; - use hezarfen_backend::domain::meal_ledger::MealLedger; + use hezarfen_backend::service::meal_ledger as ledger_service; let (app, db) = app_and_db().await; 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() { .expect("the booking exists"); let student = booking.get_student().clone(); assert_eq!( - MealLedger::balance_of(&student, &db).await.unwrap(), + meal_ledger::balance_of(&db, &student).await.unwrap(), -1000, "the seat was charged once" ); let (first, second) = tokio::join!( - MealLedger::reverse_booking(&booking, &student, &db), - MealLedger::reverse_booking(&booking, &student, &db), + ledger_service::reverse_booking(&db, &booking, &student), + ledger_service::reverse_booking(&db, &booking, &student), ); assert!(first.is_ok(), "the winner appended: {first:?}"); assert!( @@ -22248,12 +22249,12 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { "the loser must read back the winner's line, not fail: {second:?}" ); - let (lines, _) = MealLedger::list_for_student(&student, None, 0, &db) + let (lines, _) = meal_ledger::list_for_student(&db, &student, None, 0) .await .unwrap(); assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); assert_eq!( - MealLedger::balance_of(&student, &db).await.unwrap(), + meal_ledger::balance_of(&db, &student).await.unwrap(), 0, "the money moved back exactly once" ); @@ -23941,7 +23942,7 @@ async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the /// concurrent claim lives where the store can testify about it — -/// `domain::menu::tests::a_child_written_inside_a_delete_never_outlives_the_menu`, +/// `db::menu::tests::a_child_written_inside_a_delete_never_outlives_the_menu`, /// `#[ignore]`d and run against a real server — and what stays here is the /// logic, pinned deterministically. #[tokio::test] diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs index 887f7c1..ac637c8 100644 --- a/tests/regress_meals.rs +++ b/tests/regress_meals.rs @@ -11,8 +11,10 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; -use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; -use hezarfen_backend::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; +use hezarfen_backend::db::meal_attendance; +use hezarfen_backend::db::menu; +use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus; +use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot}; use hezarfen_backend::domain::settings::MealSlotDef; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; @@ -108,12 +110,12 @@ async fn a_menu_behind_the_calendar_is_neither_publishable_nor_bookable() { // Half two: the menu the create-side check cannot reach — published while // its day was still ahead, written here as the store holds it, since no // route publishes one any more. - let stale = Menu::create( + let stale = menu::create( + &db, MenuDate::try_new("2020-01-02").unwrap(), MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap(), None, &UserId::from_key(&me_id(&app, &mgr).await), - &db, ) .await .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() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); - let marked = MealAttendance::mark( + let marked = meal_attendance::mark( + &db, &menu, &ali_id, MealAttendanceStatus::try_new("served").unwrap(), &mgr_id, - &db, ) .await .expect_err("the mark is refused"); @@ -481,7 +483,7 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() { "no menu, no mark: {marked:?}" ); assert_eq!( - MealAttendance::list_for_menu(&menu, None, 0, &db) + meal_attendance::list_for_menu(&db, &menu, None, 0) .await .unwrap() .1,