forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'postgres' into pg/l9

Browse files at this commit

288a8b652cfc078c69c3329153450bcf3ef9dfe6Ahmet Kaan GümüşParent: bc532b949bca69
src/db/dietary_profile.rsmodified+47 -44
@@ -1,20 +1,28 @@
1-//! The `dietary_profile` table: one row per student (the record key *is*1+//! The `dietary_profile` table: one row per student (the primary key *is*
2-//! the student's key), created on first write and afterwards patched2+//! the student), created on first write and afterwards patched
3-//! field-by-field. The tag/note newtypes and the pure tag intersection live3+//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The
4-//! in [`crate::domain::dietary_profile`]; the web layer reads through4+//! tag/note newtypes and the pure tag intersection live in
5+//! [`crate::domain::dietary_profile`]; the web layer reads through
5 //! [`crate::service::dietary_profile`].6 //! [`crate::service::dietary_profile`].
6 7
7 use crate::database::Database;8 use crate::database::Database;
8-use crate::db::field_update::FieldUpdate;9+use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags};
9-use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags};
10 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
12 use crate::error::AppError;12 use crate::error::AppError;
13 13
14 /// One student's profile, or `None` while the school never recorded one.14 /// One student's profile, or `None` while the school never recorded one.
15-/// A single `SELECT` by record id — this is what a menu read joins on.15+/// A single `SELECT` by key — this is what a menu read joins on.
16 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {16 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {
17- Ok(db.select(DietaryProfileId::of(student).record()).await?)17+ let row = sqlx::query_as!(
18+ DietaryProfile,
19+ "SELECT student, tags, note, updated_by, updated_at
20+ FROM dietary_profile WHERE student = $1",
21+ *student,
22+ )
23+ .fetch_optional(db)
24+ .await?;
25+ Ok(row)
18 }26 }
19 27
20 /// The tags a menu read matches its dishes against: the caller's, or an28 /// The tags a menu read matches its dishes against: the caller's, or an
@@ -27,9 +35,17 @@ pub async fn tags_of(db: &Database, student: &UserId) -> Result<Vec<String>, App
27 }35 }
28 36
29 /// Write the fields the PATCH carried. Creates the row on first write;37 /// Write the fields the PATCH carried. Creates the row on first write;
30-/// afterwards only the named fields move, because `student` is `READONLY`38+/// afterwards only the named fields move, because a whole-row save would
31-/// and a whole-row save would also revert a concurrent edit of the other39+/// also revert a concurrent edit of the other field.
32-/// field (see [`FieldUpdate`]).40+///
41+/// Both paths are one statement: an absent `tags` keeps the stored list
42+/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note
43+/// clears it and a `Some(Some)` overwrites it — the same three-way shape,
44+/// spelled with a "was the field on the request?" flag plus its nullable
45+/// value. A rival `PATCH` that created the row a moment ago turns this
46+/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all,
47+/// exactly as it would have been a moment later — without the error the old
48+/// store's create-then-patch pair had to catch.
33 pub async fn save(49 pub async fn save(
34 db: &Database,50 db: &Database,
35 student: &UserId,51 student: &UserId,
@@ -37,37 +53,24 @@ pub async fn save(
37 note: Option<Option<DietaryNote>>,53 note: Option<Option<DietaryNote>>,
38 by: &UserId,54 by: &UserId,
39 ) -> Result<DietaryProfile, AppError> {55 ) -> Result<DietaryProfile, AppError> {
40- if read(db, student).await?.is_none() {56+ let row = sqlx::query_as!(
41- let profile = DietaryProfile {57+ DietaryProfile,
42- id: DietaryProfileId::of(student),58+ "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)
43- student: student.clone(),59+ VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)
44- tags: tags.clone().unwrap_or(DietaryTags(Vec::new())),60+ ON CONFLICT (student) DO UPDATE SET
45- note: note.clone().flatten(),61+ tags = COALESCE($2, dietary_profile.tags),
46- updated_by: by.clone(),62+ note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,
47- updated_at: Timestamp::now(),63+ updated_by = $4,
48- };64+ updated_at = $5
49- match db.create(profile.id.record()).content(profile).await {65+ RETURNING student, tags, note, updated_by, updated_at",
50- Ok(Some(created)) => return Ok(created),66+ *student,
51- Ok(None) => {67+ tags.map(|t| t.as_slice().to_vec()),
52- return Err(AppError::Internal("failed to save the profile".into()));68+ note.clone().flatten().map(|n| n.as_str().to_string()),
53- }69+ *by,
54- // A rival first `PATCH` created the row in the round trip since70+ Timestamp::now(),
55- // the read above (the `dietary_profile_student` UNIQUE index71+ note.is_some(),
56- // catches the same collision), and `CREATE` leaves that row72+ )
57- // untouched — so this call is a plain field write after all,73+ .fetch_one(db)
58- // exactly as it would have been a moment later. Propagated, it74+ .await?;
59- // was a 500 on a legitimate request. Same shape as75+ Ok(row)
60- // [`crate::db::meal_ledger::append`], which
61- // reads the winner back rather than failing.
62- Err(err) if err.is_already_exists() => {}
63- Err(err) => return Err(err.into()),
64- }
65- }
66- FieldUpdate::new(DietaryProfileId::of(student).record())
67- .set("tags", tags)
68- .set("note", note)
69- .set("updated_by", Some(by.clone()))
70- .set("updated_at", Some(Timestamp::now()))
71- .run::<DietaryProfile>(db)
72- .await
73 }76 }
src/db/meal_attendance.rsmodified+64 -61
@@ -1,38 +1,31 @@
1 //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per1 //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per
2-//! (menu, student) that rides the menu's revision bump2+//! (menu, student) that rides the menu's revision bump inside its own
3-//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the3+//! transaction, plus the two listings. Attendance is reporting only: nothing
4-//! two listings. Attendance is reporting only: nothing here writes the4+//! here writes the ledger, and the workflows that read it live in the web
5-//! ledger, and the workflows that read it live in the web layer via5+//! layer via [`crate::service::meal_attendance`].
6-//! [`crate::service::meal_attendance`].
7 6
8-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry};
9-8+use crate::db::page::{PagedList, Param};
10-use crate::database::Database;9+use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
11-use crate::db::menu::bump_menu_and_write;10+use crate::domain::menu::{MenuDate, MenuId};
12-use crate::db::page::PagedList;
13-use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus};
14-use crate::domain::menu::MenuDate;
15-use crate::domain::menu::MenuId;
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
18 use crate::error::AppError;13 use crate::error::AppError;
19 14
20 /// Record (or overwrite) whether `student` ate off `menu`. One row per15 /// Record (or overwrite) whether `student` ate off `menu`. One row per
21-/// pair by construction, so a correction is the same UPSERT flipping the16+/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is
22-/// status. No ledger line, ever — see the domain module header.17+/// the same upsert flipping the status. No ledger line, ever — see the
18+/// domain module header.
23 ///19 ///
24 /// `NotFound` = the menu is gone, and the mark was *not* written. The mark20 /// `NotFound` = the menu is gone, and the mark was *not* written. The mark
25-/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to21+/// and the menu's revision bump share one transaction, and the bump is what
26-/// the menu row rather than a read the write then trusts: a delete racing22+/// makes the menu's **existence** part of it: the `UPDATE` matches nothing
27-/// this one touches the very key this transaction bumps, and the store23+/// once the menu row is deleted, and Postgres commits a deleting and a
28-/// refuses to commit both. Guarding by reading the menu — even as the24+/// bumping transaction on the same row strictly one after the other — the
29-/// `UPSERT`'s own target — did not survive that race: the read saw a row25+/// mark either lands before the delete's guard re-reads its counter or not
30-/// [`crate::db::menu::delete`] had deleted but not26+/// at all. (Under the old store the same guarantee needed the shared bump
31-/// yet committed, its sweep ran on a snapshot predating this insert, and the27+/// shape because deletes and child writes could interleave with a read in
32-/// mark outlived its menu with neither caller told anything (measured 378 of28+/// between.)
33-/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic,
34-/// republishing that day and slot then resurrected it as a mark on the new
35-/// menu.
36 ///29 ///
37 /// The bump costs a booking in flight one re-read (its seat claim asserts30 /// The bump costs a booking in flight one re-read (its seat claim asserts
38 /// the revision it priced against) — the same tax every dish write already31 /// the revision it priced against) — the same tax every dish write already
@@ -45,30 +38,40 @@ pub async fn mark(
45 status: MealAttendanceStatus,38 status: MealAttendanceStatus,
46 marked_by: &UserId,39 marked_by: &UserId,
47 ) -> Result<MealAttendance, AppError> {40 ) -> Result<MealAttendance, AppError> {
48- let row = MealAttendance {41+ let marked_at = Timestamp::now();
49- id: MealAttendanceId::composite(menu, student),42+ let student = *student;
50- menu: menu.clone(),43+ let marked_by = *marked_by;
51- student: student.clone(),44+ tx_with_retry(db, false, async |tx| {
52- status,45+ let bumped = sqlx::query!(
53- marked_by: marked_by.clone(),46+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
54- marked_at: Timestamp::now(),47+ RETURNING 1 AS bumped",
55- };48+ menu.key(),
56- // Admissible for the retry loop inside: the id is bijective with the49+ )
57- // (menu, student) pair the table indexes UNIQUE, so this `UPSERT`50+ .fetch_optional(&mut *tx)
58- // resolves onto the row that index already points at instead of51+ .await?;
59- // colliding with it — it can never answer "already exists", and a52+ if bumped.is_none() {
60- // re-sent round writes the identical row.53+ return Err(AppError::NotFound);
61- bump_menu_and_write(54+ }
62- menu,55+ let row = sqlx::query_as!(
63- "UPSERT $id CONTENT $row RETURN AFTER",56+ MealAttendance,
64- vec![57+ "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at)
65- ("id".into(), row.id.record().into_value()),58+ VALUES ($1, $2, $3, $4, $5)
66- ("row".into(), row.into_value()),59+ ON CONFLICT (menu, student) DO UPDATE
67- ],60+ SET status = EXCLUDED.status,
68- db,61+ marked_by = EXCLUDED.marked_by,
69- )62+ marked_at = EXCLUDED.marked_at
70- .await?63+ RETURNING menu, student, status, marked_by, marked_at",
71- .ok_or_else(|| AppError::Internal("failed to record the mark".into()))64+ menu.key(),
65+ student,
66+ status,
67+ marked_by,
68+ marked_at,
69+ )
70+ .fetch_one(&mut *tx)
71+ .await?;
72+ Ok(row)
73+ })
74+ .await
72 }75 }
73 76
74 /// The kitchen's list for one menu.77 /// The kitchen's list for one menu.
@@ -79,10 +82,10 @@ pub async fn list_for_menu(
79 offset: i64,82 offset: i64,
80 ) -> Result<(Vec<MealAttendance>, i64), AppError> {83 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
81 PagedList::new(84 PagedList::new(
82- "meal_attendance WHERE menu = $menu",85+ "meal_attendance WHERE menu = $1",
83- "ORDER BY marked_at DESC, id DESC",86+ "ORDER BY marked_at DESC, menu DESC",
84 )87 )
85- .bind("menu", menu.record())88+ .bind(menu.key().to_string())
86 .run(limit, offset, db)89 .run(limit, offset, db)
87 .await90 .await
88 }91 }
@@ -91,7 +94,7 @@ pub async fn list_for_menu(
91 /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical,94 /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical,
92 /// which is chronological for that format (see [`MenuDate`]), and the link95 /// which is chronological for that format (see [`MenuDate`]), and the link
93 /// is followed rather than denormalized so a row can never disagree with96 /// is followed rather than denormalized so a row can never disagree with
94-/// the menu it belongs to.97+/// the menu it belongs to. A `NULL` bound means the bound is absent.
95 pub async fn list_for_student(98 pub async fn list_for_student(
96 db: &Database,99 db: &Database,
97 student: &UserId,100 student: &UserId,
@@ -101,14 +104,14 @@ pub async fn list_for_student(
101 offset: i64,104 offset: i64,
102 ) -> Result<(Vec<MealAttendance>, i64), AppError> {105 ) -> Result<(Vec<MealAttendance>, i64), AppError> {
103 PagedList::new(106 PagedList::new(
104- "meal_attendance WHERE student = $usr \107+ "meal_attendance WHERE student = $1 \
105- AND ($from = NONE OR menu.date >= $from) \108+ AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \
106- AND ($to = NONE OR menu.date <= $to)",109+ AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",
107- "ORDER BY marked_at DESC, id DESC",110+ "ORDER BY marked_at DESC, menu DESC",
108 )111 )
109- .bind("usr", student.record())112+ .bind(student.key())
110- .bind("from", from.map(|date| date.as_str().to_string()))113+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
111- .bind("to", to.map(|date| date.as_str().to_string()))114+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
112 .run(limit, offset, db)115 .run(limit, offset, db)
113 .await116 .await
114 }117 }
src/db/meal_booking.rsmodified+233 -191
@@ -1,14 +1,11 @@
1 //! The `meal_booking` table: row reads, the two listings, and the folded1 //! The `meal_booking` table: row reads, the two listings, and the folded
2-//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge2+//! transactions every seat moves by — [`claim_and_place`] (seat + row +
3-//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in3+//! charge in one transaction) and [`release_seat`] (flip + counter + refund
4-//! one). The book/cancel workflows that sequence these live in4+//! in one). The book/cancel workflows that sequence these live in
5-//! [`crate::service::meal_booking`]; the row shape and the deadline checks in5+//! [`crate::service::meal_booking`]; the row shape and the deadline checks
6-//! [`crate::domain::meal_booking`].6+//! in [`crate::domain::meal_booking`].
7 7
8-use surrealdb::types::RecordId;8+use crate::database::{Database, tx_with_retry};
9-
10-use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD};
11-use crate::database::{Database, backoff, lost_the_race};
12 use crate::db::cap::Claimed;9 use crate::db::cap::Claimed;
13 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
14 use crate::domain::meal_booking::{MealBooking, MealBookingId};11 use crate::domain::meal_booking::{MealBooking, MealBookingId};
@@ -19,7 +16,16 @@ use crate::domain::user::UserId;
19 use crate::error::AppError;16 use crate::error::AppError;
20 17
21 pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {18 pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {
22- Ok(db.select(id.record()).await?)19+ let row = sqlx::query_as!(
20+ MealBooking,
21+ "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at
22+ FROM meal_booking WHERE menu = $1 AND student = $2",
23+ id.menu().key(),
24+ *id.student(),
25+ )
26+ .fetch_optional(db)
27+ .await?;
28+ Ok(row)
23 }29 }
24 30
25 /// Every booking on a menu, cancelled ones included — the kitchen's list.31 /// Every booking on a menu, cancelled ones included — the kitchen's list.
@@ -30,10 +36,10 @@ pub async fn list_for_menu(
30 offset: i64,36 offset: i64,
31 ) -> Result<(Vec<MealBooking>, i64), AppError> {37 ) -> Result<(Vec<MealBooking>, i64), AppError> {
32 PagedList::new(38 PagedList::new(
33- "meal_booking WHERE menu = $menu",39+ "meal_booking WHERE menu = $1",
34- "ORDER BY created_at DESC, id DESC",40+ "ORDER BY created_at DESC, student DESC",
35 )41 )
36- .bind("menu", menu.record())42+ .bind(menu.key().to_string())
37 .run(limit, offset, db)43 .run(limit, offset, db)
38 .await44 .await
39 }45 }
@@ -41,10 +47,10 @@ pub async fn list_for_menu(
41 /// Every seat held for one of `students`, newest first — a caller's own47 /// Every seat held for one of `students`, newest first — a caller's own
42 /// list is themselves plus whoever they hold a *live* parent link to.48 /// list is themselves plus whoever they hold a *live* parent link to.
43 ///49 ///
44-/// Deliberately **not** `booked_by = $usr`: who placed a booking is history50+/// Deliberately **not** `booked_by`: who placed a booking is history
45-/// written onto a READONLY column, and history is not a read grant. A51+/// written onto a fixed column, and history is not a read grant. A parent
46-/// parent whose link was revoked (by an unlink or by the student-side role52+/// whose link was revoked (by an unlink or by the student-side role sweep)
47-/// sweep) would otherwise keep a live view of the child's seat, watching53+/// would otherwise keep a live view of the child's seat, watching
48 /// cancellations made long after the link died — exactly what54 /// cancellations made long after the link died — exactly what
49 /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The55 /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The
50 /// caller re-derives the list from the links on every read, so the view56 /// caller re-derives the list from the links on every read, so the view
@@ -55,34 +61,52 @@ pub async fn list_for_students(
55 limit: Option<i64>,61 limit: Option<i64>,
56 offset: i64,62 offset: i64,
57 ) -> Result<(Vec<MealBooking>, i64), AppError> {63 ) -> Result<(Vec<MealBooking>, i64), AppError> {
58- PagedList::new(64+ if students.is_empty() {
59- "meal_booking WHERE student IN $students",65+ return Ok((Vec::new(), 0));
60- "ORDER BY created_at DESC, id DESC",66+ }
61- )67+ let keys: Vec<String> = students.iter().map(UserId::key).collect();
62- .bind(68+ let rows = sqlx::query_as!(
63- "students",69+ MealBooking,
64- students.iter().map(UserId::record).collect::<Vec<_>>(),70+ "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at
71+ FROM meal_booking WHERE student = ANY($1::uuid[])
72+ ORDER BY created_at DESC, menu DESC
73+ LIMIT $2 OFFSET $3",
74+ keys,
75+ limit,
76+ offset,
65 )77 )
66- .run(limit, offset, db)78+ .fetch_all(db)
67- .await79+ .await?;
80+ // The window's own total — the same count the paging envelope answers.
81+ let total = if limit.is_some() || offset != 0 {
82+ sqlx::query_scalar!(
83+ "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])",
84+ keys,
85+ )
86+ .fetch_one(db)
87+ .await? as i64
88+ } else {
89+ rows.len() as i64
90+ };
91+ Ok((rows, total))
68 }92 }
69 93
70 /// Take the seat **and** place the row in one transaction, at the menu94 /// Take the seat **and** place the row in one transaction, at the menu
71 /// revision the price was read at.95 /// revision the price was read at.
72 ///96 ///
73-/// The seat and the row cannot be two steps. The id is the (menu, student)97+/// The seat and the row cannot be two steps. The row key is the (menu,
74-/// pair, so two `POST`s of the same seat both find no row and both claim —98+/// student) pair, so two `POST`s of the same seat both find no row and both
75-/// and on a tight cap the second is then told "full" for a seat it never99+/// claim — and on a tight cap the second is then told "full" for a seat it
76-/// owed, while the winner's row may not even be visible yet. Here the100+/// never owed, while the winner's row may not even be visible yet. Here the
77-/// duplicate `CREATE` aborts the transaction, which takes its increment with101+/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays
78-/// it: the counter never counts a row that does not exist, and a loser is102+/// the winner, while the whole transaction (seat bump included) rolls back
79-/// answered with the winner's booking instead of a refusal. Same shape as103+/// on any refused path: the counter never counts a row that does not exist.
80-/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the104+/// Same shape as the [`crate::db::cap`] claim recipe, with the revision
81-/// revision guard and the revival of a cancelled row that the general form105+/// guard and the revival of a cancelled row that the general form does not
82-/// does not carry.106+/// carry.
83 ///107 ///
84 /// A cancelled row is revived in place (a fresh attempt at `price`) rather108 /// A cancelled row is revived in place (a fresh attempt at `price`) rather
85-/// than recreated: `booked_by` and `created_at` are READONLY history — who109+/// than recreated: `booked_by` and `created_at` are fixed history — who
86 /// opened the seat, and when.110 /// opened the seat, and when.
87 ///111 ///
88 /// **The charge rides this transaction too**, for the same reason the112 /// **The charge rides this transaction too**, for the same reason the
@@ -93,118 +117,135 @@ pub async fn list_for_students(
93 /// moved past. That is why `row.attempt` is minted by the *caller*: the117 /// moved past. That is why `row.attempt` is minted by the *caller*: the
94 /// charge's id is (seat, attempt), so the number cannot be the revival's own118 /// charge's id is (seat, attempt), so the number cannot be the revival's own
95 /// `attempt + 1` any more. The revival is fenced on the attempt it read119 /// `attempt + 1` any more. The revival is fenced on the attempt it read
96-/// instead, so a rival that revived first loses this claim (the `CREATE`120+/// instead, so a rival that revived first loses this claim (the insert below
97-/// below then finds the row and aborts the whole transaction) rather than121+/// then finds the row and answers `Duplicate`) rather than billing its
98-/// billing its attempt at this call's id.122+/// attempt at this call's id.
99 ///123 ///
100-/// The charge is created only if it is not already there — a duplicate124+/// The charge is created only if it is not already there — an attempt
101-/// `CREATE` would abort the transaction and cost the seat, and an attempt
102 /// billed twice is the one thing money code may never do.125 /// billed twice is the one thing money code may never do.
103 pub(crate) async fn claim_and_place(126 pub(crate) async fn claim_and_place(
104 db: &Database,127 db: &Database,
105- seats: &RecordId,128+ menu: &MenuId,
106 cap: i64,129 cap: i64,
107 seen: i64,130 seen: i64,
108 row: &MealBooking,131 row: &MealBooking,
109 price: Option<LedgerAmount>,132 price: Option<LedgerAmount>,
110 charge: Option<&MealLedger>,133 charge: Option<&MealLedger>,
111 ) -> Result<Claimed<MealBooking>, AppError> {134 ) -> Result<Claimed<MealBooking>, AppError> {
112- // Empty when the menu is free: a seat that costs nothing owes no line.135+ let menu_key = menu.key().to_string();
113- let bill = match charge {136+ let student = row.student;
114- Some(_) => {137+ let attempt = row.attempt;
115- "IF array::len((SELECT VALUE id FROM $charge)) = 0 \138+ tx_with_retry(db, false, async |tx| {
116- { CREATE $charge CONTENT $line };"139+ // Already held? Same attempt, same price it was taken at — answered
140+ // as `Duplicate`, which the caller replays into the winner's row
141+ // (and its charge) without claiming anything.
142+ let held = sqlx::query!(
143+ "SELECT 1 AS held FROM meal_booking
144+ WHERE menu = $1 AND student = $2 AND status = 'booked'",
145+ menu_key,
146+ student,
147+ )
148+ .fetch_optional(&mut *tx)
149+ .await?;
150+ if held.is_some() {
151+ return Ok(Claimed::Duplicate);
117 }152 }
118- None => "",153+ // The seat: one conditional single-row write on the menu, atomic
119- };154+ // under Postgres — of the racers only `cap` of them per revision
120- // Slots count BEGIN, three LETs, three IFs and — when there is money to155+ // get a non-empty result, and the rest are refused with nothing
121- // take — the charge's IF, so the RETURN is slot 7 or 8.156+ // written.
122- let returned = if charge.is_some() { 8 } else { 7 };157+ let seat = sqlx::query!(
123- // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.158+ "UPDATE menu SET seats_booked = seats_booked + 1
124- let sql = format!(159+ WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3
125- "BEGIN TRANSACTION;160+ RETURNING 1 AS seat",
126- LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked');161+ menu_key,
127- IF array::len($held) > 0 {{ THROW 'held' }};162+ cap,
128- LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \163+ seen,
129- ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \164+ )
130- WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \165+ .fetch_optional(&mut *tx)
131- AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);166+ .await?;
132- IF array::len($seat) = 0 {{ THROW 'no_seat' }};167+ if seat.is_none() {
133- LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \
134- price_minor = $price, cancelled_at = NONE \
135- WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER);
136- IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};
137- {bill}
138- RETURN SELECT * FROM ONLY $id;
139- COMMIT TRANSACTION;"
140- );
141- // Every booking on one menu contends on that menu's single counter row,
142- // which is one HTTP burst of racers on a single parent — the case
143- // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no
144- // backoff just re-synchronized them and 409'd the fourth student.
145- // Admissible: a lost round aborts the whole transaction (nothing
146- // written, no seat, no charge), and the two `CREATE`s that could
147- // legitimately answer "already exists" are read as `Claimed::Duplicate`
148- // below *before* the conflict check, so no decision is ever re-asked.
149- for attempt in 0..CAP_WRITE_TRIES {
150- backoff(attempt).await;
151- let query = db
152- .query(sql.as_str())
153- .bind(("menu", seats.clone()))
154- .bind(("cap", cap))
155- .bind(("seen", seen))
156- .bind(("id", row.id.record()))
157- .bind(("attempt", row.attempt))
158- .bind(("price", price))
159- .bind(("row", row.clone()));
160- let query = match charge {
161- Some(line) => query
162- .bind(("charge", line.get_id().record()))
163- .bind(("line", line.clone())),
164- None => query,
165- };
166- let mut result = match query.await {
167- Ok(result) => result,
168- Err(err) if lost_the_race(&err) => continue,
169- Err(err) => return Err(err.into()),
170- };
171- // An aborted transaction errors *every* slot, most with a generic
172- // "not executed" — only the failing slot says why, so scan them all.
173- let mut errors = result.take_errors();
174- if errors
175- .values()
176- .any(|error| error.to_string().contains("no_seat"))
177- {
178 return Ok(Claimed::Full);168 return Ok(Claimed::Full);
179 }169 }
180- if errors170+ // Revive a cancelled row only while it still stands at the attempt
181- .values()171+ // this call read — the fence that keeps a rival's revival from
182- .any(|error| error.to_string().contains("held") || error.is_already_exists())172+ // being billed at this call's ids.
183- {173+ let revived = sqlx::query_as!(
174+ MealBooking,
175+ "UPDATE meal_booking
176+ SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL
177+ WHERE menu = $1 AND student = $2
178+ AND status = 'cancelled' AND attempt = $3 - 1
179+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
180+ menu_key,
181+ student,
182+ attempt,
183+ price,
184+ )
185+ .fetch_optional(&mut *tx)
186+ .await?;
187+ let placed = match revived {
188+ Some(row) => Some(row),
189+ None => {
190+ // No row (or a rival moved it past this attempt): place a
191+ // fresh one. A rival that landed first answers `Duplicate`
192+ // — nothing here overwrites its row.
193+ let inserted = sqlx::query_as!(
194+ MealBooking,
195+ "INSERT INTO meal_booking
196+ (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at)
197+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
198+ ON CONFLICT (menu, student) DO NOTHING
199+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
200+ menu_key,
201+ student,
202+ row.booked_by,
203+ row.status,
204+ row.attempt,
205+ price,
206+ row.cancelled_at,
207+ row.created_at,
208+ )
209+ .fetch_optional(&mut *tx)
210+ .await?;
211+ inserted
212+ }
213+ };
214+ let Some(placed) = placed else {
184 return Ok(Claimed::Duplicate);215 return Ok(Claimed::Duplicate);
185- }
186- if errors.values().any(lost_the_race) {
187- continue;
188- }
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
190- return Err(error.into());
191- }
192- return match result.take::<Option<MealBooking>>(returned)? {
193- Some(placed) => Ok(Claimed::Made(placed)),
194- None => Err(AppError::Internal("failed to book the meal".into())),
195 };216 };
196- }217+ // The charge rides the same transaction; already there (a replayed
197- Err(AppError::Conflict(218+ // POST of this seat) means fine — nothing is written twice.
198- "the menu kept changing underneath this booking",219+ if let Some(line) = charge {
199- ))220+ sqlx::query!(
221+ "INSERT INTO meal_ledger
222+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
223+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
224+ ON CONFLICT (id) DO NOTHING",
225+ line.id.key(),
226+ line.student,
227+ line.kind,
228+ line.amount_minor,
229+ line.source,
230+ line.method,
231+ line.note,
232+ line.recorded_by,
233+ line.created_at,
234+ )
235+ .execute(&mut *tx)
236+ .await?;
237+ }
238+ Ok(Claimed::Made(placed))
239+ })
240+ .await
200 }241 }
201 242
202 /// Flip the seat to `cancelled` and give it back to the menu's counter **in243 /// Flip the seat to `cancelled` and give it back to the menu's counter **in
203 /// one transaction**, so the two can never disagree: a decrement that ran244 /// one transaction**, so the two can never disagree: a decrement that ran
204 /// without the flip frees a seat still held, and a flip without the245 /// without the flip frees a seat still held, and a flip without the
205-/// decrement locks a seat nothing can ever release. The counter follows the246+/// decrement locks a seat nothing can ever release. The decrement rides the
206-/// flip's own result (`array::len`), so a row already cancelled — by a247+/// flip's own result, so a row already cancelled — by a racing cancel, or
207-/// racing cancel, or by this call retried — decrements nothing.248+/// by this call retried — decrements nothing.
208 ///249 ///
209 /// **The refund rides this transaction too**, and it has to: the flip and a250 /// **The refund rides this transaction too**, and it has to: the flip and a
210 /// reversal appended after it are two writes, and a crash in between leaves251 /// reversal appended after it are two writes, and a crash in between leaves
@@ -230,77 +271,78 @@ pub(crate) async fn claim_and_place(
230 /// reversal id is burnt for good.271 /// reversal id is burnt for good.
231 ///272 ///
232 /// `None` = the row was not this call's own `booked` attempt any more.273 /// `None` = the row was not this call's own `booked` attempt any more.
233-/// Retried while the store reports a write conflict: the menu row is
234-/// contended by every booking on it, and that contention is the cap
235-/// working, not an error.
236 pub async fn release_seat(274 pub async fn release_seat(
237 db: &Database,275 db: &Database,
238 booked: &MealBooking,276 booked: &MealBooking,
239 recorded_by: &UserId,277 recorded_by: &UserId,
240 ) -> Result<Option<MealBooking>, AppError> {278 ) -> Result<Option<MealBooking>, AppError> {
241 let refund = MealLedger::reversal_for(booked, recorded_by);279 let refund = MealLedger::reversal_for(booked, recorded_by);
242- // Guarded three ways: nothing was flipped (a rival cancelled first, and280+ let menu_key = booked.menu.key().to_string();
243- // its own transaction carried the refund), the charge never landed, or281+ let student = booked.student;
244- // this attempt is already refunded — none of which may abort the flip.282+ let attempt = booked.attempt;
245- let reverse = match refund {283+ let cancelled_at = Timestamp::now();
246- Some(_) => {284+ tx_with_retry(db, false, async |tx| {
247- "IF array::len($flipped) > 0 \285+ let flipped = sqlx::query_as!(
248- AND array::len((SELECT VALUE id FROM $charge)) > 0 \286+ MealBooking,
249- AND array::len((SELECT VALUE id FROM $reversal)) = 0 \287+ "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3
250- { CREATE $reversal CONTENT $line };"288+ WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4
251- }289+ RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at",
252- None => "",290+ menu_key,
253- };291+ student,
254- // Slots count BEGIN, the LET, the seat UPDATE and — when there is money292+ cancelled_at,
255- // to give back — the IF.293+ attempt,
256- let returned = if refund.is_some() { 4 } else { 3 };294+ )
257- // Same burst on the same counter as the book side, so the same patience295+ .fetch_optional(&mut *tx)
258- // (see [`claim_and_place`]) — a cancel that gave up left the seat296+ .await?;
259- // held with the charge standing. Admissible: the round aborts having297+ if flipped.is_some() {
260- // written nothing, and a re-send finds the row already `cancelled`, so298+ sqlx::query!(
261- // the flip matches nothing, the counter moves nothing and the guarded299+ "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1",
262- // reversal — keyed to (seat, attempt) — is not written twice.300+ menu_key,
263- for attempt in 0..CAP_WRITE_TRIES {301+ )
264- backoff(attempt).await;302+ .execute(&mut *tx)
265- let attempted = async {303+ .await?;
266- let query = db
267- .query(format!(
268- "BEGIN TRANSACTION;
269- LET $flipped = (UPDATE $id SET status = 'cancelled', \
270- cancelled_at = $now \
271- WHERE status = 'booked' AND attempt = $attempt RETURN AFTER);
272- UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\
273- ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);
274- {reverse}
275- RETURN $flipped;
276- COMMIT TRANSACTION;"
277- ))
278- .bind(("id", booked.id.record()))
279- .bind(("menu", booked.menu.record()))
280- .bind(("attempt", booked.attempt))
281- .bind(("now", Timestamp::now()));
282- let query = match &refund {
283- Some((charge, line)) => query
284- .bind(("charge", charge.record()))
285- .bind(("reversal", line.get_id().record()))
286- .bind(("line", line.clone())),
287- None => query,
288- };
289- let mut result = query.await?.check()?;
290- result.take::<Vec<MealBooking>>(returned)
291 }304 }
292- .await;305+ // Guarded three ways: nothing was flipped (a rival cancelled first,
293- match attempted {306+ // and its own transaction carried the refund), the charge never
294- Ok(rows) => return Ok(rows.into_iter().next()),307+ // landed, or this attempt is already refunded — none of which may
295- Err(err) if lost_the_race(&err) => {}308+ // abort the flip.
296- Err(err) => return Err(err.into()),309+ if let (true, Some((charge, line))) = (flipped.is_some(), &refund) {
310+ let charge_there = sqlx::query!(
311+ "SELECT 1 AS there FROM meal_ledger WHERE id = $1",
312+ charge.key(),
313+ )
314+ .fetch_optional(&mut *tx)
315+ .await?;
316+ let reversal_there = sqlx::query!(
317+ "SELECT 1 AS there FROM meal_ledger WHERE id = $1",
318+ line.id.key(),
319+ )
320+ .fetch_optional(&mut *tx)
321+ .await?;
322+ if charge_there.is_some() && reversal_there.is_none() {
323+ sqlx::query!(
324+ "INSERT INTO meal_ledger
325+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
326+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
327+ ON CONFLICT (id) DO NOTHING",
328+ line.id.key(),
329+ line.student,
330+ line.kind,
331+ line.amount_minor,
332+ line.source,
333+ line.method,
334+ line.note,
335+ line.recorded_by,
336+ line.created_at,
337+ )
338+ .execute(&mut *tx)
339+ .await?;
340+ }
297 }341 }
298- }342+ Ok(flipped)
299- Err(AppError::Conflict(343+ })
300- "the menu kept changing underneath this cancellation",344+ .await
301- ))
302 }345 }
303-
304 #[cfg(test)]346 #[cfg(test)]
305 mod tests {347 mod tests {
306 use super::*;348 use super::*;
src/db/meal_ledger.rsmodified+64 -77
@@ -3,29 +3,14 @@
3 //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal3 //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal
4 //! and credit workflows that sequence these in [`crate::service::meal_ledger`].4 //! and credit workflows that sequence these in [`crate::service::meal_ledger`].
5 5
6-use surrealdb::types::{AlreadyExistsError, SurrealValue};6+use crate::database::Database;
7-
8-use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE};
9-use crate::database::{Database, lost_the_race};
10-use crate::db::menu_dish;
11 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
12-use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind};8+use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId};
13 use crate::domain::menu::MenuId;9 use crate::domain::menu::MenuId;
14 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
15 use crate::error::AppError;11 use crate::error::AppError;
16 12
17-/// Did this `CREATE` fail *only* because the row is already there? Matched on13+/// The only writer: one `INSERT`, no update path anywhere in this module.
18-/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text
19-/// and never on "any database error", because swallowing a real fault in money
20-/// code would be far worse than the 500 it saves.
21-fn is_duplicate_record(error: &surrealdb::Error) -> bool {
22- matches!(
23- error.already_exists_details(),
24- Some(AlreadyExistsError::Record { .. })
25- )
26-}
27-
28-/// The only writer: one `CREATE`, no update path anywhere in this module.
29 ///14 ///
30 /// A line whose id already exists is left exactly as it is — the row wins,15 /// A line whose id already exists is left exactly as it is — the row wins,
31 /// the write is dropped. That is what makes a deterministic id (see16 /// the write is dropped. That is what makes a deterministic id (see
@@ -33,38 +18,52 @@ fn is_duplicate_record(error: &surrealdb::Error) -> bool {
33 /// append is a no-op, never a second line and never an edit of the first.18 /// append is a no-op, never a second line and never an edit of the first.
34 /// The point read is on the id itself, so unlike a scan it cannot miss a19 /// The point read is on the id itself, so unlike a scan it cannot miss a
35 /// row a concurrent writer just made — but it is only a fast path. The20 /// row a concurrent writer just made — but it is only a fast path. The
36-/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves21+/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an
37-/// the row untouched, so the writer that lost the race reads back the22+/// existing id nothing is written, so the writer that lost the race reads
38-/// winner's line instead of failing the request with a 500.23+/// back the winner's line instead of failing the request with a 500.
39-///
40-/// A *write conflict* is the same race decided one layer down — two
41-/// appends of one id arriving together are no longer serialized by a
42-/// process-wide lock, so the store aborts one as retryable instead of
43-/// answering it "already exists". Both are read back the same way, and a
44-/// conflict that turns out to have written nothing is simply tried again;
45-/// no path here can write a second line, since the id is the key.
46 pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> {24 pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> {
47 if let Some(existing) = read(db, &row.id).await? {25 if let Some(existing) = read(db, &row.id).await? {
48 return Ok(existing);26 return Ok(existing);
49 }27 }
50- let id = row.id.clone();28+ let inserted = sqlx::query_as!(
51- for _ in 0..CAS_UPDATE_RETRIES {29+ MealLedger,
52- match db.create(id.record()).content(row.clone()).await {30+ "INSERT INTO meal_ledger
53- Ok(Some(created)) => return Ok(created),31+ (id, student, kind, amount_minor, source, method, note, recorded_by, created_at)
54- Ok(None) => break,32+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
55- Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {33+ ON CONFLICT (id) DO NOTHING
56- if let Some(existing) = read(db, &id).await? {34+ RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at",
57- return Ok(existing);35+ row.id.key(),
58- }36+ row.student,
59- }37+ row.kind,
60- Err(e) => return Err(e.into()),38+ row.amount_minor,
61- }39+ row.source,
40+ row.method,
41+ row.note,
42+ row.recorded_by,
43+ row.created_at,
44+ )
45+ .fetch_optional(db)
46+ .await?;
47+ match inserted {
48+ Some(created) => Ok(created),
49+ // Lost the id to a concurrent append of the same line: the stored
50+ // row is the answer, never a second line.
51+ None => read(db, &row.id)
52+ .await?
53+ .ok_or_else(|| AppError::Internal("failed to write the ledger line".into())),
62 }54 }
63- Err(AppError::Internal("failed to write the ledger line".into()))
64 }55 }
65 56
66 pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> {57 pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> {
67- Ok(db.select(id.record()).await?)58+ let row = sqlx::query_as!(
59+ MealLedger,
60+ "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at
61+ FROM meal_ledger WHERE id = $1",
62+ id.key(),
63+ )
64+ .fetch_optional(db)
65+ .await?;
66+ Ok(row)
68 }67 }
69 68
70 /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`69 /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`
@@ -77,12 +76,11 @@ pub async fn price_snapshot(
77 db: &Database,76 db: &Database,
78 menu: &MenuId,77 menu: &MenuId,
79 ) -> Result<Option<LedgerAmount>, AppError> {78 ) -> Result<Option<LedgerAmount>, AppError> {
80- let total = menu_dish::list_for_menu(db, menu)79+ let row =
81- .await?80+ sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key())
82- .iter()81+ .fetch_one(db)
83- .fold(0i64, |sum, dish| {82+ .await?;
84- sum.saturating_add(dish.get_price_minor().as_minor())83+ let total = row.total;
85- });
86 if total == 0 {84 if total == 0 {
87 return Ok(None);85 return Ok(None);
88 }86 }
@@ -97,10 +95,10 @@ pub async fn list_for_student(
97 offset: i64,95 offset: i64,
98 ) -> Result<(Vec<MealLedger>, i64), AppError> {96 ) -> Result<(Vec<MealLedger>, i64), AppError> {
99 PagedList::new(97 PagedList::new(
100- "meal_ledger WHERE student = $student",98+ "meal_ledger WHERE student = $1",
101 "ORDER BY created_at DESC, id DESC",99 "ORDER BY created_at DESC, id DESC",
102 )100 )
103- .bind("student", student.record())101+ .bind(student.key())
104 .run(limit, offset, db)102 .run(limit, offset, db)
105 .await103 .await
106 }104 }
@@ -118,38 +116,27 @@ pub async fn list_for_student(
118 /// every later `GET /meals/balance/*`.116 /// every later `GET /meals/balance/*`.
119 ///117 ///
120 /// **The signs stay on the kind**, applied by the very118 /// **The signs stay on the kind**, applied by the very
121-/// [`MealLedgerKind::sign`]119+/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign)
122-/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN120+/// the documented formula is spelled in. Summing a signed CASE in SQL would
123-/// -amount …` in SQL would have folded the whole balance in one statement121+/// have folded the whole balance in one statement and forked the one rule
124-/// and forked the one rule that decides what money means into a second122+/// that decides what money means into a second language, where nothing
125-/// language, where nothing would fail the day the two disagreed. Grouping123+/// would fail the day the two disagreed. Grouping instead keeps the
126-/// instead keeps the aggregate ignorant of signs: it counts kinds, and124+/// aggregate ignorant of signs: it counts kinds, and Rust still says what a
127-/// Rust still says what a kind does. A stored running total was the third125+/// kind does. A stored running total was the third option and is a counter
128-/// option and is a counter that can drift — a bug class this repo closes,126+/// that can drift — a bug class this repo closes, not one it opens.
129-/// not one it opens.
130 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {127 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
131- let totals: Vec<KindTotal> = db128+ let totals = sqlx::query!(
132- .query(format!(129+ r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind",
133- "SELECT kind, math::sum(amount_minor) AS total \130+ CAST(sum(amount_minor) AS BIGINT) AS total
134- FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind"131+ FROM meal_ledger WHERE student = $1 GROUP BY kind"#,
135- ))132+ *student,
136- .bind(("student", student.record()))133+ )
137- .await?134+ .fetch_all(db)
138- .check()?135+ .await?;
139- .take(0)?;
140 Ok(totals136 Ok(totals
141 .iter()137 .iter()
142 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))138 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
143 }139 }
144-
145-/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands
146-/// it back — at most three rows, never the lines behind them.
147-#[derive(Debug, SurrealValue)]
148-struct KindTotal {
149- kind: MealLedgerKind,
150- total: i64,
151-}
152-
153 #[cfg(test)]140 #[cfg(test)]
154 mod tests {141 mod tests {
155 use super::*;142 use super::*;
src/db/menu.rsmodified+173 -205
@@ -1,100 +1,33 @@
1 //! The `menu` table: publishing (the slot reference claimed inside the1 //! The `menu` table: publishing (the slot reference claimed inside the
2 //! write's own transaction), row reads and listings, the compare-and-set2 //! write's own transaction), row reads and listings, the compare-and-set
3-//! every cap PATCH writes through, the cascading delete, and3+//! every cap PATCH writes through, and the cascading delete. The kitchen
4-//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every4+//! workflows — the guarded dish-cap insert — live in
5-//! child write (a dish, an attendance mark) uses so nothing can outlive its
6-//! menu. The kitchen workflows — the dish cap under
7-//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in
8 //! [`crate::service::menu`].5 //! [`crate::service::menu`].
9 6
10-use surrealdb::types::{SurrealValue, Value};7+use crate::database::{Database, tx_with_retry, unique_violation};
11-8+use crate::db::page::{PagedList, Param};
12-use crate::constant::{
13- MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD,
14- REF_COUNT_FIELD,
15-};
16-use crate::database::{Database, transaction_with_retry, write_with_retry};
17-use crate::db::cap;
18-use crate::db::page::PagedList;
19 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};9 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};
20 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
21 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
22 use crate::error::AppError;12 use crate::error::AppError;
23 13
24-/// Move the menu's revision **and** run `statement` — a write to something
25-/// hanging off a menu — in one transaction, handing back the row it returned.
26-///
27-/// What a seat on that menu costs, or who is recorded against it, is about to
28-/// change, so any booking that priced itself against the old revision has to
29-/// re-read. The bump cannot be a query of its own: in the gap the menu row
30-/// carries the *new* revision with the *old* price, and a booking reading there
31-/// passes the very CAS that exists to refuse it — a seat billed a price the
32-/// menu had already left, or admitted past a capacity that had already shrunk.
33-///
34-/// The bump is also what makes the menu's **existence** part of the write
35-/// ([`crate::db::menu_dish::create`] leans on
36-/// the same thing): the `UPDATE` matches nothing once the menu row is deleted,
37-/// and a delete racing this one touches the very key this transaction writes,
38-/// so the two cannot both commit. Reading the menu instead — even as the write
39-/// statement's own target — does not survive that race: the read sees a row the
40-/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot
41-/// predating this insert, so both commit and the child outlives its menu
42-/// (measured 378 of 3600 raced rounds before this shape was shared).
43-///
44-/// Deliberately on every such write, not only the ones that move
45-/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies
46-/// to every write cannot be forgotten by the next one added.
47-///
48-/// Admissible for [`transaction_with_retry`] as long as `statement` is: an
49-/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never
50-/// answer "already exists", and neither can an `UPSERT` whose id is bijective
51-/// with every unique tuple its table indexes — a lost round wrote nothing, so
52-/// re-sending it is the recovery.
53-pub(crate) async fn bump_menu_and_write<T: SurrealValue>(
54- menu: &MenuId,
55- statement: &str,
56- mut bindings: Vec<(String, Value)>,
57- db: &Database,
58-) -> Result<Option<T>, AppError> {
59- bindings.push(("menu".into(), menu.record().into_value()));
60- let (mut result, mut errors) = transaction_with_retry(
61- db,
62- &format!(
63- "BEGIN TRANSACTION;
64- LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \
65- ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);
66- IF array::len($bumped) = 0 {{ THROW 'no_menu' }};
67- LET $row = ({statement});
68- RETURN $row;
69- COMMIT TRANSACTION;"
70- ),
71- &bindings,
72- &["no_menu"],
73- )
74- .await?;
75- // An aborted transaction errors *every* slot, most with a generic "not
76- // executed" — only the THROW's own slot names the reason.
77- if errors
78- .values()
79- .any(|error| error.to_string().contains("no_menu"))
80- {
81- return Err(AppError::NotFound);
82- }
83- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
84- return Err(error.into());
85- }
86- // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
87- Ok(result.take::<Vec<T>>(4)?.into_iter().next())
88-}
89-
90 /// Publish a menu. Refused (409) when the day+slot already carries one.14 /// Publish a menu. Refused (409) when the day+slot already carries one.
91 ///15 ///
92-/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the16+/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so
93-/// refusal is decided by the store rather than by a check a concurrent17+/// the refusal is decided by the store rather than by a check a concurrent
94-/// publish can outrun: two publishes of the same meal write one id, and the loser's18+/// publish can outrun: two publishes of the same meal write one row, and
95-/// "already exists" becomes the same 409. The pre-check stays for the19+/// the loser's unique violation on `menu_pkey` becomes the same 409. The
96-/// ordinary case — and for menus published before ids were derived, whose20+/// in-transaction pre-check stays for the ordinary case.
97-/// ULID key no new publish can collide with.21+///
22+/// The menu takes a reference on its slot, which is what stops the slot
23+/// being dropped from the settings while this menu (whose slot is only
24+/// snapshotted text) still points at it. Claimed *inside* the write's own
25+/// transaction, with the duplicate gate ahead of the retired check so
26+/// "you already published this" still outranks "the slot is retired" (the
27+/// [`crate::db::cap`] reference-claim recipe): the counted row and the
28+/// count commit together or not at all, so no crash window is small enough
29+/// to leave a slot counted by a menu that does not exist — a slot nobody
30+/// could ever retire.
98 pub async fn create(31 pub async fn create(
99 db: &Database,32 db: &Database,
100 date: MenuDate,33 date: MenuDate,
@@ -102,39 +35,80 @@ pub async fn create(
102 capacity: Option<i64>,35 capacity: Option<i64>,
103 created_by: &UserId,36 created_by: &UserId,
104 ) -> Result<Menu, AppError> {37 ) -> Result<Menu, AppError> {
105- let taken = AppError::Conflict("a menu is already published for that date and slot");38+ let id_key = MenuId::for_slot(&date, &slot).key().to_string();
106- if find(db, &date, &slot).await?.is_some() {
107- return Err(taken);
108- }
109- // The menu takes a reference on its slot, which is what stops the slot
110- // being dropped from the settings while this menu (whose slot is only
111- // snapshotted text) still points at it. Claimed *inside* the write's own
112- // transaction: a claim of its own could land and the row then fail to,
113- // leaving the slot counted by a menu that does not exist — a slot
114- // nobody can ever retire, and no crash window is small enough for that.
115 let counter = slot_ref(slot.as_str());39 let counter = slot_ref(slot.as_str());
116- let menu = Menu {40+ let date_s = date.as_str().to_string();
117- id: MenuId::for_slot(&date, &slot),41+ let slot_s = slot.as_str().to_string();
118- date,42+ let created_by = *created_by;
119- slot,43+ let created_at = Timestamp::now();
120- capacity,44+ tx_with_retry(db, false, async |tx| {
121- version: Some(0),45+ // Duplicate gate ahead of the retired check: "already published"
122- created_by: created_by.clone(),46+ // outranks "slot retired", on the very path a rival publish races.
123- created_at: Timestamp::now(),47+ let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,)
124- };48+ .fetch_optional(&mut *tx)
125- let id = menu.id.record();49+ .await?;
126- match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? {50+ if exists.is_some() {
127- cap::ClaimedRef::Made(created) => Ok(created),51+ return Err(AppError::Conflict(
128- cap::ClaimedRef::Duplicate => Err(taken),52+ "a menu is already published for that date and slot",
129- cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!(53+ ));
130- "the '{}' meal slot has been removed from the school's settings",54+ }
131- menu.slot.as_str()55+ let inserted = match sqlx::query_as!(
132- ))),56+ Menu,
133- }57+ "WITH ref AS (
58+ INSERT INTO slot_ref (name, count) VALUES ($2, 1)
59+ ON CONFLICT (name) DO UPDATE SET count = slot_ref.count + 1
60+ WHERE slot_ref.retired = false
61+ RETURNING 1 AS ref
62+ )
63+ INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at)
64+ SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref)
65+ RETURNING id, date, slot, capacity, version, created_by, created_at",
66+ id_key,
67+ counter,
68+ date_s,
69+ slot_s,
70+ capacity,
71+ Some(0i64),
72+ created_by,
73+ created_at,
74+ )
75+ .fetch_optional(&mut *tx)
76+ .await
77+ {
78+ Ok(row) => row,
79+ Err(err) => {
80+ // A rival published the same meal after the pre-check: its
81+ // row owns the key, and its publish is the answer.
82+ if unique_violation(&err) == Some("menu_pkey") {
83+ return Err(AppError::Conflict(
84+ "a menu is already published for that date and slot",
85+ ));
86+ }
87+ return Err(err.into());
88+ }
89+ };
90+ match inserted {
91+ Some(menu) => Ok(menu),
92+ // The slot's ref row is retired — nothing was written.
93+ None => Err(AppError::ConflictOwned(format!(
94+ "the '{}' meal slot has been removed from the school's settings",
95+ slot_s,
96+ ))),
97+ }
98+ })
99+ .await
134 }100 }
135 101
136 pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> {102 pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> {
137- Ok(db.select(id.record()).await?)103+ let row = sqlx::query_as!(
104+ Menu,
105+ "SELECT id, date, slot, capacity, version, created_by, created_at
106+ FROM menu WHERE id = $1",
107+ id.key(),
108+ )
109+ .fetch_optional(db)
110+ .await?;
111+ Ok(row)
138 }112 }
139 113
140 /// The menu for one day and slot, if any — the uniqueness check.114 /// The menu for one day and slot, if any — the uniqueness check.
@@ -143,18 +117,21 @@ pub async fn find(
143 date: &MenuDate,117 date: &MenuDate,
144 slot: &MenuSlot,118 slot: &MenuSlot,
145 ) -> Result<Option<Menu>, AppError> {119 ) -> Result<Option<Menu>, AppError> {
146- let mut result = db120+ let row = sqlx::query_as!(
147- .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1")121+ Menu,
148- .bind(("date", date.as_str().to_string()))122+ "SELECT id, date, slot, capacity, version, created_by, created_at
149- .bind(("slot", slot.as_str().to_string()))123+ FROM menu WHERE date = $1 AND slot = $2 LIMIT 1",
150- .await?124+ date.as_str(),
151- .check()?;125+ slot.as_str(),
152- Ok(result.take::<Vec<Menu>>(0)?.into_iter().next())126+ )
127+ .fetch_optional(db)
128+ .await?;
129+ Ok(row)
153 }130 }
154 131
155 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;132 /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
156-/// either may be omitted. The comparison is lexical, which is chronological133+/// either may be omitted (`NULL` bound). The comparison is lexical, which
157-/// for this format.134+/// is chronological for this format.
158 pub async fn list(135 pub async fn list(
159 db: &Database,136 db: &Database,
160 from: Option<&MenuDate>,137 from: Option<&MenuDate>,
@@ -163,25 +140,26 @@ pub async fn list(
163 offset: i64,140 offset: i64,
164 ) -> Result<(Vec<Menu>, i64), AppError> {141 ) -> Result<(Vec<Menu>, i64), AppError> {
165 PagedList::new(142 PagedList::new(
166- "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)",143+ "menu WHERE ($1::text IS NULL OR date >= $1::text) \
144+ AND ($2::text IS NULL OR date <= $2::text)",
167 "ORDER BY date DESC, slot ASC, id DESC",145 "ORDER BY date DESC, slot ASC, id DESC",
168 )146 )
169- .bind("from", from.map(|date| date.as_str().to_string()))147+ .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
170- .bind("to", to.map(|date| date.as_str().to_string()))148+ .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
171 .run(limit, offset, db)149 .run(limit, offset, db)
172 .await150 .await
173 }151 }
174 152
175-/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,153+/// Only `capacity` is writable: `date` and `slot` are fixed at publish,
176 /// because moving a published menu to another day is a different menu.154 /// because moving a published menu to another day is a different menu.
177 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.155 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
178 ///156 ///
179 /// The revision moves **in the same statement** as the cap, indivisibly: a157 /// The revision moves **in the same statement** as the cap, indivisibly: a
180-/// booking claims its seat against the revision158+/// booking claims its seat against the revision it read the cap at, so a
181-/// it read the cap at, so a shrink that bumped in a query of its own left a159+/// shrink that bumped in a query of its own left a window where the row
182-/// window where the row carried the *new* revision and the *old* cap — and160+/// carried the *new* revision and the *old* cap — and a booking arriving
183-/// a booking arriving there passes a CAS meant to refuse it, over-admitting161+/// there passes a CAS meant to refuse it, over-admitting by exactly the
184-/// by exactly the seats in flight.162+/// seats in flight.
185 pub async fn update(163 pub async fn update(
186 db: &Database,164 db: &Database,
187 menu: Menu,165 menu: Menu,
@@ -192,99 +170,89 @@ pub async fn update(
192 // booking's price or cap has moved, so none owes a re-read.170 // booking's price or cap has moved, so none owes a re-read.
193 return read(db, &menu.id).await?.ok_or(AppError::NotFound);171 return read(db, &menu.id).await?.ok_or(AppError::NotFound);
194 };172 };
195- let sql = format!(173+ let row = sqlx::query_as!(
196- "UPDATE $id SET capacity = $capacity, \174+ Menu,
197- {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER"175+ "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1
198- );176+ WHERE id = $1
199- // One counter write in flight at a time, like every other one.177+ RETURNING id, date, slot, capacity, version, created_by, created_at",
200- let _guard = cap::counter_lock().await;178+ menu.id.key(),
201- write_with_retry::<Menu>(179+ capacity,
202- db,
203- &sql,
204- &[
205- ("id".into(), menu.id.record().into_value()),
206- ("capacity".into(), capacity.into_value()),
207- ],
208 )180 )
209- .await?181+ .fetch_optional(db)
210- .into_iter()182+ .await?;
211- .next()183+ row.ok_or(AppError::NotFound)
212- .ok_or(AppError::NotFound)
213 }184 }
214 185
215-/// Delete the menu and the dishes on it — a dish has no meaning without186+/// Delete the menu and the dishes and marks on it — a dish or a mark has
216-/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.187+/// no meaning without its menu, and the menu key cannot be re-homed.
217 ///188 ///
218 /// Refused (409) while a seat is still held, and the *row itself* decides189 /// Refused (409) while a seat is still held, and the *row itself* decides
219 /// that: the delete carries the seat counter in its `WHERE`, so a booking190 /// that: the delete carries the seat counter in its `WHERE`, so a booking
220-/// landing at that instant either takes its seat before191+/// landing at that instant either takes its seat before the delete (which
221-/// the delete (which then finds a non-zero counter and refuses) or after it192+/// then finds a non-zero counter and refuses) or after it (and finds no
222-/// (and finds no menu). A read-then-delete pair had a window where both193+/// menu). A read-then-delete pair had a window where both happened — a
223-/// happened — a paid seat on a menu that no longer exists.194+/// paid seat on a menu that no longer exists.
224 ///195 ///
225 /// The slot gets its reference back in that same transaction — a slot no196 /// The slot gets its reference back in that same transaction — a slot no
226-/// menu is published for any more may leave the settings again, and the197+/// menu is published for any more may leave the settings again. Released
227-/// `FOR` runs only over a row the guard actually took. Released afterwards198+/// afterwards in a statement of its own, a crash between the two left the
228-/// in a query of its own, a crash between the two left the slot counted by199+/// slot counted by a menu that no longer exists: a slot nobody can retire.
229-/// a menu that no longer exists: a slot nobody can retire.
230 ///200 ///
231-/// The marks go in that same `FOR`, for a sharper reason than tidiness:201+/// The marks go in that same sweep, for a sharper reason than tidiness:
232 /// [`MenuId::for_slot`] is deterministic, so republishing the same day and202 /// [`MenuId::for_slot`] is deterministic, so republishing the same day and
233-/// slot mints the *same* record id. A mark left behind would come back as a203+/// slot mints the *same* row key. A mark left behind would come back as a
234 /// mark on the new menu — the kitchen reading "served" for a student who204 /// mark on the new menu — the kitchen reading "served" for a student who
235 /// never came — and until then the student's own report cites a menu that205 /// never came — and until then the student's own report cites a menu that
236 /// is gone. Attendance carries no money and no counter, so it is safe to206 /// is gone. Attendance carries no money and no counter, so it is safe to
237-/// drop; cancelled *bookings* deliberately stay, because their `attempt`207+/// drop; cancelled *bookings* deliberately stay (no foreign key ties them
238-/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut208+/// to the menu), because their `attempt` counter is what keeps the
209+/// ledger's `(booking, attempt)` keys unique across the republish. Cut
239 /// those and a re-book on a republished menu would reuse a charge id the210 /// those and a re-book on a republished menu would reuse a charge id the
240 /// ledger already holds, and the append (idempotent by design) would bill211 /// ledger already holds, and the append (idempotent by design) would bill
241 /// the seat nothing.212 /// the seat nothing.
242 ///213 ///
243-/// The dishes ride in that `FOR` too, and for the same reason as the marks:214+/// The dishes ride in the same sweep: run after the commit, a crash
244-/// run after the transaction committed, a crash between the two orphaned215+/// between the two would orphan them on the row key a republish mints
245-/// them on a record id republishing the day and slot mints again — a new216+/// again — a new menu serving (and pricing) the old one's food.
246-/// menu serving (and pricing) the old one's food.
247 pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {217 pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
248- let sql = format!(218+ let key = menu.id.key().to_string();
249- "BEGIN TRANSACTION;219+ let counter = slot_ref(menu.slot.as_str());
250- LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);220+ let deleted = tx_with_retry(db, true, async |tx| {
251- FOR $row IN ($gone ?? []) {{221+ let deleted = sqlx::query_as!(
252- UPSERT $counter SET {REF_COUNT_FIELD} = \222+ Menu,
253- math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);223+ "DELETE FROM menu WHERE id = $1 AND seats_booked = 0
254- DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id;224+ RETURNING id, date, slot, capacity, version, created_by, created_at",
255- DELETE {MENU_DISH_TABLE} WHERE menu = $id;225+ key,
256- }};226+ )
257- RETURN $gone;227+ .fetch_optional(&mut *tx)
258- COMMIT TRANSACTION;"228+ .await?;
259- );229+ let Some(row) = deleted else {
260- // `slot` is a `READONLY` column, so this counter is the one the deleted230+ return Ok(None);
261- // row carries. Nothing here can answer "already exists" — the `UPSERT`231+ };
262- // is keyed by a slot name on a table with no `UNIQUE` index, so it232+ sqlx::query!(
263- // resolves onto the row it names ([`transaction_with_retry`]).233+ "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1",
264- let (mut result, mut errors) = transaction_with_retry(234+ counter,
265- db,235+ )
266- &sql,236+ .execute(&mut *tx)
267- &[237+ .await?;
268- ("id".into(), menu.id.record().into_value()),238+ sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
269- ("counter".into(), slot_ref(menu.slot.as_str()).into_value()),239+ .execute(&mut *tx)
270- ],240+ .await?;
271- &[],241+ sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
272- )242+ .execute(&mut *tx)
243+ .await?;
244+ Ok(Some(row))
245+ })
273 .await?;246 .await?;
274- if let Some(error) = errors.drain().map(|(_, error)| error).next() {247+ match deleted {
275- return Err(error.into());248+ Some(menu) => Ok(menu),
276- }
277- // BEGIN, the LET and the FOR take a slot each.
278- let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else {
279 // Nothing back: either seats are held, or the menu is already gone.249 // Nothing back: either seats are held, or the menu is already gone.
280- return Err(match read(db, &menu.id).await? {250+ None => match read(db, &menu.id).await? {
281- Some(_) => AppError::Conflict("the menu still has live bookings"),251+ Some(_) => Err(AppError::Conflict("the menu still has live bookings")),
282- None => AppError::NotFound,252+ None => Err(AppError::NotFound),
283- });253+ },
284- };254+ }
285- Ok(deleted)
286 }255 }
287-
288 #[cfg(test)]256 #[cfg(test)]
289 mod tests {257 mod tests {
290 use super::*;258 use super::*;
src/db/menu_dish.rsmodified+147 -124
@@ -1,14 +1,9 @@
1-//! The `menu_dish` table: the dishes on a menu — the insert and the field1+//! The `menu_dish` table: the dishes on a menu — the guarded insert (the
2-//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the2+//! dish cap, enforced by the menu row's own lock), the field PATCH riding
3-//! reads and listings, and the delete. The dish-cap gate and the3+//! the menu's revision bump, the reads and listings, and the delete. The
4-//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in4+//! kitchen workflows live in [`crate::service::menu`].
5-//! [`crate::service::menu`].
6 5
7-use surrealdb::types::{SurrealValue, Value};6+use crate::database::{Database, tx_with_retry};
8-
9-use crate::constant::MENU_VERSION_FIELD;
10-use crate::database::{Database, transaction_with_retry};
11-use crate::db::menu::bump_menu_and_write;
12 use crate::domain::menu::MenuId;7 use crate::domain::menu::MenuId;
13 use crate::domain::menu_dish::{8 use crate::domain::menu_dish::{
14 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,9 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
@@ -16,7 +11,15 @@ use crate::domain::menu_dish::{
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::error::AppError;12 use crate::error::AppError;
18 13
19-/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`].14+/// Add a dish. The dish cap is one guarded decision, not a count a caller
15+/// took a moment earlier: the menu row is locked `FOR NO KEY UPDATE` in
16+/// this write's own transaction and the `INSERT` runs with a
17+/// `count(*) < $cap` guard — a writer that queued on the lock behind a
18+/// concurrent one re-counts after it and is refused (`409`) instead of
19+/// overfilling. The revision bump rides the same transaction, and the
20+/// lock's `SELECT` is what makes the menu's **existence** part of the
21+/// write: it matches nothing once the menu row is deleted, so `NotFound`
22+/// means the dish was not written.
20 pub async fn create(23 pub async fn create(
21 db: &Database,24 db: &Database,
22 menu: &MenuId,25 menu: &MenuId,
@@ -24,67 +27,67 @@ pub async fn create(
24 description: Option<DishDescription>,27 description: Option<DishDescription>,
25 price_minor: DishPrice,28 price_minor: DishPrice,
26 tags: DishTags,29 tags: DishTags,
30+ cap: i64,
27 ) -> Result<MenuDish, AppError> {31 ) -> Result<MenuDish, AppError> {
28- let dish = MenuDish {32+ let menu_key = menu.key().to_string();
29- id: MenuDishId::generate(),33+ let id = MenuDishId::generate();
30- menu: menu.clone(),34+ let created_at = Timestamp::now();
31- name,35+ tx_with_retry(db, false, async |tx| {
32- description,36+ // The lock first: every later statement in this transaction then
33- price_minor,37+ // sees the committed state of whoever queued ahead of it.
34- tags,38+ let locked = sqlx::query!(
35- created_at: Timestamp::now(),39+ "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE",
36- };40+ menu_key,
37- // The revision bump and the insert are one transaction, and the bump is41+ )
38- // what makes the menu's existence part of it: the `UPDATE` matches42+ .fetch_optional(&mut *tx)
39- // nothing once the menu row is deleted, and a delete racing this one43+ .await?;
40- // touches the very key this transaction writes, so the two cannot both44+ if locked.is_none() {
41- // commit. Without that, a dish landing just after `DELETE /menus/{id}`45+ return Err(AppError::NotFound);
42- // removed the row but before its cascade ran outlived its menu.46+ }
43- // Every other dish write bumps the same version key, so a lost round is47+ sqlx::query!(
44- // ordinary here; it is re-sent rather than reported. Re-sending is sound48+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1",
45- // even with the `CREATE` in the batch — the abort wrote nothing, the id49+ menu_key,
46- // is a ULID freshly generated above and never seen by a rival, and50+ )
47- // `menu_dish` carries no UNIQUE index — so the retry cannot answer51+ .execute(&mut *tx)
48- // "already exists" (see [`transaction_with_retry`]).52+ .await?;
49- let (mut result, mut errors) = transaction_with_retry(53+ let placed = sqlx::query_as!(
50- db,54+ MenuDish,
51- &format!(55+ "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)
52- "BEGIN TRANSACTION;56+ SELECT $1, $2, $3, $4, $5, $6, $7
53- LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \57+ WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8
54- ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);58+ RETURNING id, menu, name, description, price_minor, tags, created_at",
55- IF array::len($bumped) = 0 {{ THROW 'no_menu' }};59+ id,
56- CREATE $id CONTENT $dish;60+ menu_key,
57- COMMIT TRANSACTION;"61+ name,
58- ),62+ description,
59- &[63+ price_minor,
60- ("menu".into(), menu.record().into_value()),64+ tags,
61- ("id".into(), dish.id.record().into_value()),65+ created_at,
62- ("dish".into(), dish.into_value()),66+ cap,
63- ],67+ )
64- &["no_menu"],68+ .fetch_optional(&mut *tx)
65- )69+ .await?;
66- .await?;70+ match placed {
67- // An aborted transaction errors *every* slot, most with a generic "not71+ Some(dish) => Ok(dish),
68- // executed" — only the THROW's own slot names the reason.72+ // The menu exists (locked above), so an empty result is the cap.
69- if errors73+ None => Err(AppError::Conflict(
70- .values()74+ "the menu already carries the maximum number of dishes",
71- .any(|error| error.to_string().contains("no_menu"))75+ )),
72- {76+ }
73- return Err(AppError::NotFound);77+ })
74- }78+ .await
75- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
76- return Err(error.into());
77- }
78- // Slots count BEGIN, the LET and the IF: the CREATE is slot 3.
79- result
80- .take::<Vec<MenuDish>>(3)?
81- .into_iter()
82- .next()
83- .ok_or_else(|| AppError::Internal("failed to add the dish".into()))
84 }79 }
85 80
86 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {81 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {
87- Ok(db.select(id.record()).await?)82+ let row = sqlx::query_as!(
83+ MenuDish,
84+ "SELECT id, menu, name, description, price_minor, tags, created_at
85+ FROM menu_dish WHERE id = $1",
86+ id.key(),
87+ )
88+ .fetch_optional(db)
89+ .await?;
90+ Ok(row)
88 }91 }
89 92
90 /// Every dish on one menu, in the order they were added.93 /// Every dish on one menu, in the order they were added.
@@ -98,31 +101,28 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result<Vec<MenuD
98 if menus.is_empty() {101 if menus.is_empty() {
99 return Ok(Vec::new());102 return Ok(Vec::new());
100 }103 }
101- let mut result = db104+ let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();
102- .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC")105+ let rows = sqlx::query_as!(
103- .bind((106+ MenuDish,
104- "menus",107+ "SELECT id, menu, name, description, price_minor, tags, created_at
105- menus.iter().map(MenuId::record).collect::<Vec<_>>(),108+ FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
106- ))109+ keys,
107- .await?110+ )
108- .check()?;111+ .fetch_all(db)
109- Ok(result.take::<Vec<MenuDish>>(0)?)112+ .await?;
110-}113+ Ok(rows)
111-
112-/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate.
113-pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result<usize, AppError> {
114- Ok(list_for_menu(db, menu).await?.len())
115 }114 }
116 115
117 /// Write only the fields the PATCH carried. `description` is nullable, so116 /// Write only the fields the PATCH carried. `description` is nullable, so
118 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.117 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
118+/// Each field is spelled with a "was it on the request?" flag and its
119+/// nullable value, so an omitted field is never written and a concurrent
120+/// PATCH of another one is not reverted.
119 ///121 ///
120-/// The `SET` is built here rather than by122+/// The revision bump lands in the same transaction — "every dish write
121-/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the123+/// bumps" is the rule a caller can rely on without knowing which fields
122-/// revision bump lands on *another* row and has to share this write's124+/// were on the wire. A PATCH that carried nothing still bumps and reads
123-/// transaction; the field-by-field scoping — an omitted field is never125+/// the row back.
124-/// written, so a concurrent PATCH of another one is not reverted — is the
125-/// same rule, spelled out.
126 pub async fn update(126 pub async fn update(
127 db: &Database,127 db: &Database,
128 dish: MenuDish,128 dish: MenuDish,
@@ -131,45 +131,68 @@ pub async fn update(
131 price_minor: Option<DishPrice>,131 price_minor: Option<DishPrice>,
132 tags: Option<DishTags>,132 tags: Option<DishTags>,
133 ) -> Result<MenuDish, AppError> {133 ) -> Result<MenuDish, AppError> {
134- let mut sets: Vec<&str> = Vec::new();134+ let dish_key = dish.id.key();
135- let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())];135+ let menu_key = dish.menu.key().to_string();
136- let mut set = |field: &'static str, value: Option<Value>| {136+ tx_with_retry(db, false, async |tx| {
137- if let Some(value) = value {137+ let bumped = sqlx::query!(
138- sets.push(field);138+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
139- bindings.push((field.into(), value));139+ RETURNING 1 AS bumped",
140+ menu_key,
141+ )
142+ .fetch_optional(&mut *tx)
143+ .await?;
144+ if bumped.is_none() {
145+ return Err(AppError::NotFound);
140 }146 }
141- };147+ let row = sqlx::query_as!(
142- set("name", name.map(SurrealValue::into_value));148+ MenuDish,
143- set("description", description.map(SurrealValue::into_value));149+ "UPDATE menu_dish SET
144- set("price_minor", price_minor.map(SurrealValue::into_value));150+ name = COALESCE($2, name),
145- set("tags", tags.map(SurrealValue::into_value));151+ description = CASE WHEN $3 THEN $4 ELSE description END,
146- // A PATCH that carried nothing writes nothing and reads the row back,152+ price_minor = COALESCE($5, price_minor),
147- // exactly as `FieldUpdate` answers one — but it still moves the153+ tags = COALESCE($6, tags)
148- // revision, because "every dish write bumps" is the rule a caller can154+ WHERE id = $1
149- // rely on without knowing which fields were on the wire.155+ RETURNING id, menu, name, description, price_minor, tags, created_at",
150- let statement = if sets.is_empty() {156+ dish_key,
151- "SELECT * FROM $id".to_string()157+ name.map(|n| n.as_str().to_string()),
152- } else {158+ description.is_some(),
153- format!(159+ description
154- "UPDATE $id SET {} RETURN AFTER",160+ .clone()
155- sets.iter()161+ .flatten()
156- .map(|field| format!("{field} = ${field}"))162+ .map(|d| d.as_str().to_string()),
157- .collect::<Vec<_>>()163+ price_minor.map(DishPrice::as_minor),
158- .join(", ")164+ tags.map(|t| t.as_slice().to_vec()),
159 )165 )
160- };166+ .fetch_optional(&mut *tx)
161- bump_menu_and_write(&dish.menu, &statement, bindings, db)167+ .await?;
162- .await?168+ row.ok_or(AppError::NotFound)
163- .ok_or(AppError::NotFound)169+ })
170+ .await
164 }171 }
165 172
166 pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {173 pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
167- bump_menu_and_write(174+ let dish_key = dish.id.key();
168- &dish.menu,175+ let menu_key = dish.menu.key().to_string();
169- "DELETE $id RETURN BEFORE",176+ tx_with_retry(db, false, async |tx| {
170- vec![("id".into(), dish.id.record().into_value())],177+ let bumped = sqlx::query!(
171- db,178+ "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
172- )179+ RETURNING 1 AS bumped",
173- .await?180+ menu_key,
174- .ok_or(AppError::NotFound)181+ )
182+ .fetch_optional(&mut *tx)
183+ .await?;
184+ if bumped.is_none() {
185+ return Err(AppError::NotFound);
186+ }
187+ let row = sqlx::query_as!(
188+ MenuDish,
189+ "DELETE FROM menu_dish WHERE id = $1
190+ RETURNING id, menu, name, description, price_minor, tags, created_at",
191+ dish_key,
192+ )
193+ .fetch_optional(&mut *tx)
194+ .await?;
195+ row.ok_or(AppError::NotFound)
196+ })
197+ .await
175 }198 }
src/domain/menu.rsmodified+1 -1
@@ -11,7 +11,7 @@
11 //! never rewrite a menu already published under it.11 //! never rewrite a menu already published under it.
12 //!12 //!
13 //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the13 //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the
14-//! dish-cap lock) in [`crate::service::menu`].14+//! dish-cap gate) in [`crate::service::menu`].
15 15
16 use sqlx::Type;16 use sqlx::Type;
17 17
src/domain/menu_dish.rsmodified+2 -2
@@ -5,8 +5,8 @@
5 //! at any layer. `tags` are validated against the school's `dietary_tags`5 //! at any layer. `tags` are validated against the school's `dietary_tags`
6 //! list, the same contract a menu's `slot` has with `meal_slots`.6 //! list, the same contract a menu's `slot` has with `meal_slots`.
7 //!7 //!
8-//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the8+//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in
9-//! write lock in [`crate::service::menu`].9+//! [`crate::service::menu`].
10 10
11 use sqlx::Type;11 use sqlx::Type;
12 use uuid::Uuid;12 use uuid::Uuid;
src/service/meal_attendance.rsmodified+3 -4
@@ -1,9 +1,8 @@
1 //! The attendance-mark workflows: recording who ate off a menu and the two1 //! The attendance-mark workflows: recording who ate off a menu and the two
2 //! listings the kitchen and the student report read. The mark itself is a2 //! listings the kitchen and the student report read. The mark itself is a
3-//! single atomic UPSERT that rides the menu's revision bump3+//! single atomic upsert that rides the menu's revision bump inside its own
4-//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in4+//! transaction — the queries live in [`crate::db::meal_attendance`], the row
5-//! [`crate::db::meal_attendance`], the row shape in5+//! shape in [`crate::domain::meal_attendance`].
6-//! [`crate::domain::meal_attendance`].
7 6
8 use crate::database::Database;7 use crate::database::Database;
9 use crate::db::meal_attendance;8 use crate::db::meal_attendance;
src/service/meal_booking.rsmodified+5 -5
@@ -9,9 +9,10 @@
9 //!9 //!
10 //! **No process-wide lock guards this domain**, and deliberately: every10 //! **No process-wide lock guards this domain**, and deliberately: every
11 //! invariant booking depends on is a *single-record* conditional write (the11 //! invariant booking depends on is a *single-record* conditional write (the
12-//! menu's `seats_booked` counter and the attempt-fenced row flip), which12+//! menu's `seats_booked` counter and the attempt-fenced row flip), which the
13-//! SurrealDB itself serializes — a cross-record lock would add contention13+//! guarded writes themselves serialize — a cross-record lock would add
14-//! without deciding anything the transactions do not already. What the14+//! contention without deciding anything the transactions do not already.
15+//! What the
15 //! service layer owns here is the *sequence*: read the menu, refuse a past16 //! service layer owns here is the *sequence*: read the menu, refuse a past
16 //! day or a closed cutoff before anything is claimed, settle the attempt17 //! day or a closed cutoff before anything is claimed, settle the attempt
17 //! number before the charge id exists, and map the claim's outcomes18 //! number before the charge id exists, and map the claim's outcomes
@@ -62,7 +63,6 @@ pub async fn book(
62 cutoff: &MealCutoff,63 cutoff: &MealCutoff,
63 ) -> Result<MealBooking, AppError> {64 ) -> Result<MealBooking, AppError> {
64 let id = MealBookingId::composite(menu, student);65 let id = MealBookingId::composite(menu, student);
65- let seats = menu.record();
66 for attempt in 0..CAP_WRITE_TRIES {66 for attempt in 0..CAP_WRITE_TRIES {
67 backoff(attempt).await;67 backoff(attempt).await;
68 let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?;68 let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?;
@@ -135,7 +135,7 @@ pub async fn book(
135 let charge = MealLedger::charge_for(&fresh_row, booked_by);135 let charge = MealLedger::charge_for(&fresh_row, booked_by);
136 match meal_booking::claim_and_place(136 match meal_booking::claim_and_place(
137 db,137 db,
138- &seats,138+ menu,
139 fresh.get_capacity().unwrap_or(cap::UNLIMITED),139 fresh.get_capacity().unwrap_or(cap::UNLIMITED),
140 fresh.get_version(),140 fresh.get_version(),
141 &fresh_row,141 &fresh_row,
src/service/meal_ledger.rsmodified+1 -1
@@ -77,7 +77,7 @@ pub async fn reverse_booking(
77 /// resending the identical body after a timeout gets back the line the77 /// resending the identical body after a timeout gets back the line the
78 /// first attempt wrote, not a second credit — nothing on this API can edit78 /// first attempt wrote, not a second credit — nothing on this API can edit
79 /// or delete one, so a doubled credit is corrected only by a compensating79 /// or delete one, so a doubled credit is corrected only by a compensating
80-/// line. Without one the id is a fresh ulid and two identical calls are two80+/// line. Without one the id is a fresh uuid and two identical calls are two
81 /// credits, which is what a desk taking the same amount twice really means.81 /// credits, which is what a desk taking the same amount twice really means.
82 pub async fn credit(82 pub async fn credit(
83 db: &Database,83 db: &Database,
src/service/menu.rsmodified+31 -57
@@ -1,24 +1,16 @@
1 //! The kitchen's workflows: publishing and unpublishing menus, and every1 //! The kitchen's workflows: publishing and unpublishing menus, and every
2-//! dish write — which all hold [`MENU_LOCK`], the lock that makes the2+//! dish write. The queries live in [`crate::db::menu`] and
3-//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB3+//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity
4-//! does not conflict-check) more than a wish. The queries live in4+//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`].
5-//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the
6-//! date/slot/capacity rules in [`crate::domain::menu`] and
7-//! [`crate::domain::menu_dish`].
8 //!5 //!
9-//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the6+//! **No process-wide lock guards this domain.** The dish cap
10-//! dishes, write the dish), which is why it lives here and not in the db7+//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a
11-//! layer: a single-call atomicity lock would be the store's to own, but8+//! process mutex could make safe; it is now one guarded statement — the
12-//! count-then-write is write-skew only this process can serialize.9+//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own
13-//!10+//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that
14-//! **A leaf**: every dish write held under it moves the menu's revision11+//! lock, so two racing writers serialize on the row the database owns.
15-//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]),12+//! Every dish write moves the menu's revision in that same transaction, and
16-//! so no path under this lock reaches `cap`'s counter lock any more. Should13+//! a booking claims its seat at the revision it priced itself against.
17-//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing
18-//! may take this lock while holding a counter lock: that is the invariant a
19-//! new caller must keep, and it is what would keep the pair deadlock-free.
20-
21-use tokio::sync::Mutex;
22 14
23 use crate::constant::MAX_DISHES_PER_MENU;15 use crate::constant::MAX_DISHES_PER_MENU;
24 use crate::database::Database;16 use crate::database::Database;
@@ -30,20 +22,6 @@ use crate::domain::menu_dish::{
30 use crate::domain::user::UserId;22 use crate::domain::user::UserId;
31 use crate::error::AppError;23 use crate::error::AppError;
32 24
33-/// Serializes what is left that counts rows against one menu: the dish cap
34-/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not
35-/// conflict-check). Publishing no longer needs it — the day+slot *is* the
36-/// record id — and neither does a booking, a menu delete, or the settings
37-/// slot-removal guard: those went to conditional single-record writes
38-/// ([`crate::db::cap`]), which the store decides as this lock cannot.
39-//
40-// corner-cut: the dish cap therefore rests on this lock alone — a dish write
41-// added without taking it reopens the count-then-write hole silently. Closing
42-// it properly is another `cap` counter (`dish_count` on the menu row) plus its
43-// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was
44-// not worth the column here.
45-pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
46-
47 /// Publish a menu for one day and meal slot. The caller has validated the25 /// Publish a menu for one day and meal slot. The caller has validated the
48 /// date (a real calendar day, not already over), the slot (one the school26 /// date (a real calendar day, not already over), the slot (one the school
49 /// serves) and the capacity; the day+slot duplicate refusal is decided by27 /// serves) and the capacity; the day+slot duplicate refusal is decided by
@@ -92,18 +70,15 @@ pub async fn delete(db: &Database, menu_row: Menu) -> Result<Menu, AppError> {
92 70
93 /// Add a dish to a menu, under the dish cap.71 /// Add a dish to a menu, under the dish cap.
94 ///72 ///
95-/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write73+/// The cap is the database's to enforce, not this process's: the write
96-/// is write-skew, so the count and the insert have to be one step. The74+/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a
97-/// *price* no longer needs it — a dish write moves the menu's revision, and75+/// `count(*) < cap` guard, so a writer that queued behind a concurrent one
98-/// a booking claims its seat at the revision it priced itself against.76+/// re-counts after the lock and is refused (`409`) instead of overfilling
99-/// The lock is a leaf again: the revision bump rides the dish write's own77+/// — the count and the insert are one decision, with no window a second
100-/// transaction now, so nothing held under it takes `cap`'s counter lock. It78+/// writer can slip through.
101-/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a
102-/// caller that changes it must keep.
103 ///79 ///
104-/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`80+/// The *price* needs no lock — a dish write moves the menu's revision, and
105-/// running in the gap takes its cascade with it and this dish lands on a menu81+/// a booking claims its seat at the revision it priced itself against.
106-/// that no longer exists.
107 pub async fn add_dish(82 pub async fn add_dish(
108 db: &Database,83 db: &Database,
109 menu_id: &MenuId,84 menu_id: &MenuId,
@@ -112,14 +87,16 @@ pub async fn add_dish(
112 price_minor: DishPrice,87 price_minor: DishPrice,
113 tags: DishTags,88 tags: DishTags,
114 ) -> Result<MenuDish, AppError> {89 ) -> Result<MenuDish, AppError> {
115- let _guard = MENU_LOCK.lock().await;90+ menu_dish::create(
116- let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?;91+ db,
117- if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU {92+ menu_id,
118- return Err(AppError::Conflict(93+ name,
119- "the menu already carries the maximum number of dishes",94+ description,
120- ));95+ price_minor,
121- }96+ tags,
122- menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await97+ MAX_DISHES_PER_MENU as i64,
98+ )
99+ .await
123 }100 }
124 101
125 /// One dish, for callers that only inspect it.102 /// One dish, for callers that only inspect it.
@@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus(
140 menu_dish::list_for_menus(db, menus).await117 menu_dish::list_for_menus(db, menus).await
141 }118 }
142 119
143-/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see120+/// Edit a dish. Only what the request carried is written.
144-/// [`add_dish`]. Only what the request carried is written.
145 pub async fn update_dish(121 pub async fn update_dish(
146 db: &Database,122 db: &Database,
147 dish: MenuDish,123 dish: MenuDish,
@@ -150,12 +126,10 @@ pub async fn update_dish(
150 price_minor: Option<DishPrice>,126 price_minor: Option<DishPrice>,
151 tags: Option<DishTags>,127 tags: Option<DishTags>,
152 ) -> Result<MenuDish, AppError> {128 ) -> Result<MenuDish, AppError> {
153- let _guard = MENU_LOCK.lock().await;
154 menu_dish::update(db, dish, name, description, price_minor, tags).await129 menu_dish::update(db, dish, name, description, price_minor, tags).await
155 }130 }
156 131
157-/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write.132+/// Remove a dish from its menu.
158 pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {133 pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
159- let _guard = MENU_LOCK.lock().await;
160 menu_dish::delete(db, dish).await134 menu_dish::delete(db, dish).await
161 }135 }
src/web/meals.rsmodified+9 -9
@@ -438,11 +438,11 @@ async fn add_dish(
438 &req.tags,438 &req.tags,
439 &service::settings::load(&st.db).await?.get_dietary_tags(),439 &service::settings::load(&st.db).await?.get_dietary_tags(),
440 )?;440 )?;
441- // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK)441+ // The dish-cap gate lives in the service: the cap is one guarded
442- // lease live in the service: count-then-write is write-skew, so the count442+ // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the
443- // and the insert have to be one step, and the menu is read *inside* the443+ // dish write's own transaction and the insert carries the
444- // lock — read before it, a `DELETE /menus/{id}` running in the gap takes444+ // `count(*) < cap` guard, so a dish can never land on a menu that no
445- // its cascade with it and this dish lands on a menu that no longer exists.445+ // longer exists, and two racing writers cannot overfill it either.
446 let dish = service::menu::add_dish(446 let dish = service::menu::add_dish(
447 &st.db,447 &st.db,
448 &MenuId::from_key(&id),448 &MenuId::from_key(&id),
@@ -502,8 +502,8 @@ async fn update_dish(
502 )?),502 )?),
503 None => None,503 None => None,
504 };504 };
505- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)505+ // The dish write locks the menu row inside its own transaction — see
506- // inside the service, like every dish write — see `add_dish`.506+ // `add_dish`.
507 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;507 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;
508 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;508 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;
509 Ok(Json(DishResponse::new(&updated, &viewer_tags)))509 Ok(Json(DishResponse::new(&updated, &viewer_tags)))
@@ -531,8 +531,8 @@ async fn delete_dish(
531 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))531 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))
532 .await?532 .await?
533 .ok_or(AppError::NotFound)?;533 .ok_or(AppError::NotFound)?;
534- // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK)534+ // The dish write locks the menu row inside its own transaction — see
535- // inside the service, like every dish write — see `add_dish`.535+ // `add_dish`.
536 service::menu::delete_dish(&st.db, dish).await?;536 service::menu::delete_dish(&st.db, dish).await?;
537 Ok(StatusCode::NO_CONTENT)537 Ok(StatusCode::NO_CONTENT)
538 }538 }