From 50719d0ac0860701800283696249d5afb7e4ca02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 08:10:19 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20feat!:=20port=20meals?= =?UTF-8?q?=20(menu,=20dishes,=20bookings,=20attendance,=20ledger,=20dieta?= =?UTF-8?q?ry=20profiles)=20to=20sqlx/Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/dietary_profile.rs | 91 +++---- src/db/meal_attendance.rs | 125 +++++----- src/db/meal_booking.rs | 424 ++++++++++++++++++--------------- src/db/meal_ledger.rs | 141 +++++------ src/db/menu.rs | 378 ++++++++++++++--------------- src/db/menu_dish.rs | 271 +++++++++++---------- src/domain/menu.rs | 2 +- src/domain/menu_dish.rs | 4 +- src/service/meal_attendance.rs | 7 +- src/service/meal_booking.rs | 10 +- src/service/meal_ledger.rs | 2 +- src/service/menu.rs | 88 +++---- src/web/meals.rs | 18 +- 13 files changed, 780 insertions(+), 781 deletions(-) diff --git a/src/db/dietary_profile.rs b/src/db/dietary_profile.rs index 80f8ce4..7a80655 100644 --- a/src/db/dietary_profile.rs +++ b/src/db/dietary_profile.rs @@ -1,20 +1,28 @@ -//! The `dietary_profile` table: one row per student (the record key *is* -//! the student's key), created on first write and afterwards patched -//! field-by-field. The tag/note newtypes and the pure tag intersection live -//! in [`crate::domain::dietary_profile`]; the web layer reads through +//! The `dietary_profile` table: one row per student (the primary key *is* +//! the student), created on first write and afterwards patched +//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The +//! tag/note newtypes and the pure tag intersection live in +//! [`crate::domain::dietary_profile`]; the web layer reads through //! [`crate::service::dietary_profile`]. use crate::database::Database; -use crate::db::field_update::FieldUpdate; -use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags}; +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; /// One student's profile, or `None` while the school never recorded one. -/// A single `SELECT` by record id — this is what a menu read joins on. +/// A single `SELECT` by key — this is what a menu read joins on. pub async fn read(db: &Database, student: &UserId) -> Result, AppError> { - Ok(db.select(DietaryProfileId::of(student).record()).await?) + let row = sqlx::query_as!( + DietaryProfile, + "SELECT student, tags, note, updated_by, updated_at + FROM dietary_profile WHERE student = $1", + *student, + ) + .fetch_optional(db) + .await?; + Ok(row) } /// 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, App } /// Write the fields the PATCH carried. Creates the row on first write; -/// afterwards only the named fields move, because `student` is `READONLY` -/// and a whole-row save would also revert a concurrent edit of the other -/// field (see [`FieldUpdate`]). +/// afterwards only the named fields move, because a whole-row save would +/// also revert a concurrent edit of the other field. +/// +/// Both paths are one statement: an absent `tags` keeps the stored list +/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note +/// clears it and a `Some(Some)` overwrites it — the same three-way shape, +/// spelled with a "was the field on the request?" flag plus its nullable +/// value. A rival `PATCH` that created the row a moment ago turns this +/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all, +/// exactly as it would have been a moment later — without the error the old +/// store's create-then-patch pair had to catch. pub async fn save( db: &Database, student: &UserId, @@ -37,37 +53,24 @@ pub async fn save( note: Option>, by: &UserId, ) -> Result { - if read(db, student).await?.is_none() { - let profile = DietaryProfile { - id: DietaryProfileId::of(student), - student: student.clone(), - tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), - note: note.clone().flatten(), - updated_by: by.clone(), - updated_at: Timestamp::now(), - }; - match db.create(profile.id.record()).content(profile).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => { - return Err(AppError::Internal("failed to save the profile".into())); - } - // A rival first `PATCH` created the row in the round trip since - // the read above (the `dietary_profile_student` UNIQUE index - // catches the same collision), and `CREATE` leaves that row - // untouched — so this call is a plain field write after all, - // exactly as it would have been a moment later. Propagated, it - // was a 500 on a legitimate request. Same shape as - // [`crate::db::meal_ledger::append`], which - // reads the winner back rather than failing. - Err(err) if err.is_already_exists() => {} - Err(err) => return Err(err.into()), - } - } - FieldUpdate::new(DietaryProfileId::of(student).record()) - .set("tags", tags) - .set("note", note) - .set("updated_by", Some(by.clone())) - .set("updated_at", Some(Timestamp::now())) - .run::(db) - .await + let row = sqlx::query_as!( + DietaryProfile, + "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at) + VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5) + ON CONFLICT (student) DO UPDATE SET + tags = COALESCE($2, dietary_profile.tags), + note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, + updated_by = $4, + updated_at = $5 + RETURNING student, tags, note, updated_by, updated_at", + *student, + tags.map(|t| t.as_slice().to_vec()), + note.clone().flatten().map(|n| n.as_str().to_string()), + *by, + Timestamp::now(), + note.is_some(), + ) + .fetch_one(db) + .await?; + Ok(row) } diff --git a/src/db/meal_attendance.rs b/src/db/meal_attendance.rs index 43145ff..a848c83 100644 --- a/src/db/meal_attendance.rs +++ b/src/db/meal_attendance.rs @@ -1,38 +1,31 @@ //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per -//! (menu, student) that rides the menu's revision bump -//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the -//! two listings. Attendance is reporting only: nothing here writes the -//! ledger, and the workflows that read it live in the web layer via -//! [`crate::service::meal_attendance`]. +//! (menu, student) that rides the menu's revision bump inside its own +//! transaction, plus the two listings. Attendance is reporting only: nothing +//! here writes the ledger, and the workflows that read it live in the web +//! layer via [`crate::service::meal_attendance`]. -use surrealdb::types::SurrealValue; - -use crate::database::Database; -use crate::db::menu::bump_menu_and_write; -use crate::db::page::PagedList; -use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; -use crate::domain::menu::MenuDate; -use crate::domain::menu::MenuId; +use crate::database::{Database, tx_with_retry}; +use crate::db::page::{PagedList, Param}; +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; +use crate::domain::menu::{MenuDate, MenuId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; /// Record (or overwrite) whether `student` ate off `menu`. One row per -/// pair by construction, so a correction is the same UPSERT flipping the -/// status. No ledger line, ever — see the domain module header. +/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is +/// the same upsert flipping the status. No ledger line, ever — see the +/// domain module header. /// /// `NotFound` = the menu is gone, and the mark was *not* written. The mark -/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to -/// the menu row rather than a read the write then trusts: a delete racing -/// this one touches the very key this transaction bumps, and the store -/// refuses to commit both. Guarding by reading the menu — even as the -/// `UPSERT`'s own target — did not survive that race: the read saw a row -/// [`crate::db::menu::delete`] had deleted but not -/// yet committed, its sweep ran on a snapshot predating this insert, and the -/// mark outlived its menu with neither caller told anything (measured 378 of -/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, -/// republishing that day and slot then resurrected it as a mark on the new -/// menu. +/// and the menu's revision bump share one transaction, and the bump is what +/// makes the menu's **existence** part of it: the `UPDATE` matches nothing +/// once the menu row is deleted, and Postgres commits a deleting and a +/// bumping transaction on the same row strictly one after the other — the +/// mark either lands before the delete's guard re-reads its counter or not +/// at all. (Under the old store the same guarantee needed the shared bump +/// shape because deletes and child writes could interleave with a read in +/// between.) /// /// The bump costs a booking in flight one re-read (its seat claim asserts /// the revision it priced against) — the same tax every dish write already @@ -45,30 +38,40 @@ pub async fn mark( status: MealAttendanceStatus, marked_by: &UserId, ) -> Result { - let row = MealAttendance { - id: MealAttendanceId::composite(menu, student), - menu: menu.clone(), - student: student.clone(), - status, - marked_by: marked_by.clone(), - marked_at: Timestamp::now(), - }; - // Admissible for the retry loop inside: the id is bijective with the - // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` - // resolves onto the row that index already points at instead of - // colliding with it — it can never answer "already exists", and a - // re-sent round writes the identical row. - bump_menu_and_write( - menu, - "UPSERT $id CONTENT $row RETURN AFTER", - vec![ - ("id".into(), row.id.record().into_value()), - ("row".into(), row.into_value()), - ], - db, - ) - .await? - .ok_or_else(|| AppError::Internal("failed to record the mark".into())) + let marked_at = Timestamp::now(); + let student = *student; + let marked_by = *marked_by; + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu.key(), + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); + } + let row = sqlx::query_as!( + MealAttendance, + "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (menu, student) DO UPDATE + SET status = EXCLUDED.status, + marked_by = EXCLUDED.marked_by, + marked_at = EXCLUDED.marked_at + RETURNING menu, student, status, marked_by, marked_at", + menu.key(), + student, + status, + marked_by, + marked_at, + ) + .fetch_one(&mut *tx) + .await?; + Ok(row) + }) + .await } /// The kitchen's list for one menu. @@ -79,10 +82,10 @@ pub async fn list_for_menu( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_attendance WHERE menu = $menu", - "ORDER BY marked_at DESC, id DESC", + "meal_attendance WHERE menu = $1", + "ORDER BY marked_at DESC, menu DESC", ) - .bind("menu", menu.record()) + .bind(menu.key().to_string()) .run(limit, offset, db) .await } @@ -91,7 +94,7 @@ pub async fn list_for_menu( /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, /// which is chronological for that format (see [`MenuDate`]), and the link /// is followed rather than denormalized so a row can never disagree with -/// the menu it belongs to. +/// the menu it belongs to. A `NULL` bound means the bound is absent. pub async fn list_for_student( db: &Database, student: &UserId, @@ -101,14 +104,14 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_attendance WHERE student = $usr \ - AND ($from = NONE OR menu.date >= $from) \ - AND ($to = NONE OR menu.date <= $to)", - "ORDER BY marked_at DESC, id DESC", + "meal_attendance WHERE student = $1 \ + AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \ + AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))", + "ORDER BY marked_at DESC, menu DESC", ) - .bind("usr", student.record()) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) + .bind(student.key()) + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) .run(limit, offset, db) .await } diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index ddfaa14..06cf601 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -1,14 +1,11 @@ //! The `meal_booking` table: row reads, the two listings, and the folded -//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge -//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in -//! one). The book/cancel workflows that sequence these live in -//! [`crate::service::meal_booking`]; the row shape and the deadline checks in -//! [`crate::domain::meal_booking`]. +//! transactions every seat moves by — [`claim_and_place`] (seat + row + +//! charge in one transaction) and [`release_seat`] (flip + counter + refund +//! in one). The book/cancel workflows that sequence these live in +//! [`crate::service::meal_booking`]; the row shape and the deadline checks +//! in [`crate::domain::meal_booking`]. -use surrealdb::types::RecordId; - -use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD}; -use crate::database::{Database, backoff, lost_the_race}; +use crate::database::{Database, tx_with_retry}; use crate::db::cap::Claimed; use crate::db::page::PagedList; use crate::domain::meal_booking::{MealBooking, MealBookingId}; @@ -19,7 +16,16 @@ use crate::domain::user::UserId; use crate::error::AppError; pub async fn read(db: &Database, id: &MealBookingId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MealBooking, + "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + FROM meal_booking WHERE menu = $1 AND student = $2", + id.menu().key(), + *id.student(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Every booking on a menu, cancelled ones included — the kitchen's list. @@ -30,10 +36,10 @@ pub async fn list_for_menu( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_booking WHERE menu = $menu", - "ORDER BY created_at DESC, id DESC", + "meal_booking WHERE menu = $1", + "ORDER BY created_at DESC, student DESC", ) - .bind("menu", menu.record()) + .bind(menu.key().to_string()) .run(limit, offset, db) .await } @@ -41,10 +47,10 @@ pub async fn list_for_menu( /// Every seat held for one of `students`, newest first — a caller's own /// list is themselves plus whoever they hold a *live* parent link to. /// -/// Deliberately **not** `booked_by = $usr`: who placed a booking is history -/// written onto a READONLY column, and history is not a read grant. A -/// parent whose link was revoked (by an unlink or by the student-side role -/// sweep) would otherwise keep a live view of the child's seat, watching +/// Deliberately **not** `booked_by`: who placed a booking is history +/// written onto a fixed column, and history is not a read grant. A parent +/// whose link was revoked (by an unlink or by the student-side role sweep) +/// would otherwise keep a live view of the child's seat, watching /// cancellations made long after the link died — exactly what /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The /// caller re-derives the list from the links on every read, so the view @@ -55,34 +61,52 @@ pub async fn list_for_students( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "meal_booking WHERE student IN $students", - "ORDER BY created_at DESC, id DESC", - ) - .bind( - "students", - students.iter().map(UserId::record).collect::>(), + if students.is_empty() { + return Ok((Vec::new(), 0)); + } + let keys: Vec = students.iter().map(UserId::key).collect(); + let rows = sqlx::query_as!( + MealBooking, + "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + FROM meal_booking WHERE student = ANY($1::uuid[]) + ORDER BY created_at DESC, menu DESC + LIMIT $2 OFFSET $3", + keys, + limit, + offset, ) - .run(limit, offset, db) - .await + .fetch_all(db) + .await?; + // The window's own total — the same count the paging envelope answers. + let total = if limit.is_some() || offset != 0 { + sqlx::query_scalar!( + "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])", + keys, + ) + .fetch_one(db) + .await? as i64 + } else { + rows.len() as i64 + }; + Ok((rows, total)) } /// Take the seat **and** place the row in one transaction, at the menu /// revision the price was read at. /// -/// The seat and the row cannot be two steps. The id is the (menu, student) -/// pair, so two `POST`s of the same seat both find no row and both claim — -/// and on a tight cap the second is then told "full" for a seat it never -/// owed, while the winner's row may not even be visible yet. Here the -/// duplicate `CREATE` aborts the transaction, which takes its increment with -/// it: the counter never counts a row that does not exist, and a loser is -/// answered with the winner's booking instead of a refusal. Same shape as -/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the -/// revision guard and the revival of a cancelled row that the general form -/// does not carry. +/// The seat and the row cannot be two steps. The row key is the (menu, +/// student) pair, so two `POST`s of the same seat both find no row and both +/// claim — and on a tight cap the second is then told "full" for a seat it +/// never owed, while the winner's row may not even be visible yet. Here the +/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays +/// the winner, while the whole transaction (seat bump included) rolls back +/// on any refused path: the counter never counts a row that does not exist. +/// Same shape as the [`crate::db::cap`] claim recipe, with the revision +/// guard and the revival of a cancelled row that the general form does not +/// carry. /// /// A cancelled row is revived in place (a fresh attempt at `price`) rather -/// than recreated: `booked_by` and `created_at` are READONLY history — who +/// than recreated: `booked_by` and `created_at` are fixed history — who /// opened the seat, and when. /// /// **The charge rides this transaction too**, for the same reason the @@ -93,118 +117,135 @@ pub async fn list_for_students( /// moved past. That is why `row.attempt` is minted by the *caller*: the /// charge's id is (seat, attempt), so the number cannot be the revival's own /// `attempt + 1` any more. The revival is fenced on the attempt it read -/// instead, so a rival that revived first loses this claim (the `CREATE` -/// below then finds the row and aborts the whole transaction) rather than -/// billing its attempt at this call's id. +/// instead, so a rival that revived first loses this claim (the insert below +/// then finds the row and answers `Duplicate`) rather than billing its +/// attempt at this call's id. /// -/// The charge is created only if it is not already there — a duplicate -/// `CREATE` would abort the transaction and cost the seat, and an attempt +/// The charge is created only if it is not already there — an attempt /// billed twice is the one thing money code may never do. pub(crate) async fn claim_and_place( db: &Database, - seats: &RecordId, + menu: &MenuId, cap: i64, seen: i64, row: &MealBooking, price: Option, charge: Option<&MealLedger>, ) -> Result, AppError> { - // Empty when the menu is free: a seat that costs nothing owes no line. - let bill = match charge { - Some(_) => { - "IF array::len((SELECT VALUE id FROM $charge)) = 0 \ - { CREATE $charge CONTENT $line };" + let menu_key = menu.key().to_string(); + let student = row.student; + let attempt = row.attempt; + tx_with_retry(db, false, async |tx| { + // Already held? Same attempt, same price it was taken at — answered + // as `Duplicate`, which the caller replays into the winner's row + // (and its charge) without claiming anything. + let held = sqlx::query!( + "SELECT 1 AS held FROM meal_booking + WHERE menu = $1 AND student = $2 AND status = 'booked'", + menu_key, + student, + ) + .fetch_optional(&mut *tx) + .await?; + if held.is_some() { + return Ok(Claimed::Duplicate); } - None => "", - }; - // Slots count BEGIN, three LETs, three IFs and — when there is money to - // take — the charge's IF, so the RETURN is slot 7 or 8. - let returned = if charge.is_some() { 8 } else { 7 }; - // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way. - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked'); - IF array::len($held) > 0 {{ THROW 'held' }}; - LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \ - ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \ - WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \ - AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW 'no_seat' }}; - LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \ - price_minor = $price, cancelled_at = NONE \ - WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER); - IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }}; - {bill} - RETURN SELECT * FROM ONLY $id; - COMMIT TRANSACTION;" - ); - // Every booking on one menu contends on that menu's single counter row, - // which is one HTTP burst of racers on a single parent — the case - // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no - // backoff just re-synchronized them and 409'd the fourth student. - // Admissible: a lost round aborts the whole transaction (nothing - // written, no seat, no charge), and the two `CREATE`s that could - // legitimately answer "already exists" are read as `Claimed::Duplicate` - // below *before* the conflict check, so no decision is ever re-asked. - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let query = db - .query(sql.as_str()) - .bind(("menu", seats.clone())) - .bind(("cap", cap)) - .bind(("seen", seen)) - .bind(("id", row.id.record())) - .bind(("attempt", row.attempt)) - .bind(("price", price)) - .bind(("row", row.clone())); - let query = match charge { - Some(line) => query - .bind(("charge", line.get_id().record())) - .bind(("line", line.clone())), - None => query, - }; - let mut result = match query.await { - Ok(result) => result, - Err(err) if lost_the_race(&err) => continue, - Err(err) => return Err(err.into()), - }; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the failing slot says why, so scan them all. - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains("no_seat")) - { + // The seat: one conditional single-row write on the menu, atomic + // under Postgres — of the racers only `cap` of them per revision + // get a non-empty result, and the rest are refused with nothing + // written. + let seat = sqlx::query!( + "UPDATE menu SET seats_booked = seats_booked + 1 + WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3 + RETURNING 1 AS seat", + menu_key, + cap, + seen, + ) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { return Ok(Claimed::Full); } - if errors - .values() - .any(|error| error.to_string().contains("held") || error.is_already_exists()) - { + // Revive a cancelled row only while it still stands at the attempt + // this call read — the fence that keeps a rival's revival from + // being billed at this call's ids. + let revived = sqlx::query_as!( + MealBooking, + "UPDATE meal_booking + SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL + WHERE menu = $1 AND student = $2 + AND status = 'cancelled' AND attempt = $3 - 1 + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + attempt, + price, + ) + .fetch_optional(&mut *tx) + .await?; + let placed = match revived { + Some(row) => Some(row), + None => { + // No row (or a rival moved it past this attempt): place a + // fresh one. A rival that landed first answers `Duplicate` + // — nothing here overwrites its row. + let inserted = sqlx::query_as!( + MealBooking, + "INSERT INTO meal_booking + (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (menu, student) DO NOTHING + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + row.booked_by, + row.status, + row.attempt, + price, + row.cancelled_at, + row.created_at, + ) + .fetch_optional(&mut *tx) + .await?; + inserted + } + }; + let Some(placed) = placed else { return Ok(Claimed::Duplicate); - } - if errors.values().any(lost_the_race) { - continue; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - return match result.take::>(returned)? { - Some(placed) => Ok(Claimed::Made(placed)), - None => Err(AppError::Internal("failed to book the meal".into())), }; - } - Err(AppError::Conflict( - "the menu kept changing underneath this booking", - )) + // The charge rides the same transaction; already there (a replayed + // POST of this seat) means fine — nothing is written twice. + if let Some(line) = charge { + sqlx::query!( + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING", + line.id.key(), + line.student, + line.kind, + line.amount_minor, + line.source, + line.method, + line.note, + line.recorded_by, + line.created_at, + ) + .execute(&mut *tx) + .await?; + } + Ok(Claimed::Made(placed)) + }) + .await } /// Flip the seat to `cancelled` and give it back to the menu's counter **in /// one transaction**, so the two can never disagree: a decrement that ran /// without the flip frees a seat still held, and a flip without the -/// decrement locks a seat nothing can ever release. The counter follows the -/// flip's own result (`array::len`), so a row already cancelled — by a -/// racing cancel, or by this call retried — decrements nothing. +/// decrement locks a seat nothing can ever release. The decrement rides the +/// flip's own result, so a row already cancelled — by a racing cancel, or +/// by this call retried — decrements nothing. /// /// **The refund rides this transaction too**, and it has to: the flip and a /// reversal appended after it are two writes, and a crash in between leaves @@ -230,77 +271,78 @@ pub(crate) async fn claim_and_place( /// reversal id is burnt for good. /// /// `None` = the row was not this call's own `booked` attempt any more. -/// Retried while the store reports a write conflict: the menu row is -/// contended by every booking on it, and that contention is the cap -/// working, not an error. pub async fn release_seat( db: &Database, booked: &MealBooking, recorded_by: &UserId, ) -> Result, AppError> { let refund = MealLedger::reversal_for(booked, recorded_by); - // Guarded three ways: nothing was flipped (a rival cancelled first, and - // its own transaction carried the refund), the charge never landed, or - // this attempt is already refunded — none of which may abort the flip. - let reverse = match refund { - Some(_) => { - "IF array::len($flipped) > 0 \ - AND array::len((SELECT VALUE id FROM $charge)) > 0 \ - AND array::len((SELECT VALUE id FROM $reversal)) = 0 \ - { CREATE $reversal CONTENT $line };" - } - None => "", - }; - // Slots count BEGIN, the LET, the seat UPDATE and — when there is money - // to give back — the IF. - let returned = if refund.is_some() { 4 } else { 3 }; - // Same burst on the same counter as the book side, so the same patience - // (see [`claim_and_place`]) — a cancel that gave up left the seat - // held with the charge standing. Admissible: the round aborts having - // written nothing, and a re-send finds the row already `cancelled`, so - // the flip matches nothing, the counter moves nothing and the guarded - // reversal — keyed to (seat, attempt) — is not written twice. - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = async { - let query = db - .query(format!( - "BEGIN TRANSACTION; - LET $flipped = (UPDATE $id SET status = 'cancelled', \ - cancelled_at = $now \ - WHERE status = 'booked' AND attempt = $attempt RETURN AFTER); - UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\ - ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]); - {reverse} - RETURN $flipped; - COMMIT TRANSACTION;" - )) - .bind(("id", booked.id.record())) - .bind(("menu", booked.menu.record())) - .bind(("attempt", booked.attempt)) - .bind(("now", Timestamp::now())); - let query = match &refund { - Some((charge, line)) => query - .bind(("charge", charge.record())) - .bind(("reversal", line.get_id().record())) - .bind(("line", line.clone())), - None => query, - }; - let mut result = query.await?.check()?; - result.take::>(returned) + let menu_key = booked.menu.key().to_string(); + let student = booked.student; + let attempt = booked.attempt; + let cancelled_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + let flipped = sqlx::query_as!( + MealBooking, + "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 + WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + menu_key, + student, + cancelled_at, + attempt, + ) + .fetch_optional(&mut *tx) + .await?; + if flipped.is_some() { + sqlx::query!( + "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1", + menu_key, + ) + .execute(&mut *tx) + .await?; } - .await; - match attempted { - Ok(rows) => return Ok(rows.into_iter().next()), - Err(err) if lost_the_race(&err) => {} - Err(err) => return Err(err.into()), + // Guarded three ways: nothing was flipped (a rival cancelled first, + // and its own transaction carried the refund), the charge never + // landed, or this attempt is already refunded — none of which may + // abort the flip. + if let (true, Some((charge, line))) = (flipped.is_some(), &refund) { + let charge_there = sqlx::query!( + "SELECT 1 AS there FROM meal_ledger WHERE id = $1", + charge.key(), + ) + .fetch_optional(&mut *tx) + .await?; + let reversal_there = sqlx::query!( + "SELECT 1 AS there FROM meal_ledger WHERE id = $1", + line.id.key(), + ) + .fetch_optional(&mut *tx) + .await?; + if charge_there.is_some() && reversal_there.is_none() { + sqlx::query!( + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING", + line.id.key(), + line.student, + line.kind, + line.amount_minor, + line.source, + line.method, + line.note, + line.recorded_by, + line.created_at, + ) + .execute(&mut *tx) + .await?; + } } - } - Err(AppError::Conflict( - "the menu kept changing underneath this cancellation", - )) + Ok(flipped) + }) + .await } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs index dc0ea5e..f4266dc 100644 --- a/src/db/meal_ledger.rs +++ b/src/db/meal_ledger.rs @@ -3,29 +3,14 @@ //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal //! and credit workflows that sequence these in [`crate::service::meal_ledger`]. -use surrealdb::types::{AlreadyExistsError, SurrealValue}; - -use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE}; -use crate::database::{Database, lost_the_race}; -use crate::db::menu_dish; +use crate::database::Database; use crate::db::page::PagedList; -use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId, MealLedgerKind}; +use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId}; use crate::domain::menu::MenuId; use crate::domain::user::UserId; use crate::error::AppError; -/// Did this `CREATE` fail *only* because the row is already there? Matched on -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text -/// and never on "any database error", because swallowing a real fault in money -/// code would be far worse than the 500 it saves. -fn is_duplicate_record(error: &surrealdb::Error) -> bool { - matches!( - error.already_exists_details(), - Some(AlreadyExistsError::Record { .. }) - ) -} - -/// The only writer: one `CREATE`, no update path anywhere in this module. +/// The only writer: one `INSERT`, no update path anywhere in this module. /// /// A line whose id already exists is left exactly as it is — the row wins, /// the write is dropped. That is what makes a deterministic id (see @@ -33,38 +18,52 @@ fn is_duplicate_record(error: &surrealdb::Error) -> bool { /// append is a no-op, never a second line and never an edit of the first. /// The point read is on the id itself, so unlike a scan it cannot miss a /// row a concurrent writer just made — but it is only a fast path. The -/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves -/// the row untouched, so the writer that lost the race reads back the -/// winner's line instead of failing the request with a 500. -/// -/// A *write conflict* is the same race decided one layer down — two -/// appends of one id arriving together are no longer serialized by a -/// process-wide lock, so the store aborts one as retryable instead of -/// answering it "already exists". Both are read back the same way, and a -/// conflict that turns out to have written nothing is simply tried again; -/// no path here can write a second line, since the id is the key. +/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an +/// existing id nothing is written, so the writer that lost the race reads +/// back the winner's line instead of failing the request with a 500. pub(crate) async fn append(db: &Database, row: MealLedger) -> Result { if let Some(existing) = read(db, &row.id).await? { return Ok(existing); } - let id = row.id.clone(); - for _ in 0..CAS_UPDATE_RETRIES { - match db.create(id.record()).content(row.clone()).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => break, - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { - if let Some(existing) = read(db, &id).await? { - return Ok(existing); - } - } - Err(e) => return Err(e.into()), - } + let inserted = sqlx::query_as!( + MealLedger, + "INSERT INTO meal_ledger + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING + RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at", + row.id.key(), + row.student, + row.kind, + row.amount_minor, + row.source, + row.method, + row.note, + row.recorded_by, + row.created_at, + ) + .fetch_optional(db) + .await?; + match inserted { + Some(created) => Ok(created), + // Lost the id to a concurrent append of the same line: the stored + // row is the answer, never a second line. + None => read(db, &row.id) + .await? + .ok_or_else(|| AppError::Internal("failed to write the ledger line".into())), } - Err(AppError::Internal("failed to write the ledger line".into())) } pub async fn read(db: &Database, id: &MealLedgerId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MealLedger, + "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at + FROM meal_ledger WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// What a seat on `menu` costs *right now*: the sum of its dishes. `None` @@ -77,12 +76,11 @@ pub async fn price_snapshot( db: &Database, menu: &MenuId, ) -> Result, AppError> { - let total = menu_dish::list_for_menu(db, menu) - .await? - .iter() - .fold(0i64, |sum, dish| { - sum.saturating_add(dish.get_price_minor().as_minor()) - }); + let row = + sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key()) + .fetch_one(db) + .await?; + let total = row.total; if total == 0 { return Ok(None); } @@ -97,10 +95,10 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "meal_ledger WHERE student = $student", + "meal_ledger WHERE student = $1", "ORDER BY created_at DESC, id DESC", ) - .bind("student", student.record()) + .bind(student.key()) .run(limit, offset, db) .await } @@ -118,38 +116,27 @@ pub async fn list_for_student( /// every later `GET /meals/balance/*`. /// /// **The signs stay on the kind**, applied by the very -/// [`MealLedgerKind::sign`] -/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN -/// -amount …` in SQL would have folded the whole balance in one statement -/// and forked the one rule that decides what money means into a second -/// language, where nothing would fail the day the two disagreed. Grouping -/// instead keeps the aggregate ignorant of signs: it counts kinds, and -/// Rust still says what a kind does. A stored running total was the third -/// option and is a counter that can drift — a bug class this repo closes, -/// not one it opens. +/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign) +/// the documented formula is spelled in. Summing a signed CASE in SQL would +/// have folded the whole balance in one statement and forked the one rule +/// that decides what money means into a second language, where nothing +/// would fail the day the two disagreed. Grouping instead keeps the +/// aggregate ignorant of signs: it counts kinds, and Rust still says what a +/// kind does. A stored running total was the third option and is a counter +/// that can drift — a bug class this repo closes, not one it opens. pub async fn balance_of(db: &Database, student: &UserId) -> Result { - let totals: Vec = db - .query(format!( - "SELECT kind, math::sum(amount_minor) AS total \ - FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" - )) - .bind(("student", student.record())) - .await? - .check()? - .take(0)?; + let totals = sqlx::query!( + r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", + CAST(sum(amount_minor) AS BIGINT) AS total + FROM meal_ledger WHERE student = $1 GROUP BY kind"#, + *student, + ) + .fetch_all(db) + .await?; Ok(totals .iter() .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) } - -/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] hands -/// it back — at most three rows, never the lines behind them. -#[derive(Debug, SurrealValue)] -struct KindTotal { - kind: MealLedgerKind, - total: i64, -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/menu.rs b/src/db/menu.rs index b95956c..40c7ebb 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -1,100 +1,33 @@ //! The `menu` table: publishing (the slot reference claimed inside the //! write's own transaction), row reads and listings, the compare-and-set -//! every cap PATCH writes through, the cascading delete, and -//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every -//! child write (a dish, an attendance mark) uses so nothing can outlive its -//! menu. The kitchen workflows — the dish cap under -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in +//! every cap PATCH writes through, and the cascading delete. The kitchen +//! workflows — the guarded dish-cap insert — live in //! [`crate::service::menu`]. -use surrealdb::types::{SurrealValue, Value}; - -use crate::constant::{ - MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, - REF_COUNT_FIELD, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::page::{PagedList, Param}; use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Move the menu's revision **and** run `statement` — a write to something -/// hanging off a menu — in one transaction, handing back the row it returned. -/// -/// What a seat on that menu costs, or who is recorded against it, is about to -/// change, so any booking that priced itself against the old revision has to -/// re-read. The bump cannot be a query of its own: in the gap the menu row -/// carries the *new* revision with the *old* price, and a booking reading there -/// passes the very CAS that exists to refuse it — a seat billed a price the -/// menu had already left, or admitted past a capacity that had already shrunk. -/// -/// The bump is also what makes the menu's **existence** part of the write -/// ([`crate::db::menu_dish::create`] leans on -/// the same thing): the `UPDATE` matches nothing once the menu row is deleted, -/// and a delete racing this one touches the very key this transaction writes, -/// so the two cannot both commit. Reading the menu instead — even as the write -/// statement's own target — does not survive that race: the read sees a row the -/// delete has not committed yet, and [`delete`]'s sweep ran on a snapshot -/// predating this insert, so both commit and the child outlives its menu -/// (measured 378 of 3600 raced rounds before this shape was shared). -/// -/// Deliberately on every such write, not only the ones that move -/// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that applies -/// to every write cannot be forgotten by the next one added. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: an -/// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN` can never -/// answer "already exists", and neither can an `UPSERT` whose id is bijective -/// with every unique tuple its table indexes — a lost round wrote nothing, so -/// re-sending it is the recovery. -pub(crate) async fn bump_menu_and_write( - menu: &MenuId, - statement: &str, - mut bindings: Vec<(String, Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("menu".into(), menu.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_menu"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. - Ok(result.take::>(4)?.into_iter().next()) -} - /// Publish a menu. Refused (409) when the day+slot already carries one. /// -/// The day and slot *are* the record id ([`MenuId::for_slot`]), so the -/// refusal is decided by the store rather than by a check a concurrent -/// publish can outrun: two publishes of the same meal write one id, and the loser's -/// "already exists" becomes the same 409. The pre-check stays for the -/// ordinary case — and for menus published before ids were derived, whose -/// ULID key no new publish can collide with. +/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so +/// the refusal is decided by the store rather than by a check a concurrent +/// publish can outrun: two publishes of the same meal write one row, and +/// the loser's unique violation on `menu_pkey` becomes the same 409. The +/// in-transaction pre-check stays for the ordinary case. +/// +/// The menu takes a reference on its slot, which is what stops the slot +/// being dropped from the settings while this menu (whose slot is only +/// snapshotted text) still points at it. Claimed *inside* the write's own +/// transaction, with the duplicate gate ahead of the retired check so +/// "you already published this" still outranks "the slot is retired" (the +/// [`crate::db::cap`] reference-claim recipe): the counted row and the +/// count commit together or not at all, so no crash window is small enough +/// to leave a slot counted by a menu that does not exist — a slot nobody +/// could ever retire. pub async fn create( db: &Database, date: MenuDate, @@ -102,39 +35,80 @@ pub async fn create( capacity: Option, created_by: &UserId, ) -> Result { - let taken = AppError::Conflict("a menu is already published for that date and slot"); - if find(db, &date, &slot).await?.is_some() { - return Err(taken); - } - // The menu takes a reference on its slot, which is what stops the slot - // being dropped from the settings while this menu (whose slot is only - // snapshotted text) still points at it. Claimed *inside* the write's own - // transaction: a claim of its own could land and the row then fail to, - // leaving the slot counted by a menu that does not exist — a slot - // nobody can ever retire, and no crash window is small enough for that. + let id_key = MenuId::for_slot(&date, &slot).key().to_string(); let counter = slot_ref(slot.as_str()); - let menu = Menu { - id: MenuId::for_slot(&date, &slot), - date, - slot, - capacity, - version: Some(0), - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let id = menu.id.record(); - match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { - cap::ClaimedRef::Made(created) => Ok(created), - cap::ClaimedRef::Duplicate => Err(taken), - cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( - "the '{}' meal slot has been removed from the school's settings", - menu.slot.as_str() - ))), - } + let date_s = date.as_str().to_string(); + let slot_s = slot.as_str().to_string(); + let created_by = *created_by; + let created_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // Duplicate gate ahead of the retired check: "already published" + // outranks "slot retired", on the very path a rival publish races. + let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) + .fetch_optional(&mut *tx) + .await?; + if exists.is_some() { + return Err(AppError::Conflict( + "a menu is already published for that date and slot", + )); + } + let inserted = match sqlx::query_as!( + Menu, + "WITH ref AS ( + INSERT INTO slot_ref (name, count) VALUES ($2, 1) + ON CONFLICT (name) DO UPDATE SET count = slot_ref.count + 1 + WHERE slot_ref.retired = false + RETURNING 1 AS ref + ) + INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at) + SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref) + RETURNING id, date, slot, capacity, version, created_by, created_at", + id_key, + counter, + date_s, + slot_s, + capacity, + Some(0i64), + created_by, + created_at, + ) + .fetch_optional(&mut *tx) + .await + { + Ok(row) => row, + Err(err) => { + // A rival published the same meal after the pre-check: its + // row owns the key, and its publish is the answer. + if unique_violation(&err) == Some("menu_pkey") { + return Err(AppError::Conflict( + "a menu is already published for that date and slot", + )); + } + return Err(err.into()); + } + }; + match inserted { + Some(menu) => Ok(menu), + // The slot's ref row is retired — nothing was written. + None => Err(AppError::ConflictOwned(format!( + "the '{}' meal slot has been removed from the school's settings", + slot_s, + ))), + } + }) + .await } pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + Menu, + "SELECT id, date, slot, capacity, version, created_by, created_at + FROM menu WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// The menu for one day and slot, if any — the uniqueness check. @@ -143,18 +117,21 @@ pub async fn find( date: &MenuDate, slot: &MenuSlot, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") - .bind(("date", date.as_str().to_string())) - .bind(("slot", slot.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Menu, + "SELECT id, date, slot, capacity, version, created_by, created_at + FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", + date.as_str(), + slot.as_str(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; -/// either may be omitted. The comparison is lexical, which is chronological -/// for this format. +/// either may be omitted (`NULL` bound). The comparison is lexical, which +/// is chronological for this format. pub async fn list( db: &Database, from: Option<&MenuDate>, @@ -163,25 +140,26 @@ pub async fn list( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "menu WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to)", + "menu WHERE ($1::text IS NULL OR date >= $1::text) \ + AND ($2::text IS NULL OR date <= $2::text)", "ORDER BY date DESC, slot ASC, id DESC", ) - .bind("from", from.map(|date| date.as_str().to_string())) - .bind("to", to.map(|date| date.as_str().to_string())) + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) .run(limit, offset, db) .await } -/// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, +/// Only `capacity` is writable: `date` and `slot` are fixed at publish, /// because moving a published menu to another day is a different menu. /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. /// /// The revision moves **in the same statement** as the cap, indivisibly: a -/// booking claims its seat against the revision -/// it read the cap at, so a shrink that bumped in a query of its own left a -/// window where the row carried the *new* revision and the *old* cap — and -/// a booking arriving there passes a CAS meant to refuse it, over-admitting -/// by exactly the seats in flight. +/// booking claims its seat against the revision it read the cap at, so a +/// shrink that bumped in a query of its own left a window where the row +/// carried the *new* revision and the *old* cap — and a booking arriving +/// there passes a CAS meant to refuse it, over-admitting by exactly the +/// seats in flight. pub async fn update( db: &Database, menu: Menu, @@ -192,99 +170,89 @@ pub async fn update( // booking's price or cap has moved, so none owes a re-read. return read(db, &menu.id).await?.ok_or(AppError::NotFound); }; - let sql = format!( - "UPDATE $id SET capacity = $capacity, \ - {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" - ); - // One counter write in flight at a time, like every other one. - let _guard = cap::counter_lock().await; - write_with_retry::( - db, - &sql, - &[ - ("id".into(), menu.id.record().into_value()), - ("capacity".into(), capacity.into_value()), - ], + let row = sqlx::query_as!( + Menu, + "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 + WHERE id = $1 + RETURNING id, date, slot, capacity, version, created_by, created_at", + menu.id.key(), + capacity, ) - .await? - .into_iter() - .next() - .ok_or(AppError::NotFound) + .fetch_optional(db) + .await?; + row.ok_or(AppError::NotFound) } -/// Delete the menu and the dishes on it — a dish has no meaning without -/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. +/// Delete the menu and the dishes and marks on it — a dish or a mark has +/// no meaning without its menu, and the menu key cannot be re-homed. /// /// Refused (409) while a seat is still held, and the *row itself* decides /// that: the delete carries the seat counter in its `WHERE`, so a booking -/// landing at that instant either takes its seat before -/// the delete (which then finds a non-zero counter and refuses) or after it -/// (and finds no menu). A read-then-delete pair had a window where both -/// happened — a paid seat on a menu that no longer exists. +/// landing at that instant either takes its seat before the delete (which +/// then finds a non-zero counter and refuses) or after it (and finds no +/// menu). A read-then-delete pair had a window where both happened — a +/// paid seat on a menu that no longer exists. /// /// The slot gets its reference back in that same transaction — a slot no -/// menu is published for any more may leave the settings again, and the -/// `FOR` runs only over a row the guard actually took. Released afterwards -/// in a query of its own, a crash between the two left the slot counted by -/// a menu that no longer exists: a slot nobody can retire. +/// menu is published for any more may leave the settings again. Released +/// afterwards in a statement of its own, a crash between the two left the +/// slot counted by a menu that no longer exists: a slot nobody can retire. /// -/// The marks go in that same `FOR`, for a sharper reason than tidiness: +/// The marks go in that same sweep, for a sharper reason than tidiness: /// [`MenuId::for_slot`] is deterministic, so republishing the same day and -/// slot mints the *same* record id. A mark left behind would come back as a +/// slot mints the *same* row key. A mark left behind would come back as a /// mark on the new menu — the kitchen reading "served" for a student who /// never came — and until then the student's own report cites a menu that /// is gone. Attendance carries no money and no counter, so it is safe to -/// drop; cancelled *bookings* deliberately stay, because their `attempt` -/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut +/// drop; cancelled *bookings* deliberately stay (no foreign key ties them +/// to the menu), because their `attempt` counter is what keeps the +/// ledger's `(booking, attempt)` keys unique across the republish. Cut /// those and a re-book on a republished menu would reuse a charge id the /// ledger already holds, and the append (idempotent by design) would bill /// the seat nothing. /// -/// The dishes ride in that `FOR` too, and for the same reason as the marks: -/// run after the transaction committed, a crash between the two orphaned -/// them on a record id republishing the day and slot mints again — a new -/// menu serving (and pricing) the old one's food. +/// The dishes ride in the same sweep: run after the commit, a crash +/// between the two would orphan them on the row key a republish mints +/// again — a new menu serving (and pricing) the old one's food. pub async fn delete(db: &Database, menu: Menu) -> Result { - let sql = format!( - "BEGIN TRANSACTION; - LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); - FOR $row IN ($gone ?? []) {{ - UPSERT $counter SET {REF_COUNT_FIELD} = \ - math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); - DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; - DELETE {MENU_DISH_TABLE} WHERE menu = $id; - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ); - // `slot` is a `READONLY` column, so this counter is the one the deleted - // row carries. Nothing here can answer "already exists" — the `UPSERT` - // is keyed by a slot name on a table with no `UNIQUE` index, so it - // resolves onto the row it names ([`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("id".into(), menu.id.record().into_value()), - ("counter".into(), slot_ref(menu.slot.as_str()).into_value()), - ], - &[], - ) + let key = menu.id.key().to_string(); + let counter = slot_ref(menu.slot.as_str()); + let deleted = tx_with_retry(db, true, async |tx| { + let deleted = sqlx::query_as!( + Menu, + "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 + RETURNING id, date, slot, capacity, version, created_by, created_at", + key, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = deleted else { + return Ok(None); + }; + sqlx::query!( + "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1", + counter, + ) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) + .execute(&mut *tx) + .await?; + Ok(Some(row)) + }) .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN, the LET and the FOR take a slot each. - let Some(deleted) = result.take::>(3)?.into_iter().next() else { + match deleted { + Some(menu) => Ok(menu), // Nothing back: either seats are held, or the menu is already gone. - return Err(match read(db, &menu.id).await? { - Some(_) => AppError::Conflict("the menu still has live bookings"), - None => AppError::NotFound, - }); - }; - Ok(deleted) + None => match read(db, &menu.id).await? { + Some(_) => Err(AppError::Conflict("the menu still has live bookings")), + None => Err(AppError::NotFound), + }, + } } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/menu_dish.rs b/src/db/menu_dish.rs index 8f988e3..e66d605 100644 --- a/src/db/menu_dish.rs +++ b/src/db/menu_dish.rs @@ -1,14 +1,9 @@ -//! The `menu_dish` table: the dishes on a menu — the insert and the field -//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the -//! reads and listings, and the delete. The dish-cap gate and the -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in -//! [`crate::service::menu`]. +//! The `menu_dish` table: the dishes on a menu — the guarded insert (the +//! dish cap, enforced by the menu row's own lock), the field PATCH riding +//! the menu's revision bump, the reads and listings, and the delete. The +//! kitchen workflows live in [`crate::service::menu`]. -use surrealdb::types::{SurrealValue, Value}; - -use crate::constant::MENU_VERSION_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::menu::bump_menu_and_write; +use crate::database::{Database, tx_with_retry}; use crate::domain::menu::MenuId; use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, @@ -16,7 +11,15 @@ use crate::domain::menu_dish::{ use crate::domain::timestamp::Timestamp; use crate::error::AppError; -/// Add a dish. Moves the menu's revision *first* — see [`bump_menu_and_write`]. +/// Add a dish. The dish cap is one guarded decision, not a count a caller +/// took a moment earlier: the menu row is locked `FOR NO KEY UPDATE` in +/// this write's own transaction and the `INSERT` runs with a +/// `count(*) < $cap` guard — a writer that queued on the lock behind a +/// concurrent one re-counts after it and is refused (`409`) instead of +/// overfilling. The revision bump rides the same transaction, and the +/// lock's `SELECT` is what makes the menu's **existence** part of the +/// write: it matches nothing once the menu row is deleted, so `NotFound` +/// means the dish was not written. pub async fn create( db: &Database, menu: &MenuId, @@ -24,67 +27,67 @@ pub async fn create( description: Option, price_minor: DishPrice, tags: DishTags, + cap: i64, ) -> Result { - let dish = MenuDish { - id: MenuDishId::generate(), - menu: menu.clone(), - name, - description, - price_minor, - tags, - created_at: Timestamp::now(), - }; - // The revision bump and the insert are one transaction, and the bump is - // what makes the menu's existence part of it: the `UPDATE` matches - // nothing once the menu row is deleted, and a delete racing this one - // touches the very key this transaction writes, so the two cannot both - // commit. Without that, a dish landing just after `DELETE /menus/{id}` - // removed the row but before its cascade ran outlived its menu. - // Every other dish write bumps the same version key, so a lost round is - // ordinary here; it is re-sent rather than reported. Re-sending is sound - // even with the `CREATE` in the batch — the abort wrote nothing, the id - // is a ULID freshly generated above and never seen by a rival, and - // `menu_dish` carries no UNIQUE index — so the retry cannot answer - // "already exists" (see [`transaction_with_retry`]). - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; - CREATE $id CONTENT $dish; - COMMIT TRANSACTION;" - ), - &[ - ("menu".into(), menu.record().into_value()), - ("id".into(), dish.id.record().into_value()), - ("dish".into(), dish.into_value()), - ], - &["no_menu"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_menu")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. - result - .take::>(3)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to add the dish".into())) + let menu_key = menu.key().to_string(); + let id = MenuDishId::generate(); + let created_at = Timestamp::now(); + tx_with_retry(db, false, async |tx| { + // The lock first: every later statement in this transaction then + // sees the committed state of whoever queued ahead of it. + let locked = sqlx::query!( + "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if locked.is_none() { + return Err(AppError::NotFound); + } + sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1", + menu_key, + ) + .execute(&mut *tx) + .await?; + let placed = sqlx::query_as!( + MenuDish, + "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) + SELECT $1, $2, $3, $4, $5, $6, $7 + WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 + RETURNING id, menu, name, description, price_minor, tags, created_at", + id, + menu_key, + name, + description, + price_minor, + tags, + created_at, + cap, + ) + .fetch_optional(&mut *tx) + .await?; + match placed { + Some(dish) => Ok(dish), + // The menu exists (locked above), so an empty result is the cap. + None => Err(AppError::Conflict( + "the menu already carries the maximum number of dishes", + )), + } + }) + .await } pub async fn read(db: &Database, id: &MenuDishId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + MenuDish, + "SELECT id, menu, name, description, price_minor, tags, created_at + FROM menu_dish WHERE id = $1", + id.key(), + ) + .fetch_optional(db) + .await?; + Ok(row) } /// 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>(), - )) - .await? - .check()?; - Ok(result.take::>(0)?) -} - -/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. -pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result { - Ok(list_for_menu(db, menu).await?.len()) + let keys: Vec = menus.iter().map(|m| m.key().to_string()).collect(); + let rows = sqlx::query_as!( + MenuDish, + "SELECT id, menu, name, description, price_minor, tags, created_at + FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", + keys, + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Write only the fields the PATCH carried. `description` is nullable, so /// it takes the three-way shape: absent = keep, `Some(None)` = clear. +/// Each field is spelled with a "was it on the request?" flag and its +/// nullable value, so an omitted field is never written and a concurrent +/// PATCH of another one is not reverted. /// -/// The `SET` is built here rather than by -/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the -/// revision bump lands on *another* row and has to share this write's -/// transaction; the field-by-field scoping — an omitted field is never -/// written, so a concurrent PATCH of another one is not reverted — is the -/// same rule, spelled out. +/// The revision bump lands in the same transaction — "every dish write +/// bumps" is the rule a caller can rely on without knowing which fields +/// were on the wire. A PATCH that carried nothing still bumps and reads +/// the row back. pub async fn update( db: &Database, dish: MenuDish, @@ -131,45 +131,68 @@ pub async fn update( price_minor: Option, tags: Option, ) -> Result { - let mut sets: Vec<&str> = Vec::new(); - let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())]; - let mut set = |field: &'static str, value: Option| { - if let Some(value) = value { - sets.push(field); - bindings.push((field.into(), value)); + let dish_key = dish.id.key(); + let menu_key = dish.menu.key().to_string(); + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); } - }; - set("name", name.map(SurrealValue::into_value)); - set("description", description.map(SurrealValue::into_value)); - set("price_minor", price_minor.map(SurrealValue::into_value)); - set("tags", tags.map(SurrealValue::into_value)); - // A PATCH that carried nothing writes nothing and reads the row back, - // exactly as `FieldUpdate` answers one — but it still moves the - // revision, because "every dish write bumps" is the rule a caller can - // rely on without knowing which fields were on the wire. - let statement = if sets.is_empty() { - "SELECT * FROM $id".to_string() - } else { - format!( - "UPDATE $id SET {} RETURN AFTER", - sets.iter() - .map(|field| format!("{field} = ${field}")) - .collect::>() - .join(", ") + let row = sqlx::query_as!( + MenuDish, + "UPDATE menu_dish SET + name = COALESCE($2, name), + description = CASE WHEN $3 THEN $4 ELSE description END, + price_minor = COALESCE($5, price_minor), + tags = COALESCE($6, tags) + WHERE id = $1 + RETURNING id, menu, name, description, price_minor, tags, created_at", + dish_key, + name.map(|n| n.as_str().to_string()), + description.is_some(), + description + .clone() + .flatten() + .map(|d| d.as_str().to_string()), + price_minor.map(DishPrice::as_minor), + tags.map(|t| t.as_slice().to_vec()), ) - }; - bump_menu_and_write(&dish.menu, &statement, bindings, db) - .await? - .ok_or(AppError::NotFound) + .fetch_optional(&mut *tx) + .await?; + row.ok_or(AppError::NotFound) + }) + .await } pub async fn delete(db: &Database, dish: MenuDish) -> Result { - bump_menu_and_write( - &dish.menu, - "DELETE $id RETURN BEFORE", - vec![("id".into(), dish.id.record().into_value())], - db, - ) - .await? - .ok_or(AppError::NotFound) + let dish_key = dish.id.key(); + let menu_key = dish.menu.key().to_string(); + tx_with_retry(db, false, async |tx| { + let bumped = sqlx::query!( + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 + RETURNING 1 AS bumped", + menu_key, + ) + .fetch_optional(&mut *tx) + .await?; + if bumped.is_none() { + return Err(AppError::NotFound); + } + let row = sqlx::query_as!( + MenuDish, + "DELETE FROM menu_dish WHERE id = $1 + RETURNING id, menu, name, description, price_minor, tags, created_at", + dish_key, + ) + .fetch_optional(&mut *tx) + .await?; + row.ok_or(AppError::NotFound) + }) + .await } diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 1978f91..0dab6c8 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -11,7 +11,7 @@ //! never rewrite a menu already published under it. //! //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the -//! dish-cap lock) in [`crate::service::menu`]. +//! dish-cap gate) in [`crate::service::menu`]. use sqlx::Type; diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 224c137..44ff4a6 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -5,8 +5,8 @@ //! at any layer. `tags` are validated against the school's `dietary_tags` //! list, the same contract a menu's `slot` has with `meal_slots`. //! -//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the -//! write lock in [`crate::service::menu`]. +//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in +//! [`crate::service::menu`]. use sqlx::Type; use uuid::Uuid; diff --git a/src/service/meal_attendance.rs b/src/service/meal_attendance.rs index c0d78d0..7092fbf 100644 --- a/src/service/meal_attendance.rs +++ b/src/service/meal_attendance.rs @@ -1,9 +1,8 @@ //! The attendance-mark workflows: recording who ate off a menu and the two //! listings the kitchen and the student report read. The mark itself is a -//! single atomic UPSERT that rides the menu's revision bump -//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in -//! [`crate::db::meal_attendance`], the row shape in -//! [`crate::domain::meal_attendance`]. +//! single atomic upsert that rides the menu's revision bump inside its own +//! transaction — the queries live in [`crate::db::meal_attendance`], the row +//! shape in [`crate::domain::meal_attendance`]. use crate::database::Database; use crate::db::meal_attendance; diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index 2443fbd..deb8359 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -9,9 +9,10 @@ //! //! **No process-wide lock guards this domain**, and deliberately: every //! invariant booking depends on is a *single-record* conditional write (the -//! menu's `seats_booked` counter and the attempt-fenced row flip), which -//! SurrealDB itself serializes — a cross-record lock would add contention -//! without deciding anything the transactions do not already. What the +//! menu's `seats_booked` counter and the attempt-fenced row flip), which the +//! guarded writes themselves serialize — a cross-record lock would add +//! contention without deciding anything the transactions do not already. +//! What the //! service layer owns here is the *sequence*: read the menu, refuse a past //! day or a closed cutoff before anything is claimed, settle the attempt //! number before the charge id exists, and map the claim's outcomes @@ -62,7 +63,6 @@ pub async fn book( cutoff: &MealCutoff, ) -> Result { let id = MealBookingId::composite(menu, student); - let seats = menu.record(); for attempt in 0..CAP_WRITE_TRIES { backoff(attempt).await; let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?; @@ -135,7 +135,7 @@ pub async fn book( let charge = MealLedger::charge_for(&fresh_row, booked_by); match meal_booking::claim_and_place( db, - &seats, + menu, fresh.get_capacity().unwrap_or(cap::UNLIMITED), fresh.get_version(), &fresh_row, diff --git a/src/service/meal_ledger.rs b/src/service/meal_ledger.rs index ae6dad7..ea99a24 100644 --- a/src/service/meal_ledger.rs +++ b/src/service/meal_ledger.rs @@ -77,7 +77,7 @@ pub async fn reverse_booking( /// resending the identical body after a timeout gets back the line the /// first attempt wrote, not a second credit — nothing on this API can edit /// or delete one, so a doubled credit is corrected only by a compensating -/// line. Without one the id is a fresh ulid and two identical calls are two +/// line. Without one the id is a fresh uuid and two identical calls are two /// credits, which is what a desk taking the same amount twice really means. pub async fn credit( db: &Database, diff --git a/src/service/menu.rs b/src/service/menu.rs index 52f2439..1895b06 100644 --- a/src/service/menu.rs +++ b/src/service/menu.rs @@ -1,24 +1,16 @@ //! The kitchen's workflows: publishing and unpublishing menus, and every -//! dish write — which all hold [`MENU_LOCK`], the lock that makes the -//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB -//! does not conflict-check) more than a wish. The queries live in -//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the -//! date/slot/capacity rules in [`crate::domain::menu`] and -//! [`crate::domain::menu_dish`]. +//! dish write. The queries live in [`crate::db::menu`] and +//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity +//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`]. //! -//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the -//! dishes, write the dish), which is why it lives here and not in the db -//! layer: a single-call atomicity lock would be the store's to own, but -//! count-then-write is write-skew only this process can serialize. -//! -//! **A leaf**: every dish write held under it moves the menu's revision -//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]), -//! so no path under this lock reaches `cap`'s counter lock any more. Should -//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing -//! may take this lock while holding a counter lock: that is the invariant a -//! new caller must keep, and it is what would keep the pair deadlock-free. - -use tokio::sync::Mutex; +//! **No process-wide lock guards this domain.** The dish cap +//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a +//! process mutex could make safe; it is now one guarded statement — the +//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own +//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that +//! lock, so two racing writers serialize on the row the database owns. +//! Every dish write moves the menu's revision in that same transaction, and +//! a booking claims its seat at the revision it priced itself against. use crate::constant::MAX_DISHES_PER_MENU; use crate::database::Database; @@ -30,20 +22,6 @@ use crate::domain::menu_dish::{ use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes what is left that counts rows against one menu: the dish cap -/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not -/// conflict-check). Publishing no longer needs it — the day+slot *is* the -/// record id — and neither does a booking, a menu delete, or the settings -/// slot-removal guard: those went to conditional single-record writes -/// ([`crate::db::cap`]), which the store decides as this lock cannot. -// -// corner-cut: the dish cap therefore rests on this lock alone — a dish write -// added without taking it reopens the count-then-write hole silently. Closing -// it properly is another `cap` counter (`dish_count` on the menu row) plus its -// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was -// not worth the column here. -pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); - /// Publish a menu for one day and meal slot. The caller has validated the /// date (a real calendar day, not already over), the slot (one the school /// serves) and the capacity; the day+slot duplicate refusal is decided by @@ -92,18 +70,15 @@ pub async fn delete(db: &Database, menu_row: Menu) -> Result { /// Add a dish to a menu, under the dish cap. /// -/// [`MENU_LOCK`] is taken for the dish cap alone: count-then-write -/// is write-skew, so the count and the insert have to be one step. The -/// *price* no longer needs it — a dish write moves the menu's revision, and -/// a booking claims its seat at the revision it priced itself against. -/// The lock is a leaf again: the revision bump rides the dish write's own -/// transaction now, so nothing held under it takes `cap`'s counter lock. It -/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a -/// caller that changes it must keep. +/// The cap is the database's to enforce, not this process's: the write +/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a +/// `count(*) < cap` guard, so a writer that queued behind a concurrent one +/// re-counts after the lock and is refused (`409`) instead of overfilling +/// — the count and the insert are one decision, with no window a second +/// writer can slip through. /// -/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` -/// running in the gap takes its cascade with it and this dish lands on a menu -/// that no longer exists. +/// The *price* needs no lock — a dish write moves the menu's revision, and +/// a booking claims its seat at the revision it priced itself against. pub async fn add_dish( db: &Database, menu_id: &MenuId, @@ -112,14 +87,16 @@ pub async fn add_dish( price_minor: DishPrice, tags: DishTags, ) -> Result { - let _guard = MENU_LOCK.lock().await; - let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?; - if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU { - return Err(AppError::Conflict( - "the menu already carries the maximum number of dishes", - )); - } - menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await + menu_dish::create( + db, + menu_id, + name, + description, + price_minor, + tags, + MAX_DISHES_PER_MENU as i64, + ) + .await } /// One dish, for callers that only inspect it. @@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus( menu_dish::list_for_menus(db, menus).await } -/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see -/// [`add_dish`]. Only what the request carried is written. +/// Edit a dish. Only what the request carried is written. pub async fn update_dish( db: &Database, dish: MenuDish, @@ -150,12 +126,10 @@ pub async fn update_dish( price_minor: Option, tags: Option, ) -> Result { - let _guard = MENU_LOCK.lock().await; menu_dish::update(db, dish, name, description, price_minor, tags).await } -/// Remove a dish from its menu. Under [`MENU_LOCK`] like every dish write. +/// Remove a dish from its menu. pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result { - let _guard = MENU_LOCK.lock().await; menu_dish::delete(db, dish).await } diff --git a/src/web/meals.rs b/src/web/meals.rs index df1cfc3..0ccbf96 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -438,11 +438,11 @@ async fn add_dish( &req.tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?; - // The dish-cap gate and its [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // lease live in the service: count-then-write is write-skew, so the count - // and the insert have to be one step, and the menu is read *inside* the - // lock — read before it, a `DELETE /menus/{id}` running in the gap takes - // its cascade with it and this dish lands on a menu that no longer exists. + // The dish-cap gate lives in the service: the cap is one guarded + // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the + // dish write's own transaction and the insert carries the + // `count(*) < cap` guard, so a dish can never land on a menu that no + // longer exists, and two racing writers cannot overfill it either. let dish = service::menu::add_dish( &st.db, &MenuId::from_key(&id), @@ -502,8 +502,8 @@ async fn update_dish( )?), None => None, }; - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // inside the service, like every dish write — see `add_dish`. + // The dish write locks the menu row inside its own transaction — see + // `add_dish`. let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(Json(DishResponse::new(&updated, &viewer_tags))) @@ -531,8 +531,8 @@ async fn delete_dish( let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) - // inside the service, like every dish write — see `add_dish`. + // The dish write locks the menu row inside its own transaction — see + // `add_dish`. service::menu::delete_dish(&st.db, dish).await?; Ok(StatusCode::NO_CONTENT) }