Merge branch 'postgres' into pg/l9
Browse files at this commit13 changed files +780 -781
- src/db/dietary_profile.rs +47 -44
- src/db/meal_attendance.rs +64 -61
- src/db/meal_booking.rs +233 -191
- src/db/meal_ledger.rs +64 -77
- src/db/menu.rs +173 -205
- src/db/menu_dish.rs +147 -124
- src/domain/menu.rs +1 -1
- src/domain/menu_dish.rs +2 -2
- src/service/meal_attendance.rs +3 -4
- src/service/meal_booking.rs +5 -5
- src/service/meal_ledger.rs +1 -1
- src/service/menu.rs +31 -57
- src/web/meals.rs +9 -9
src/db/dietary_profile.rsmodified+47 -44
| @@ -1,20 +1,28 @@ | ||
| 1 | -//! The `dietary_profile` table: one row per student (the record key *is* | |
| 2 | -//! the student's key), created on first write and afterwards patched | |
| 3 | -//! field-by-field. The tag/note newtypes and the pure tag intersection live | |
| 4 | -//! in [`crate::domain::dietary_profile`]; the web layer reads through | |
| 1 | +//! The `dietary_profile` table: one row per student (the primary key *is* | |
| 2 | +//! the student), created on first write and afterwards patched | |
| 3 | +//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The | |
| 4 | +//! tag/note newtypes and the pure tag intersection live in | |
| 5 | +//! [`crate::domain::dietary_profile`]; the web layer reads through | |
| 5 | 6 | //! [`crate::service::dietary_profile`]. |
| 6 | 7 | |
| 7 | 8 | use crate::database::Database; |
| 8 | -use crate::db::field_update::FieldUpdate; | |
| 9 | -use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryProfileId, DietaryTags}; | |
| 9 | +use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; | |
| 10 | 10 | use crate::domain::timestamp::Timestamp; |
| 11 | 11 | use crate::domain::user::UserId; |
| 12 | 12 | use crate::error::AppError; |
| 13 | 13 | |
| 14 | 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 | 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 | 28 | /// 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 | 37 | /// Write the fields the PATCH carried. Creates the row on first write; |
| 30 | -/// afterwards only the named fields move, because `student` is `READONLY` | |
| 31 | -/// and a whole-row save would also revert a concurrent edit of the other | |
| 32 | -/// field (see [`FieldUpdate`]). | |
| 38 | +/// afterwards only the named fields move, because a whole-row save would | |
| 39 | +/// also revert a concurrent edit of the other field. | |
| 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 | 49 | pub async fn save( |
| 34 | 50 | db: &Database, |
| 35 | 51 | student: &UserId, |
| @@ -37,37 +53,24 @@ pub async fn save( | ||
| 37 | 53 | note: Option<Option<DietaryNote>>, |
| 38 | 54 | by: &UserId, |
| 39 | 55 | ) -> Result<DietaryProfile, AppError> { |
| 40 | - if read(db, student).await?.is_none() { | |
| 41 | - let profile = DietaryProfile { | |
| 42 | - id: DietaryProfileId::of(student), | |
| 43 | - student: student.clone(), | |
| 44 | - tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), | |
| 45 | - note: note.clone().flatten(), | |
| 46 | - updated_by: by.clone(), | |
| 47 | - updated_at: Timestamp::now(), | |
| 48 | - }; | |
| 49 | - match db.create(profile.id.record()).content(profile).await { | |
| 50 | - Ok(Some(created)) => return Ok(created), | |
| 51 | - Ok(None) => { | |
| 52 | - return Err(AppError::Internal("failed to save the profile".into())); | |
| 53 | - } | |
| 54 | - // A rival first `PATCH` created the row in the round trip since | |
| 55 | - // the read above (the `dietary_profile_student` UNIQUE index | |
| 56 | - // catches the same collision), and `CREATE` leaves that row | |
| 57 | - // untouched — so this call is a plain field write after all, | |
| 58 | - // exactly as it would have been a moment later. Propagated, it | |
| 59 | - // was a 500 on a legitimate request. Same shape as | |
| 60 | - // [`crate::db::meal_ledger::append`], which | |
| 61 | - // reads the winner back rather than failing. | |
| 62 | - Err(err) if err.is_already_exists() => {} | |
| 63 | - Err(err) => return Err(err.into()), | |
| 64 | - } | |
| 65 | - } | |
| 66 | - FieldUpdate::new(DietaryProfileId::of(student).record()) | |
| 67 | - .set("tags", tags) | |
| 68 | - .set("note", note) | |
| 69 | - .set("updated_by", Some(by.clone())) | |
| 70 | - .set("updated_at", Some(Timestamp::now())) | |
| 71 | - .run::<DietaryProfile>(db) | |
| 72 | - .await | |
| 56 | + let row = sqlx::query_as!( | |
| 57 | + DietaryProfile, | |
| 58 | + "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at) | |
| 59 | + VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5) | |
| 60 | + ON CONFLICT (student) DO UPDATE SET | |
| 61 | + tags = COALESCE($2, dietary_profile.tags), | |
| 62 | + note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, | |
| 63 | + updated_by = $4, | |
| 64 | + updated_at = $5 | |
| 65 | + RETURNING student, tags, note, updated_by, updated_at", | |
| 66 | + *student, | |
| 67 | + tags.map(|t| t.as_slice().to_vec()), | |
| 68 | + note.clone().flatten().map(|n| n.as_str().to_string()), | |
| 69 | + *by, | |
| 70 | + Timestamp::now(), | |
| 71 | + note.is_some(), | |
| 72 | + ) | |
| 73 | + .fetch_one(db) | |
| 74 | + .await?; | |
| 75 | + Ok(row) | |
| 73 | 76 | } |
src/db/meal_attendance.rsmodified+64 -61
| @@ -1,38 +1,31 @@ | ||
| 1 | 1 | //! The `meal_attendance` table: the kitchen's marks — one atomic UPSERT per |
| 2 | -//! (menu, student) that rides the menu's revision bump | |
| 3 | -//! ([`bump_menu_and_write`](crate::db::menu::bump_menu_and_write)), plus the | |
| 4 | -//! two listings. Attendance is reporting only: nothing here writes the | |
| 5 | -//! ledger, and the workflows that read it live in the web layer via | |
| 6 | -//! [`crate::service::meal_attendance`]. | |
| 2 | +//! (menu, student) that rides the menu's revision bump inside its own | |
| 3 | +//! transaction, plus the two listings. Attendance is reporting only: nothing | |
| 4 | +//! here writes the ledger, and the workflows that read it live in the web | |
| 5 | +//! layer via [`crate::service::meal_attendance`]. | |
| 7 | 6 | |
| 8 | -use surrealdb::types::SurrealValue; | |
| 9 | - | |
| 10 | -use crate::database::Database; | |
| 11 | -use crate::db::menu::bump_menu_and_write; | |
| 12 | -use crate::db::page::PagedList; | |
| 13 | -use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; | |
| 14 | -use crate::domain::menu::MenuDate; | |
| 15 | -use crate::domain::menu::MenuId; | |
| 7 | +use crate::database::{Database, tx_with_retry}; | |
| 8 | +use crate::db::page::{PagedList, Param}; | |
| 9 | +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | |
| 10 | +use crate::domain::menu::{MenuDate, MenuId}; | |
| 16 | 11 | use crate::domain::timestamp::Timestamp; |
| 17 | 12 | use crate::domain::user::UserId; |
| 18 | 13 | use crate::error::AppError; |
| 19 | 14 | |
| 20 | 15 | /// Record (or overwrite) whether `student` ate off `menu`. One row per |
| 21 | -/// pair by construction, so a correction is the same UPSERT flipping the | |
| 22 | -/// status. No ledger line, ever — see the domain module header. | |
| 16 | +/// pair by construction (`ON CONFLICT (menu, student)`), so a correction is | |
| 17 | +/// the same upsert flipping the status. No ledger line, ever — see the | |
| 18 | +/// domain module header. | |
| 23 | 19 | /// |
| 24 | 20 | /// `NotFound` = the menu is gone, and the mark was *not* written. The mark |
| 25 | -/// rides in [`bump_menu_and_write`], so the menu's existence is a *write* to | |
| 26 | -/// the menu row rather than a read the write then trusts: a delete racing | |
| 27 | -/// this one touches the very key this transaction bumps, and the store | |
| 28 | -/// refuses to commit both. Guarding by reading the menu — even as the | |
| 29 | -/// `UPSERT`'s own target — did not survive that race: the read saw a row | |
| 30 | -/// [`crate::db::menu::delete`] had deleted but not | |
| 31 | -/// yet committed, its sweep ran on a snapshot predating this insert, and the | |
| 32 | -/// mark outlived its menu with neither caller told anything (measured 378 of | |
| 33 | -/// 3600 raced rounds). Since [`MenuId::for_slot`] is deterministic, | |
| 34 | -/// republishing that day and slot then resurrected it as a mark on the new | |
| 35 | -/// menu. | |
| 21 | +/// and the menu's revision bump share one transaction, and the bump is what | |
| 22 | +/// makes the menu's **existence** part of it: the `UPDATE` matches nothing | |
| 23 | +/// once the menu row is deleted, and Postgres commits a deleting and a | |
| 24 | +/// bumping transaction on the same row strictly one after the other — the | |
| 25 | +/// mark either lands before the delete's guard re-reads its counter or not | |
| 26 | +/// at all. (Under the old store the same guarantee needed the shared bump | |
| 27 | +/// shape because deletes and child writes could interleave with a read in | |
| 28 | +/// between.) | |
| 36 | 29 | /// |
| 37 | 30 | /// The bump costs a booking in flight one re-read (its seat claim asserts |
| 38 | 31 | /// the revision it priced against) — the same tax every dish write already |
| @@ -45,30 +38,40 @@ pub async fn mark( | ||
| 45 | 38 | status: MealAttendanceStatus, |
| 46 | 39 | marked_by: &UserId, |
| 47 | 40 | ) -> Result<MealAttendance, AppError> { |
| 48 | - let row = MealAttendance { | |
| 49 | - id: MealAttendanceId::composite(menu, student), | |
| 50 | - menu: menu.clone(), | |
| 51 | - student: student.clone(), | |
| 52 | - status, | |
| 53 | - marked_by: marked_by.clone(), | |
| 54 | - marked_at: Timestamp::now(), | |
| 55 | - }; | |
| 56 | - // Admissible for the retry loop inside: the id is bijective with the | |
| 57 | - // (menu, student) pair the table indexes UNIQUE, so this `UPSERT` | |
| 58 | - // resolves onto the row that index already points at instead of | |
| 59 | - // colliding with it — it can never answer "already exists", and a | |
| 60 | - // re-sent round writes the identical row. | |
| 61 | - bump_menu_and_write( | |
| 62 | - menu, | |
| 63 | - "UPSERT $id CONTENT $row RETURN AFTER", | |
| 64 | - vec![ | |
| 65 | - ("id".into(), row.id.record().into_value()), | |
| 66 | - ("row".into(), row.into_value()), | |
| 67 | - ], | |
| 68 | - db, | |
| 69 | - ) | |
| 70 | - .await? | |
| 71 | - .ok_or_else(|| AppError::Internal("failed to record the mark".into())) | |
| 41 | + let marked_at = Timestamp::now(); | |
| 42 | + let student = *student; | |
| 43 | + let marked_by = *marked_by; | |
| 44 | + tx_with_retry(db, false, async |tx| { | |
| 45 | + let bumped = sqlx::query!( | |
| 46 | + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | |
| 47 | + RETURNING 1 AS bumped", | |
| 48 | + menu.key(), | |
| 49 | + ) | |
| 50 | + .fetch_optional(&mut *tx) | |
| 51 | + .await?; | |
| 52 | + if bumped.is_none() { | |
| 53 | + return Err(AppError::NotFound); | |
| 54 | + } | |
| 55 | + let row = sqlx::query_as!( | |
| 56 | + MealAttendance, | |
| 57 | + "INSERT INTO meal_attendance (menu, student, status, marked_by, marked_at) | |
| 58 | + VALUES ($1, $2, $3, $4, $5) | |
| 59 | + ON CONFLICT (menu, student) DO UPDATE | |
| 60 | + SET status = EXCLUDED.status, | |
| 61 | + marked_by = EXCLUDED.marked_by, | |
| 62 | + marked_at = EXCLUDED.marked_at | |
| 63 | + RETURNING menu, student, status, marked_by, marked_at", | |
| 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 | 77 | /// The kitchen's list for one menu. |
| @@ -79,10 +82,10 @@ pub async fn list_for_menu( | ||
| 79 | 82 | offset: i64, |
| 80 | 83 | ) -> Result<(Vec<MealAttendance>, i64), AppError> { |
| 81 | 84 | PagedList::new( |
| 82 | - "meal_attendance WHERE menu = $menu", | |
| 83 | - "ORDER BY marked_at DESC, id DESC", | |
| 85 | + "meal_attendance WHERE menu = $1", | |
| 86 | + "ORDER BY marked_at DESC, menu DESC", | |
| 84 | 87 | ) |
| 85 | - .bind("menu", menu.record()) | |
| 88 | + .bind(menu.key().to_string()) | |
| 86 | 89 | .run(limit, offset, db) |
| 87 | 90 | .await |
| 88 | 91 | } |
| @@ -91,7 +94,7 @@ pub async fn list_for_menu( | ||
| 91 | 94 | /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, |
| 92 | 95 | /// which is chronological for that format (see [`MenuDate`]), and the link |
| 93 | 96 | /// 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 | 98 | pub async fn list_for_student( |
| 96 | 99 | db: &Database, |
| 97 | 100 | student: &UserId, |
| @@ -101,14 +104,14 @@ pub async fn list_for_student( | ||
| 101 | 104 | offset: i64, |
| 102 | 105 | ) -> Result<(Vec<MealAttendance>, i64), AppError> { |
| 103 | 106 | PagedList::new( |
| 104 | - "meal_attendance WHERE student = $usr \ | |
| 105 | - AND ($from = NONE OR menu.date >= $from) \ | |
| 106 | - AND ($to = NONE OR menu.date <= $to)", | |
| 107 | - "ORDER BY marked_at DESC, id DESC", | |
| 107 | + "meal_attendance WHERE student = $1 \ | |
| 108 | + AND ($2::text IS NULL OR menu IN (SELECT id FROM menu WHERE date >= $2::text)) \ | |
| 109 | + AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))", | |
| 110 | + "ORDER BY marked_at DESC, menu DESC", | |
| 108 | 111 | ) |
| 109 | - .bind("usr", student.record()) | |
| 110 | - .bind("from", from.map(|date| date.as_str().to_string())) | |
| 111 | - .bind("to", to.map(|date| date.as_str().to_string())) | |
| 112 | + .bind(student.key()) | |
| 113 | + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) | |
| 114 | + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) | |
| 112 | 115 | .run(limit, offset, db) |
| 113 | 116 | .await |
| 114 | 117 | } |
src/db/meal_booking.rsmodified+233 -191
| @@ -1,14 +1,11 @@ | ||
| 1 | 1 | //! The `meal_booking` table: row reads, the two listings, and the folded |
| 2 | -//! transactions every seat moves by — [`claim_and_place`] (seat + row + charge | |
| 3 | -//! in one `BEGIN…COMMIT`) and [`release_seat`] (flip + counter + refund in | |
| 4 | -//! one). The book/cancel workflows that sequence these live in | |
| 5 | -//! [`crate::service::meal_booking`]; the row shape and the deadline checks in | |
| 6 | -//! [`crate::domain::meal_booking`]. | |
| 2 | +//! transactions every seat moves by — [`claim_and_place`] (seat + row + | |
| 3 | +//! charge in one transaction) and [`release_seat`] (flip + counter + refund | |
| 4 | +//! in one). The book/cancel workflows that sequence these live in | |
| 5 | +//! [`crate::service::meal_booking`]; the row shape and the deadline checks | |
| 6 | +//! in [`crate::domain::meal_booking`]. | |
| 7 | 7 | |
| 8 | -use surrealdb::types::RecordId; | |
| 9 | - | |
| 10 | -use crate::constant::{CAP_WRITE_TRIES, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD}; | |
| 11 | -use crate::database::{Database, backoff, lost_the_race}; | |
| 8 | +use crate::database::{Database, tx_with_retry}; | |
| 12 | 9 | use crate::db::cap::Claimed; |
| 13 | 10 | use crate::db::page::PagedList; |
| 14 | 11 | use crate::domain::meal_booking::{MealBooking, MealBookingId}; |
| @@ -19,7 +16,16 @@ use crate::domain::user::UserId; | ||
| 19 | 16 | use crate::error::AppError; |
| 20 | 17 | |
| 21 | 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 | 31 | /// Every booking on a menu, cancelled ones included — the kitchen's list. |
| @@ -30,10 +36,10 @@ pub async fn list_for_menu( | ||
| 30 | 36 | offset: i64, |
| 31 | 37 | ) -> Result<(Vec<MealBooking>, i64), AppError> { |
| 32 | 38 | PagedList::new( |
| 33 | - "meal_booking WHERE menu = $menu", | |
| 34 | - "ORDER BY created_at DESC, id DESC", | |
| 39 | + "meal_booking WHERE menu = $1", | |
| 40 | + "ORDER BY created_at DESC, student DESC", | |
| 35 | 41 | ) |
| 36 | - .bind("menu", menu.record()) | |
| 42 | + .bind(menu.key().to_string()) | |
| 37 | 43 | .run(limit, offset, db) |
| 38 | 44 | .await |
| 39 | 45 | } |
| @@ -41,10 +47,10 @@ pub async fn list_for_menu( | ||
| 41 | 47 | /// Every seat held for one of `students`, newest first — a caller's own |
| 42 | 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 history | |
| 45 | -/// written onto a READONLY column, and history is not a read grant. A | |
| 46 | -/// parent whose link was revoked (by an unlink or by the student-side role | |
| 47 | -/// sweep) would otherwise keep a live view of the child's seat, watching | |
| 50 | +/// Deliberately **not** `booked_by`: who placed a booking is history | |
| 51 | +/// written onto a fixed column, and history is not a read grant. A parent | |
| 52 | +/// whose link was revoked (by an unlink or by the student-side role sweep) | |
| 53 | +/// would otherwise keep a live view of the child's seat, watching | |
| 48 | 54 | /// cancellations made long after the link died — exactly what |
| 49 | 55 | /// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The |
| 50 | 56 | /// 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 | 61 | limit: Option<i64>, |
| 56 | 62 | offset: i64, |
| 57 | 63 | ) -> Result<(Vec<MealBooking>, i64), AppError> { |
| 58 | - PagedList::new( | |
| 59 | - "meal_booking WHERE student IN $students", | |
| 60 | - "ORDER BY created_at DESC, id DESC", | |
| 61 | - ) | |
| 62 | - .bind( | |
| 63 | - "students", | |
| 64 | - students.iter().map(UserId::record).collect::<Vec<_>>(), | |
| 64 | + if students.is_empty() { | |
| 65 | + return Ok((Vec::new(), 0)); | |
| 66 | + } | |
| 67 | + let keys: Vec<String> = students.iter().map(UserId::key).collect(); | |
| 68 | + let rows = sqlx::query_as!( | |
| 69 | + MealBooking, | |
| 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) | |
| 67 | - .await | |
| 78 | + .fetch_all(db) | |
| 79 | + .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 | 94 | /// Take the seat **and** place the row in one transaction, at the menu |
| 71 | 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) | |
| 74 | -/// pair, so two `POST`s of the same seat both find no row and both claim — | |
| 75 | -/// and on a tight cap the second is then told "full" for a seat it never | |
| 76 | -/// owed, while the winner's row may not even be visible yet. Here the | |
| 77 | -/// duplicate `CREATE` aborts the transaction, which takes its increment with | |
| 78 | -/// it: the counter never counts a row that does not exist, and a loser is | |
| 79 | -/// answered with the winner's booking instead of a refusal. Same shape as | |
| 80 | -/// [`cap::claim_and_create`](crate::db::cap::claim_and_create), with the | |
| 81 | -/// revision guard and the revival of a cancelled row that the general form | |
| 82 | -/// does not carry. | |
| 97 | +/// The seat and the row cannot be two steps. The row key is the (menu, | |
| 98 | +/// student) pair, so two `POST`s of the same seat both find no row and both | |
| 99 | +/// claim — and on a tight cap the second is then told "full" for a seat it | |
| 100 | +/// never owed, while the winner's row may not even be visible yet. Here the | |
| 101 | +/// duplicate insert answers [`Claimed::Duplicate`] and the caller replays | |
| 102 | +/// the winner, while the whole transaction (seat bump included) rolls back | |
| 103 | +/// on any refused path: the counter never counts a row that does not exist. | |
| 104 | +/// Same shape as the [`crate::db::cap`] claim recipe, with the revision | |
| 105 | +/// guard and the revival of a cancelled row that the general form does not | |
| 106 | +/// carry. | |
| 83 | 107 | /// |
| 84 | 108 | /// A cancelled row is revived in place (a fresh attempt at `price`) rather |
| 85 | -/// than recreated: `booked_by` and `created_at` are READONLY history — who | |
| 109 | +/// than recreated: `booked_by` and `created_at` are fixed history — who | |
| 86 | 110 | /// opened the seat, and when. |
| 87 | 111 | /// |
| 88 | 112 | /// **The charge rides this transaction too**, for the same reason the |
| @@ -93,118 +117,135 @@ pub async fn list_for_students( | ||
| 93 | 117 | /// moved past. That is why `row.attempt` is minted by the *caller*: the |
| 94 | 118 | /// charge's id is (seat, attempt), so the number cannot be the revival's own |
| 95 | 119 | /// `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` | |
| 97 | -/// below then finds the row and aborts the whole transaction) rather than | |
| 98 | -/// billing its attempt at this call's id. | |
| 120 | +/// instead, so a rival that revived first loses this claim (the insert below | |
| 121 | +/// then finds the row and answers `Duplicate`) rather than billing its | |
| 122 | +/// attempt at this call's id. | |
| 99 | 123 | /// |
| 100 | -/// The charge is created only if it is not already there — a duplicate | |
| 101 | -/// `CREATE` would abort the transaction and cost the seat, and an attempt | |
| 124 | +/// The charge is created only if it is not already there — an attempt | |
| 102 | 125 | /// billed twice is the one thing money code may never do. |
| 103 | 126 | pub(crate) async fn claim_and_place( |
| 104 | 127 | db: &Database, |
| 105 | - seats: &RecordId, | |
| 128 | + menu: &MenuId, | |
| 106 | 129 | cap: i64, |
| 107 | 130 | seen: i64, |
| 108 | 131 | row: &MealBooking, |
| 109 | 132 | price: Option<LedgerAmount>, |
| 110 | 133 | charge: Option<&MealLedger>, |
| 111 | 134 | ) -> Result<Claimed<MealBooking>, AppError> { |
| 112 | - // Empty when the menu is free: a seat that costs nothing owes no line. | |
| 113 | - let bill = match charge { | |
| 114 | - Some(_) => { | |
| 115 | - "IF array::len((SELECT VALUE id FROM $charge)) = 0 \ | |
| 116 | - { CREATE $charge CONTENT $line };" | |
| 135 | + let menu_key = menu.key().to_string(); | |
| 136 | + let student = row.student; | |
| 137 | + let attempt = row.attempt; | |
| 138 | + tx_with_retry(db, false, async |tx| { | |
| 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 => "", | |
| 119 | - }; | |
| 120 | - // Slots count BEGIN, three LETs, three IFs and — when there is money to | |
| 121 | - // take — the charge's IF, so the RETURN is slot 7 or 8. | |
| 122 | - let returned = if charge.is_some() { 8 } else { 7 }; | |
| 123 | - // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way. | |
| 124 | - let sql = format!( | |
| 125 | - "BEGIN TRANSACTION; | |
| 126 | - LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked'); | |
| 127 | - IF array::len($held) > 0 {{ THROW 'held' }}; | |
| 128 | - LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \ | |
| 129 | - ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \ | |
| 130 | - WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \ | |
| 131 | - AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id); | |
| 132 | - IF array::len($seat) = 0 {{ THROW 'no_seat' }}; | |
| 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 | - { | |
| 153 | + // The seat: one conditional single-row write on the menu, atomic | |
| 154 | + // under Postgres — of the racers only `cap` of them per revision | |
| 155 | + // get a non-empty result, and the rest are refused with nothing | |
| 156 | + // written. | |
| 157 | + let seat = sqlx::query!( | |
| 158 | + "UPDATE menu SET seats_booked = seats_booked + 1 | |
| 159 | + WHERE id = $1 AND seats_booked < $2 AND COALESCE(version, 0) = $3 | |
| 160 | + RETURNING 1 AS seat", | |
| 161 | + menu_key, | |
| 162 | + cap, | |
| 163 | + seen, | |
| 164 | + ) | |
| 165 | + .fetch_optional(&mut *tx) | |
| 166 | + .await?; | |
| 167 | + if seat.is_none() { | |
| 178 | 168 | return Ok(Claimed::Full); |
| 179 | 169 | } |
| 180 | - if errors | |
| 181 | - .values() | |
| 182 | - .any(|error| error.to_string().contains("held") || error.is_already_exists()) | |
| 183 | - { | |
| 170 | + // Revive a cancelled row only while it still stands at the attempt | |
| 171 | + // this call read — the fence that keeps a rival's revival from | |
| 172 | + // being billed at this call's ids. | |
| 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 | 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 | - } | |
| 197 | - Err(AppError::Conflict( | |
| 198 | - "the menu kept changing underneath this booking", | |
| 199 | - )) | |
| 217 | + // The charge rides the same transaction; already there (a replayed | |
| 218 | + // POST of this seat) means fine — nothing is written twice. | |
| 219 | + if let Some(line) = charge { | |
| 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 | 243 | /// Flip the seat to `cancelled` and give it back to the menu's counter **in |
| 203 | 244 | /// one transaction**, so the two can never disagree: a decrement that ran |
| 204 | 245 | /// 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 the | |
| 206 | -/// flip's own result (`array::len`), so a row already cancelled — by a | |
| 207 | -/// racing cancel, or by this call retried — decrements nothing. | |
| 246 | +/// decrement locks a seat nothing can ever release. The decrement rides the | |
| 247 | +/// flip's own result, so a row already cancelled — by a racing cancel, or | |
| 248 | +/// by this call retried — decrements nothing. | |
| 208 | 249 | /// |
| 209 | 250 | /// **The refund rides this transaction too**, and it has to: the flip and a |
| 210 | 251 | /// 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 | 271 | /// reversal id is burnt for good. |
| 231 | 272 | /// |
| 232 | 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 | 274 | pub async fn release_seat( |
| 237 | 275 | db: &Database, |
| 238 | 276 | booked: &MealBooking, |
| 239 | 277 | recorded_by: &UserId, |
| 240 | 278 | ) -> Result<Option<MealBooking>, AppError> { |
| 241 | 279 | let refund = MealLedger::reversal_for(booked, recorded_by); |
| 242 | - // Guarded three ways: nothing was flipped (a rival cancelled first, and | |
| 243 | - // its own transaction carried the refund), the charge never landed, or | |
| 244 | - // this attempt is already refunded — none of which may abort the flip. | |
| 245 | - let reverse = match refund { | |
| 246 | - Some(_) => { | |
| 247 | - "IF array::len($flipped) > 0 \ | |
| 248 | - AND array::len((SELECT VALUE id FROM $charge)) > 0 \ | |
| 249 | - AND array::len((SELECT VALUE id FROM $reversal)) = 0 \ | |
| 250 | - { CREATE $reversal CONTENT $line };" | |
| 251 | - } | |
| 252 | - None => "", | |
| 253 | - }; | |
| 254 | - // Slots count BEGIN, the LET, the seat UPDATE and — when there is money | |
| 255 | - // to give back — the IF. | |
| 256 | - let returned = if refund.is_some() { 4 } else { 3 }; | |
| 257 | - // Same burst on the same counter as the book side, so the same patience | |
| 258 | - // (see [`claim_and_place`]) — a cancel that gave up left the seat | |
| 259 | - // held with the charge standing. Admissible: the round aborts having | |
| 260 | - // written nothing, and a re-send finds the row already `cancelled`, so | |
| 261 | - // the flip matches nothing, the counter moves nothing and the guarded | |
| 262 | - // reversal — keyed to (seat, attempt) — is not written twice. | |
| 263 | - for attempt in 0..CAP_WRITE_TRIES { | |
| 264 | - backoff(attempt).await; | |
| 265 | - let attempted = async { | |
| 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) | |
| 280 | + let menu_key = booked.menu.key().to_string(); | |
| 281 | + let student = booked.student; | |
| 282 | + let attempt = booked.attempt; | |
| 283 | + let cancelled_at = Timestamp::now(); | |
| 284 | + tx_with_retry(db, false, async |tx| { | |
| 285 | + let flipped = sqlx::query_as!( | |
| 286 | + MealBooking, | |
| 287 | + "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 | |
| 288 | + WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 | |
| 289 | + RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", | |
| 290 | + menu_key, | |
| 291 | + student, | |
| 292 | + cancelled_at, | |
| 293 | + attempt, | |
| 294 | + ) | |
| 295 | + .fetch_optional(&mut *tx) | |
| 296 | + .await?; | |
| 297 | + if flipped.is_some() { | |
| 298 | + sqlx::query!( | |
| 299 | + "UPDATE menu SET seats_booked = GREATEST(seats_booked - 1, 0) WHERE id = $1", | |
| 300 | + menu_key, | |
| 301 | + ) | |
| 302 | + .execute(&mut *tx) | |
| 303 | + .await?; | |
| 291 | 304 | } |
| 292 | - .await; | |
| 293 | - match attempted { | |
| 294 | - Ok(rows) => return Ok(rows.into_iter().next()), | |
| 295 | - Err(err) if lost_the_race(&err) => {} | |
| 296 | - Err(err) => return Err(err.into()), | |
| 305 | + // Guarded three ways: nothing was flipped (a rival cancelled first, | |
| 306 | + // and its own transaction carried the refund), the charge never | |
| 307 | + // landed, or this attempt is already refunded — none of which may | |
| 308 | + // abort the flip. | |
| 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 | - } | |
| 299 | - Err(AppError::Conflict( | |
| 300 | - "the menu kept changing underneath this cancellation", | |
| 301 | - )) | |
| 342 | + Ok(flipped) | |
| 343 | + }) | |
| 344 | + .await | |
| 302 | 345 | } |
| 303 | - | |
| 304 | 346 | #[cfg(test)] |
| 305 | 347 | mod tests { |
| 306 | 348 | use super::*; |
src/db/meal_ledger.rsmodified+64 -77
| @@ -3,29 +3,14 @@ | ||
| 3 | 3 | //! convention live in [`crate::domain::meal_ledger`]; the charge/reversal |
| 4 | 4 | //! and credit workflows that sequence these in [`crate::service::meal_ledger`]. |
| 5 | 5 | |
| 6 | -use surrealdb::types::{AlreadyExistsError, SurrealValue}; | |
| 7 | - | |
| 8 | -use crate::constant::{CAS_UPDATE_RETRIES, MEAL_LEDGER_TABLE}; | |
| 9 | -use crate::database::{Database, lost_the_race}; | |
| 10 | -use crate::db::menu_dish; | |
| 6 | +use crate::database::Database; | |
| 11 | 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 | 9 | use crate::domain::menu::MenuId; |
| 14 | 10 | use crate::domain::user::UserId; |
| 15 | 11 | use crate::error::AppError; |
| 16 | 12 | |
| 17 | -/// Did this `CREATE` fail *only* because the row is already there? Matched on | |
| 18 | -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text | |
| 19 | -/// and never on "any database error", because swallowing a real fault in money | |
| 20 | -/// code would be far worse than the 500 it saves. | |
| 21 | -fn is_duplicate_record(error: &surrealdb::Error) -> bool { | |
| 22 | - matches!( | |
| 23 | - error.already_exists_details(), | |
| 24 | - Some(AlreadyExistsError::Record { .. }) | |
| 25 | - ) | |
| 26 | -} | |
| 27 | - | |
| 28 | -/// The only writer: one `CREATE`, no update path anywhere in this module. | |
| 13 | +/// The only writer: one `INSERT`, no update path anywhere in this module. | |
| 29 | 14 | /// |
| 30 | 15 | /// A line whose id already exists is left exactly as it is — the row wins, |
| 31 | 16 | /// 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 | 18 | /// append is a no-op, never a second line and never an edit of the first. |
| 34 | 19 | /// The point read is on the id itself, so unlike a scan it cannot miss a |
| 35 | 20 | /// row a concurrent writer just made — but it is only a fast path. The |
| 36 | -/// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves | |
| 37 | -/// the row untouched, so the writer that lost the race reads back the | |
| 38 | -/// winner's line instead of failing the request with a 500. | |
| 39 | -/// | |
| 40 | -/// A *write conflict* is the same race decided one layer down — two | |
| 41 | -/// appends of one id arriving together are no longer serialized by a | |
| 42 | -/// process-wide lock, so the store aborts one as retryable instead of | |
| 43 | -/// answering it "already exists". Both are read back the same way, and a | |
| 44 | -/// conflict that turns out to have written nothing is simply tried again; | |
| 45 | -/// no path here can write a second line, since the id is the key. | |
| 21 | +/// guarantee is the insert's own `ON CONFLICT (id) DO NOTHING`: on an | |
| 22 | +/// existing id nothing is written, so the writer that lost the race reads | |
| 23 | +/// back the winner's line instead of failing the request with a 500. | |
| 46 | 24 | pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, AppError> { |
| 47 | 25 | if let Some(existing) = read(db, &row.id).await? { |
| 48 | 26 | return Ok(existing); |
| 49 | 27 | } |
| 50 | - let id = row.id.clone(); | |
| 51 | - for _ in 0..CAS_UPDATE_RETRIES { | |
| 52 | - match db.create(id.record()).content(row.clone()).await { | |
| 53 | - Ok(Some(created)) => return Ok(created), | |
| 54 | - Ok(None) => break, | |
| 55 | - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | |
| 56 | - if let Some(existing) = read(db, &id).await? { | |
| 57 | - return Ok(existing); | |
| 58 | - } | |
| 59 | - } | |
| 60 | - Err(e) => return Err(e.into()), | |
| 61 | - } | |
| 28 | + let inserted = sqlx::query_as!( | |
| 29 | + MealLedger, | |
| 30 | + "INSERT INTO meal_ledger | |
| 31 | + (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) | |
| 32 | + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) | |
| 33 | + ON CONFLICT (id) DO NOTHING | |
| 34 | + RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at", | |
| 35 | + row.id.key(), | |
| 36 | + row.student, | |
| 37 | + row.kind, | |
| 38 | + row.amount_minor, | |
| 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 | 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 | 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 | 76 | db: &Database, |
| 78 | 77 | menu: &MenuId, |
| 79 | 78 | ) -> Result<Option<LedgerAmount>, AppError> { |
| 80 | - let total = menu_dish::list_for_menu(db, menu) | |
| 81 | - .await? | |
| 82 | - .iter() | |
| 83 | - .fold(0i64, |sum, dish| { | |
| 84 | - sum.saturating_add(dish.get_price_minor().as_minor()) | |
| 85 | - }); | |
| 79 | + let row = | |
| 80 | + sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key()) | |
| 81 | + .fetch_one(db) | |
| 82 | + .await?; | |
| 83 | + let total = row.total; | |
| 86 | 84 | if total == 0 { |
| 87 | 85 | return Ok(None); |
| 88 | 86 | } |
| @@ -97,10 +95,10 @@ pub async fn list_for_student( | ||
| 97 | 95 | offset: i64, |
| 98 | 96 | ) -> Result<(Vec<MealLedger>, i64), AppError> { |
| 99 | 97 | PagedList::new( |
| 100 | - "meal_ledger WHERE student = $student", | |
| 98 | + "meal_ledger WHERE student = $1", | |
| 101 | 99 | "ORDER BY created_at DESC, id DESC", |
| 102 | 100 | ) |
| 103 | - .bind("student", student.record()) | |
| 101 | + .bind(student.key()) | |
| 104 | 102 | .run(limit, offset, db) |
| 105 | 103 | .await |
| 106 | 104 | } |
| @@ -118,38 +116,27 @@ pub async fn list_for_student( | ||
| 118 | 116 | /// every later `GET /meals/balance/*`. |
| 119 | 117 | /// |
| 120 | 118 | /// **The signs stay on the kind**, applied by the very |
| 121 | -/// [`MealLedgerKind::sign`] | |
| 122 | -/// the documented formula is spelled in. Summing `IF kind = 'charge' THEN | |
| 123 | -/// -amount …` in SQL would have folded the whole balance in one statement | |
| 124 | -/// and forked the one rule that decides what money means into a second | |
| 125 | -/// language, where nothing would fail the day the two disagreed. Grouping | |
| 126 | -/// instead keeps the aggregate ignorant of signs: it counts kinds, and | |
| 127 | -/// Rust still says what a kind does. A stored running total was the third | |
| 128 | -/// option and is a counter that can drift — a bug class this repo closes, | |
| 129 | -/// not one it opens. | |
| 119 | +/// [`MealLedgerKind::sign`](crate::domain::meal_ledger::MealLedgerKind::sign) | |
| 120 | +/// the documented formula is spelled in. Summing a signed CASE in SQL would | |
| 121 | +/// have folded the whole balance in one statement and forked the one rule | |
| 122 | +/// that decides what money means into a second language, where nothing | |
| 123 | +/// would fail the day the two disagreed. Grouping instead keeps the | |
| 124 | +/// aggregate ignorant of signs: it counts kinds, and Rust still says what a | |
| 125 | +/// kind does. A stored running total was the third option and is a counter | |
| 126 | +/// that can drift — a bug class this repo closes, not one it opens. | |
| 130 | 127 | pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { |
| 131 | - let totals: Vec<KindTotal> = db | |
| 132 | - .query(format!( | |
| 133 | - "SELECT kind, math::sum(amount_minor) AS total \ | |
| 134 | - FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" | |
| 135 | - )) | |
| 136 | - .bind(("student", student.record())) | |
| 137 | - .await? | |
| 138 | - .check()? | |
| 139 | - .take(0)?; | |
| 128 | + let totals = sqlx::query!( | |
| 129 | + r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", | |
| 130 | + CAST(sum(amount_minor) AS BIGINT) AS total | |
| 131 | + FROM meal_ledger WHERE student = $1 GROUP BY kind"#, | |
| 132 | + *student, | |
| 133 | + ) | |
| 134 | + .fetch_all(db) | |
| 135 | + .await?; | |
| 140 | 136 | Ok(totals |
| 141 | 137 | .iter() |
| 142 | 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 | 140 | #[cfg(test)] |
| 154 | 141 | mod tests { |
| 155 | 142 | use super::*; |
src/db/menu.rsmodified+173 -205
| @@ -1,100 +1,33 @@ | ||
| 1 | 1 | //! The `menu` table: publishing (the slot reference claimed inside the |
| 2 | 2 | //! write's own transaction), row reads and listings, the compare-and-set |
| 3 | -//! every cap PATCH writes through, the cascading delete, and | |
| 4 | -//! [`bump_menu_and_write`] — the shared "write the menu row too" shape every | |
| 5 | -//! child write (a dish, an attendance mark) uses so nothing can outlive its | |
| 6 | -//! menu. The kitchen workflows — the dish cap under | |
| 7 | -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) — live in | |
| 3 | +//! every cap PATCH writes through, and the cascading delete. The kitchen | |
| 4 | +//! workflows — the guarded dish-cap insert — live in | |
| 8 | 5 | //! [`crate::service::menu`]. |
| 9 | 6 | |
| 10 | -use surrealdb::types::{SurrealValue, Value}; | |
| 11 | - | |
| 12 | -use crate::constant::{ | |
| 13 | - MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, | |
| 14 | - REF_COUNT_FIELD, | |
| 15 | -}; | |
| 16 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | |
| 17 | -use crate::db::cap; | |
| 18 | -use crate::db::page::PagedList; | |
| 7 | +use crate::database::{Database, tx_with_retry, unique_violation}; | |
| 8 | +use crate::db::page::{PagedList, Param}; | |
| 19 | 9 | use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref}; |
| 20 | 10 | use crate::domain::timestamp::Timestamp; |
| 21 | 11 | use crate::domain::user::UserId; |
| 22 | 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 | 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 the | |
| 93 | -/// refusal is decided by the store rather than by a check a concurrent | |
| 94 | -/// publish can outrun: two publishes of the same meal write one id, and the loser's | |
| 95 | -/// "already exists" becomes the same 409. The pre-check stays for the | |
| 96 | -/// ordinary case — and for menus published before ids were derived, whose | |
| 97 | -/// ULID key no new publish can collide with. | |
| 16 | +/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so | |
| 17 | +/// the refusal is decided by the store rather than by a check a concurrent | |
| 18 | +/// publish can outrun: two publishes of the same meal write one row, and | |
| 19 | +/// the loser's unique violation on `menu_pkey` becomes the same 409. The | |
| 20 | +/// in-transaction pre-check stays for the ordinary case. | |
| 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 | 31 | pub async fn create( |
| 99 | 32 | db: &Database, |
| 100 | 33 | date: MenuDate, |
| @@ -102,39 +35,80 @@ pub async fn create( | ||
| 102 | 35 | capacity: Option<i64>, |
| 103 | 36 | created_by: &UserId, |
| 104 | 37 | ) -> Result<Menu, AppError> { |
| 105 | - let taken = AppError::Conflict("a menu is already published for that date and slot"); | |
| 106 | - if find(db, &date, &slot).await?.is_some() { | |
| 107 | - return Err(taken); | |
| 108 | - } | |
| 109 | - // The menu takes a reference on its slot, which is what stops the slot | |
| 110 | - // being dropped from the settings while this menu (whose slot is only | |
| 111 | - // snapshotted text) still points at it. Claimed *inside* the write's own | |
| 112 | - // transaction: a claim of its own could land and the row then fail to, | |
| 113 | - // leaving the slot counted by a menu that does not exist — a slot | |
| 114 | - // nobody can ever retire, and no crash window is small enough for that. | |
| 38 | + let id_key = MenuId::for_slot(&date, &slot).key().to_string(); | |
| 115 | 39 | let counter = slot_ref(slot.as_str()); |
| 116 | - let menu = Menu { | |
| 117 | - id: MenuId::for_slot(&date, &slot), | |
| 118 | - date, | |
| 119 | - slot, | |
| 120 | - capacity, | |
| 121 | - version: Some(0), | |
| 122 | - created_by: created_by.clone(), | |
| 123 | - created_at: Timestamp::now(), | |
| 124 | - }; | |
| 125 | - let id = menu.id.record(); | |
| 126 | - match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { | |
| 127 | - cap::ClaimedRef::Made(created) => Ok(created), | |
| 128 | - cap::ClaimedRef::Duplicate => Err(taken), | |
| 129 | - cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( | |
| 130 | - "the '{}' meal slot has been removed from the school's settings", | |
| 131 | - menu.slot.as_str() | |
| 132 | - ))), | |
| 133 | - } | |
| 40 | + let date_s = date.as_str().to_string(); | |
| 41 | + let slot_s = slot.as_str().to_string(); | |
| 42 | + let created_by = *created_by; | |
| 43 | + let created_at = Timestamp::now(); | |
| 44 | + tx_with_retry(db, false, async |tx| { | |
| 45 | + // Duplicate gate ahead of the retired check: "already published" | |
| 46 | + // outranks "slot retired", on the very path a rival publish races. | |
| 47 | + let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) | |
| 48 | + .fetch_optional(&mut *tx) | |
| 49 | + .await?; | |
| 50 | + if exists.is_some() { | |
| 51 | + return Err(AppError::Conflict( | |
| 52 | + "a menu is already published for that date and slot", | |
| 53 | + )); | |
| 54 | + } | |
| 55 | + let inserted = match sqlx::query_as!( | |
| 56 | + Menu, | |
| 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 | 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 | 114 | /// The menu for one day and slot, if any — the uniqueness check. |
| @@ -143,18 +117,21 @@ pub async fn find( | ||
| 143 | 117 | date: &MenuDate, |
| 144 | 118 | slot: &MenuSlot, |
| 145 | 119 | ) -> Result<Option<Menu>, AppError> { |
| 146 | - let mut result = db | |
| 147 | - .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") | |
| 148 | - .bind(("date", date.as_str().to_string())) | |
| 149 | - .bind(("slot", slot.as_str().to_string())) | |
| 150 | - .await? | |
| 151 | - .check()?; | |
| 152 | - Ok(result.take::<Vec<Menu>>(0)?.into_iter().next()) | |
| 120 | + let row = sqlx::query_as!( | |
| 121 | + Menu, | |
| 122 | + "SELECT id, date, slot, capacity, version, created_by, created_at | |
| 123 | + FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", | |
| 124 | + date.as_str(), | |
| 125 | + slot.as_str(), | |
| 126 | + ) | |
| 127 | + .fetch_optional(db) | |
| 128 | + .await?; | |
| 129 | + Ok(row) | |
| 153 | 130 | } |
| 154 | 131 | |
| 155 | 132 | /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; |
| 156 | -/// either may be omitted. The comparison is lexical, which is chronological | |
| 157 | -/// for this format. | |
| 133 | +/// either may be omitted (`NULL` bound). The comparison is lexical, which | |
| 134 | +/// is chronological for this format. | |
| 158 | 135 | pub async fn list( |
| 159 | 136 | db: &Database, |
| 160 | 137 | from: Option<&MenuDate>, |
| @@ -163,25 +140,26 @@ pub async fn list( | ||
| 163 | 140 | offset: i64, |
| 164 | 141 | ) -> Result<(Vec<Menu>, i64), AppError> { |
| 165 | 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 | 145 | "ORDER BY date DESC, slot ASC, id DESC", |
| 168 | 146 | ) |
| 169 | - .bind("from", from.map(|date| date.as_str().to_string())) | |
| 170 | - .bind("to", to.map(|date| date.as_str().to_string())) | |
| 147 | + .bind(Param::OptText(from.map(|date| date.as_str().to_string()))) | |
| 148 | + .bind(Param::OptText(to.map(|date| date.as_str().to_string()))) | |
| 171 | 149 | .run(limit, offset, db) |
| 172 | 150 | .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 | 154 | /// because moving a published menu to another day is a different menu. |
| 177 | 155 | /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. |
| 178 | 156 | /// |
| 179 | 157 | /// The revision moves **in the same statement** as the cap, indivisibly: a |
| 180 | -/// booking claims its seat against the revision | |
| 181 | -/// it read the cap at, so a shrink that bumped in a query of its own left a | |
| 182 | -/// window where the row carried the *new* revision and the *old* cap — and | |
| 183 | -/// a booking arriving there passes a CAS meant to refuse it, over-admitting | |
| 184 | -/// by exactly the seats in flight. | |
| 158 | +/// booking claims its seat against the revision it read the cap at, so a | |
| 159 | +/// shrink that bumped in a query of its own left a window where the row | |
| 160 | +/// carried the *new* revision and the *old* cap — and a booking arriving | |
| 161 | +/// there passes a CAS meant to refuse it, over-admitting by exactly the | |
| 162 | +/// seats in flight. | |
| 185 | 163 | pub async fn update( |
| 186 | 164 | db: &Database, |
| 187 | 165 | menu: Menu, |
| @@ -192,99 +170,89 @@ pub async fn update( | ||
| 192 | 170 | // booking's price or cap has moved, so none owes a re-read. |
| 193 | 171 | return read(db, &menu.id).await?.ok_or(AppError::NotFound); |
| 194 | 172 | }; |
| 195 | - let sql = format!( | |
| 196 | - "UPDATE $id SET capacity = $capacity, \ | |
| 197 | - {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" | |
| 198 | - ); | |
| 199 | - // One counter write in flight at a time, like every other one. | |
| 200 | - let _guard = cap::counter_lock().await; | |
| 201 | - write_with_retry::<Menu>( | |
| 202 | - db, | |
| 203 | - &sql, | |
| 204 | - &[ | |
| 205 | - ("id".into(), menu.id.record().into_value()), | |
| 206 | - ("capacity".into(), capacity.into_value()), | |
| 207 | - ], | |
| 173 | + let row = sqlx::query_as!( | |
| 174 | + Menu, | |
| 175 | + "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 | |
| 176 | + WHERE id = $1 | |
| 177 | + RETURNING id, date, slot, capacity, version, created_by, created_at", | |
| 178 | + menu.id.key(), | |
| 179 | + capacity, | |
| 208 | 180 | ) |
| 209 | - .await? | |
| 210 | - .into_iter() | |
| 211 | - .next() | |
| 212 | - .ok_or(AppError::NotFound) | |
| 181 | + .fetch_optional(db) | |
| 182 | + .await?; | |
| 183 | + row.ok_or(AppError::NotFound) | |
| 213 | 184 | } |
| 214 | 185 | |
| 215 | -/// Delete the menu and the dishes on it — a dish has no meaning without | |
| 216 | -/// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. | |
| 186 | +/// Delete the menu and the dishes and marks on it — a dish or a mark has | |
| 187 | +/// no meaning without its menu, and the menu key cannot be re-homed. | |
| 217 | 188 | /// |
| 218 | 189 | /// Refused (409) while a seat is still held, and the *row itself* decides |
| 219 | 190 | /// that: the delete carries the seat counter in its `WHERE`, so a booking |
| 220 | -/// landing at that instant either takes its seat before | |
| 221 | -/// the delete (which then finds a non-zero counter and refuses) or after it | |
| 222 | -/// (and finds no menu). A read-then-delete pair had a window where both | |
| 223 | -/// happened — a paid seat on a menu that no longer exists. | |
| 191 | +/// landing at that instant either takes its seat before the delete (which | |
| 192 | +/// then finds a non-zero counter and refuses) or after it (and finds no | |
| 193 | +/// menu). A read-then-delete pair had a window where both happened — a | |
| 194 | +/// paid seat on a menu that no longer exists. | |
| 224 | 195 | /// |
| 225 | 196 | /// The slot gets its reference back in that same transaction — a slot no |
| 226 | -/// menu is published for any more may leave the settings again, and the | |
| 227 | -/// `FOR` runs only over a row the guard actually took. Released afterwards | |
| 228 | -/// in a query of its own, a crash between the two left the slot counted by | |
| 229 | -/// a menu that no longer exists: a slot nobody can retire. | |
| 197 | +/// menu is published for any more may leave the settings again. Released | |
| 198 | +/// afterwards in a statement of its own, a crash between the two left the | |
| 199 | +/// slot counted by 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 | 202 | /// [`MenuId::for_slot`] is deterministic, so republishing the same day and |
| 233 | -/// slot mints the *same* record id. A mark left behind would come back as a | |
| 203 | +/// slot mints the *same* row key. A mark left behind would come back as a | |
| 234 | 204 | /// mark on the new menu — the kitchen reading "served" for a student who |
| 235 | 205 | /// never came — and until then the student's own report cites a menu that |
| 236 | 206 | /// is gone. Attendance carries no money and no counter, so it is safe to |
| 237 | -/// drop; cancelled *bookings* deliberately stay, because their `attempt` | |
| 238 | -/// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut | |
| 207 | +/// drop; cancelled *bookings* deliberately stay (no foreign key ties them | |
| 208 | +/// to the menu), because their `attempt` counter is what keeps the | |
| 209 | +/// ledger's `(booking, attempt)` keys unique across the republish. Cut | |
| 239 | 210 | /// those and a re-book on a republished menu would reuse a charge id the |
| 240 | 211 | /// ledger already holds, and the append (idempotent by design) would bill |
| 241 | 212 | /// the seat nothing. |
| 242 | 213 | /// |
| 243 | -/// The dishes ride in that `FOR` too, and for the same reason as the marks: | |
| 244 | -/// run after the transaction committed, a crash between the two orphaned | |
| 245 | -/// them on a record id republishing the day and slot mints again — a new | |
| 246 | -/// menu serving (and pricing) the old one's food. | |
| 214 | +/// The dishes ride in the same sweep: run after the commit, a crash | |
| 215 | +/// between the two would orphan them on the row key a republish mints | |
| 216 | +/// again — a new menu serving (and pricing) the old one's food. | |
| 247 | 217 | pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { |
| 248 | - let sql = format!( | |
| 249 | - "BEGIN TRANSACTION; | |
| 250 | - LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); | |
| 251 | - FOR $row IN ($gone ?? []) {{ | |
| 252 | - UPSERT $counter SET {REF_COUNT_FIELD} = \ | |
| 253 | - math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); | |
| 254 | - DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; | |
| 255 | - DELETE {MENU_DISH_TABLE} WHERE menu = $id; | |
| 256 | - }}; | |
| 257 | - RETURN $gone; | |
| 258 | - COMMIT TRANSACTION;" | |
| 259 | - ); | |
| 260 | - // `slot` is a `READONLY` column, so this counter is the one the deleted | |
| 261 | - // row carries. Nothing here can answer "already exists" — the `UPSERT` | |
| 262 | - // is keyed by a slot name on a table with no `UNIQUE` index, so it | |
| 263 | - // resolves onto the row it names ([`transaction_with_retry`]). | |
| 264 | - let (mut result, mut errors) = transaction_with_retry( | |
| 265 | - db, | |
| 266 | - &sql, | |
| 267 | - &[ | |
| 268 | - ("id".into(), menu.id.record().into_value()), | |
| 269 | - ("counter".into(), slot_ref(menu.slot.as_str()).into_value()), | |
| 270 | - ], | |
| 271 | - &[], | |
| 272 | - ) | |
| 218 | + let key = menu.id.key().to_string(); | |
| 219 | + let counter = slot_ref(menu.slot.as_str()); | |
| 220 | + let deleted = tx_with_retry(db, true, async |tx| { | |
| 221 | + let deleted = sqlx::query_as!( | |
| 222 | + Menu, | |
| 223 | + "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 | |
| 224 | + RETURNING id, date, slot, capacity, version, created_by, created_at", | |
| 225 | + key, | |
| 226 | + ) | |
| 227 | + .fetch_optional(&mut *tx) | |
| 228 | + .await?; | |
| 229 | + let Some(row) = deleted else { | |
| 230 | + return Ok(None); | |
| 231 | + }; | |
| 232 | + sqlx::query!( | |
| 233 | + "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1", | |
| 234 | + counter, | |
| 235 | + ) | |
| 236 | + .execute(&mut *tx) | |
| 237 | + .await?; | |
| 238 | + sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) | |
| 239 | + .execute(&mut *tx) | |
| 240 | + .await?; | |
| 241 | + sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) | |
| 242 | + .execute(&mut *tx) | |
| 243 | + .await?; | |
| 244 | + Ok(Some(row)) | |
| 245 | + }) | |
| 273 | 246 | .await?; |
| 274 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 275 | - return Err(error.into()); | |
| 276 | - } | |
| 277 | - // BEGIN, the LET and the FOR take a slot each. | |
| 278 | - let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else { | |
| 247 | + match deleted { | |
| 248 | + Some(menu) => Ok(menu), | |
| 279 | 249 | // Nothing back: either seats are held, or the menu is already gone. |
| 280 | - return Err(match read(db, &menu.id).await? { | |
| 281 | - Some(_) => AppError::Conflict("the menu still has live bookings"), | |
| 282 | - None => AppError::NotFound, | |
| 283 | - }); | |
| 284 | - }; | |
| 285 | - Ok(deleted) | |
| 250 | + None => match read(db, &menu.id).await? { | |
| 251 | + Some(_) => Err(AppError::Conflict("the menu still has live bookings")), | |
| 252 | + None => Err(AppError::NotFound), | |
| 253 | + }, | |
| 254 | + } | |
| 286 | 255 | } |
| 287 | - | |
| 288 | 256 | #[cfg(test)] |
| 289 | 257 | mod tests { |
| 290 | 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 field | |
| 2 | -//! PATCH riding the menu's revision bump ([`bump_menu_and_write`]), the | |
| 3 | -//! reads and listings, and the delete. The dish-cap gate and the | |
| 4 | -//! [`MENU_LOCK`](crate::service::menu::MENU_LOCK) leases live in | |
| 5 | -//! [`crate::service::menu`]. | |
| 1 | +//! The `menu_dish` table: the dishes on a menu — the guarded insert (the | |
| 2 | +//! dish cap, enforced by the menu row's own lock), the field PATCH riding | |
| 3 | +//! the menu's revision bump, the reads and listings, and the delete. The | |
| 4 | +//! kitchen workflows live in [`crate::service::menu`]. | |
| 6 | 5 | |
| 7 | -use surrealdb::types::{SurrealValue, Value}; | |
| 8 | - | |
| 9 | -use crate::constant::MENU_VERSION_FIELD; | |
| 10 | -use crate::database::{Database, transaction_with_retry}; | |
| 11 | -use crate::db::menu::bump_menu_and_write; | |
| 6 | +use crate::database::{Database, tx_with_retry}; | |
| 12 | 7 | use crate::domain::menu::MenuId; |
| 13 | 8 | use crate::domain::menu_dish::{ |
| 14 | 9 | DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, |
| @@ -16,7 +11,15 @@ use crate::domain::menu_dish::{ | ||
| 16 | 11 | use crate::domain::timestamp::Timestamp; |
| 17 | 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 | 23 | pub async fn create( |
| 21 | 24 | db: &Database, |
| 22 | 25 | menu: &MenuId, |
| @@ -24,67 +27,67 @@ pub async fn create( | ||
| 24 | 27 | description: Option<DishDescription>, |
| 25 | 28 | price_minor: DishPrice, |
| 26 | 29 | tags: DishTags, |
| 30 | + cap: i64, | |
| 27 | 31 | ) -> Result<MenuDish, AppError> { |
| 28 | - let dish = MenuDish { | |
| 29 | - id: MenuDishId::generate(), | |
| 30 | - menu: menu.clone(), | |
| 31 | - name, | |
| 32 | - description, | |
| 33 | - price_minor, | |
| 34 | - tags, | |
| 35 | - created_at: Timestamp::now(), | |
| 36 | - }; | |
| 37 | - // The revision bump and the insert are one transaction, and the bump is | |
| 38 | - // what makes the menu's existence part of it: the `UPDATE` matches | |
| 39 | - // nothing once the menu row is deleted, and a delete racing this one | |
| 40 | - // touches the very key this transaction writes, so the two cannot both | |
| 41 | - // commit. Without that, a dish landing just after `DELETE /menus/{id}` | |
| 42 | - // removed the row but before its cascade ran outlived its menu. | |
| 43 | - // Every other dish write bumps the same version key, so a lost round is | |
| 44 | - // ordinary here; it is re-sent rather than reported. Re-sending is sound | |
| 45 | - // even with the `CREATE` in the batch — the abort wrote nothing, the id | |
| 46 | - // is a ULID freshly generated above and never seen by a rival, and | |
| 47 | - // `menu_dish` carries no UNIQUE index — so the retry cannot answer | |
| 48 | - // "already exists" (see [`transaction_with_retry`]). | |
| 49 | - let (mut result, mut errors) = transaction_with_retry( | |
| 50 | - db, | |
| 51 | - &format!( | |
| 52 | - "BEGIN TRANSACTION; | |
| 53 | - LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ | |
| 54 | - ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); | |
| 55 | - IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; | |
| 56 | - CREATE $id CONTENT $dish; | |
| 57 | - COMMIT TRANSACTION;" | |
| 58 | - ), | |
| 59 | - &[ | |
| 60 | - ("menu".into(), menu.record().into_value()), | |
| 61 | - ("id".into(), dish.id.record().into_value()), | |
| 62 | - ("dish".into(), dish.into_value()), | |
| 63 | - ], | |
| 64 | - &["no_menu"], | |
| 65 | - ) | |
| 66 | - .await?; | |
| 67 | - // An aborted transaction errors *every* slot, most with a generic "not | |
| 68 | - // executed" — only the THROW's own slot names the reason. | |
| 69 | - if errors | |
| 70 | - .values() | |
| 71 | - .any(|error| error.to_string().contains("no_menu")) | |
| 72 | - { | |
| 73 | - return Err(AppError::NotFound); | |
| 74 | - } | |
| 75 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 76 | - return Err(error.into()); | |
| 77 | - } | |
| 78 | - // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. | |
| 79 | - result | |
| 80 | - .take::<Vec<MenuDish>>(3)? | |
| 81 | - .into_iter() | |
| 82 | - .next() | |
| 83 | - .ok_or_else(|| AppError::Internal("failed to add the dish".into())) | |
| 32 | + let menu_key = menu.key().to_string(); | |
| 33 | + let id = MenuDishId::generate(); | |
| 34 | + let created_at = Timestamp::now(); | |
| 35 | + tx_with_retry(db, false, async |tx| { | |
| 36 | + // The lock first: every later statement in this transaction then | |
| 37 | + // sees the committed state of whoever queued ahead of it. | |
| 38 | + let locked = sqlx::query!( | |
| 39 | + "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE", | |
| 40 | + menu_key, | |
| 41 | + ) | |
| 42 | + .fetch_optional(&mut *tx) | |
| 43 | + .await?; | |
| 44 | + if locked.is_none() { | |
| 45 | + return Err(AppError::NotFound); | |
| 46 | + } | |
| 47 | + sqlx::query!( | |
| 48 | + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1", | |
| 49 | + menu_key, | |
| 50 | + ) | |
| 51 | + .execute(&mut *tx) | |
| 52 | + .await?; | |
| 53 | + let placed = sqlx::query_as!( | |
| 54 | + MenuDish, | |
| 55 | + "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) | |
| 56 | + SELECT $1, $2, $3, $4, $5, $6, $7 | |
| 57 | + WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 | |
| 58 | + RETURNING id, menu, name, description, price_minor, tags, created_at", | |
| 59 | + id, | |
| 60 | + menu_key, | |
| 61 | + name, | |
| 62 | + description, | |
| 63 | + price_minor, | |
| 64 | + tags, | |
| 65 | + created_at, | |
| 66 | + cap, | |
| 67 | + ) | |
| 68 | + .fetch_optional(&mut *tx) | |
| 69 | + .await?; | |
| 70 | + match placed { | |
| 71 | + Some(dish) => Ok(dish), | |
| 72 | + // The menu exists (locked above), so an empty result is the cap. | |
| 73 | + None => Err(AppError::Conflict( | |
| 74 | + "the menu already carries the maximum number of dishes", | |
| 75 | + )), | |
| 76 | + } | |
| 77 | + }) | |
| 78 | + .await | |
| 84 | 79 | } |
| 85 | 80 | |
| 86 | 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 | 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 | 101 | if menus.is_empty() { |
| 99 | 102 | return Ok(Vec::new()); |
| 100 | 103 | } |
| 101 | - let mut result = db | |
| 102 | - .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") | |
| 103 | - .bind(( | |
| 104 | - "menus", | |
| 105 | - menus.iter().map(MenuId::record).collect::<Vec<_>>(), | |
| 106 | - )) | |
| 107 | - .await? | |
| 108 | - .check()?; | |
| 109 | - Ok(result.take::<Vec<MenuDish>>(0)?) | |
| 110 | -} | |
| 111 | - | |
| 112 | -/// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. | |
| 113 | -pub async fn count_for_menu(db: &Database, menu: &MenuId) -> Result<usize, AppError> { | |
| 114 | - Ok(list_for_menu(db, menu).await?.len()) | |
| 104 | + let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect(); | |
| 105 | + let rows = sqlx::query_as!( | |
| 106 | + MenuDish, | |
| 107 | + "SELECT id, menu, name, description, price_minor, tags, created_at | |
| 108 | + FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", | |
| 109 | + keys, | |
| 110 | + ) | |
| 111 | + .fetch_all(db) | |
| 112 | + .await?; | |
| 113 | + Ok(rows) | |
| 115 | 114 | } |
| 116 | 115 | |
| 117 | 116 | /// Write only the fields the PATCH carried. `description` is nullable, so |
| 118 | 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 by | |
| 121 | -/// [`FieldUpdate`](crate::db::field_update::FieldUpdate) because the | |
| 122 | -/// revision bump lands on *another* row and has to share this write's | |
| 123 | -/// transaction; the field-by-field scoping — an omitted field is never | |
| 124 | -/// written, so a concurrent PATCH of another one is not reverted — is the | |
| 125 | -/// same rule, spelled out. | |
| 122 | +/// The revision bump lands in the same transaction — "every dish write | |
| 123 | +/// bumps" is the rule a caller can rely on without knowing which fields | |
| 124 | +/// were on the wire. A PATCH that carried nothing still bumps and reads | |
| 125 | +/// the row back. | |
| 126 | 126 | pub async fn update( |
| 127 | 127 | db: &Database, |
| 128 | 128 | dish: MenuDish, |
| @@ -131,45 +131,68 @@ pub async fn update( | ||
| 131 | 131 | price_minor: Option<DishPrice>, |
| 132 | 132 | tags: Option<DishTags>, |
| 133 | 133 | ) -> Result<MenuDish, AppError> { |
| 134 | - let mut sets: Vec<&str> = Vec::new(); | |
| 135 | - let mut bindings: Vec<(String, Value)> = vec![("id".into(), dish.id.record().into_value())]; | |
| 136 | - let mut set = |field: &'static str, value: Option<Value>| { | |
| 137 | - if let Some(value) = value { | |
| 138 | - sets.push(field); | |
| 139 | - bindings.push((field.into(), value)); | |
| 134 | + let dish_key = dish.id.key(); | |
| 135 | + let menu_key = dish.menu.key().to_string(); | |
| 136 | + tx_with_retry(db, false, async |tx| { | |
| 137 | + let bumped = sqlx::query!( | |
| 138 | + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | |
| 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 | - }; | |
| 142 | - set("name", name.map(SurrealValue::into_value)); | |
| 143 | - set("description", description.map(SurrealValue::into_value)); | |
| 144 | - set("price_minor", price_minor.map(SurrealValue::into_value)); | |
| 145 | - set("tags", tags.map(SurrealValue::into_value)); | |
| 146 | - // A PATCH that carried nothing writes nothing and reads the row back, | |
| 147 | - // exactly as `FieldUpdate` answers one — but it still moves the | |
| 148 | - // revision, because "every dish write bumps" is the rule a caller can | |
| 149 | - // rely on without knowing which fields were on the wire. | |
| 150 | - let statement = if sets.is_empty() { | |
| 151 | - "SELECT * FROM $id".to_string() | |
| 152 | - } else { | |
| 153 | - format!( | |
| 154 | - "UPDATE $id SET {} RETURN AFTER", | |
| 155 | - sets.iter() | |
| 156 | - .map(|field| format!("{field} = ${field}")) | |
| 157 | - .collect::<Vec<_>>() | |
| 158 | - .join(", ") | |
| 147 | + let row = sqlx::query_as!( | |
| 148 | + MenuDish, | |
| 149 | + "UPDATE menu_dish SET | |
| 150 | + name = COALESCE($2, name), | |
| 151 | + description = CASE WHEN $3 THEN $4 ELSE description END, | |
| 152 | + price_minor = COALESCE($5, price_minor), | |
| 153 | + tags = COALESCE($6, tags) | |
| 154 | + WHERE id = $1 | |
| 155 | + RETURNING id, menu, name, description, price_minor, tags, created_at", | |
| 156 | + dish_key, | |
| 157 | + name.map(|n| n.as_str().to_string()), | |
| 158 | + description.is_some(), | |
| 159 | + description | |
| 160 | + .clone() | |
| 161 | + .flatten() | |
| 162 | + .map(|d| d.as_str().to_string()), | |
| 163 | + price_minor.map(DishPrice::as_minor), | |
| 164 | + tags.map(|t| t.as_slice().to_vec()), | |
| 159 | 165 | ) |
| 160 | - }; | |
| 161 | - bump_menu_and_write(&dish.menu, &statement, bindings, db) | |
| 162 | - .await? | |
| 163 | - .ok_or(AppError::NotFound) | |
| 166 | + .fetch_optional(&mut *tx) | |
| 167 | + .await?; | |
| 168 | + row.ok_or(AppError::NotFound) | |
| 169 | + }) | |
| 170 | + .await | |
| 164 | 171 | } |
| 165 | 172 | |
| 166 | 173 | pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { |
| 167 | - bump_menu_and_write( | |
| 168 | - &dish.menu, | |
| 169 | - "DELETE $id RETURN BEFORE", | |
| 170 | - vec![("id".into(), dish.id.record().into_value())], | |
| 171 | - db, | |
| 172 | - ) | |
| 173 | - .await? | |
| 174 | - .ok_or(AppError::NotFound) | |
| 174 | + let dish_key = dish.id.key(); | |
| 175 | + let menu_key = dish.menu.key().to_string(); | |
| 176 | + tx_with_retry(db, false, async |tx| { | |
| 177 | + let bumped = sqlx::query!( | |
| 178 | + "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | |
| 179 | + RETURNING 1 AS bumped", | |
| 180 | + menu_key, | |
| 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 | 11 | //! never rewrite a menu already published under it. |
| 12 | 12 | //! |
| 13 | 13 | //! 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 | 16 | use sqlx::Type; |
| 17 | 17 |
src/domain/menu_dish.rsmodified+2 -2
| @@ -5,8 +5,8 @@ | ||
| 5 | 5 | //! at any layer. `tags` are validated against the school's `dietary_tags` |
| 6 | 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 the | |
| 9 | -//! write lock in [`crate::service::menu`]. | |
| 8 | +//! The queries live in [`crate::db::menu_dish`]; the dish-cap gate in | |
| 9 | +//! [`crate::service::menu`]. | |
| 10 | 10 | |
| 11 | 11 | use sqlx::Type; |
| 12 | 12 | use uuid::Uuid; |
src/service/meal_attendance.rsmodified+3 -4
| @@ -1,9 +1,8 @@ | ||
| 1 | 1 | //! The attendance-mark workflows: recording who ate off a menu and the two |
| 2 | 2 | //! listings the kitchen and the student report read. The mark itself is a |
| 3 | -//! single atomic UPSERT that rides the menu's revision bump | |
| 4 | -//! ([`crate::db::menu::bump_menu_and_write`]) — the queries live in | |
| 5 | -//! [`crate::db::meal_attendance`], the row shape in | |
| 6 | -//! [`crate::domain::meal_attendance`]. | |
| 3 | +//! single atomic upsert that rides the menu's revision bump inside its own | |
| 4 | +//! transaction — the queries live in [`crate::db::meal_attendance`], the row | |
| 5 | +//! shape in [`crate::domain::meal_attendance`]. | |
| 7 | 6 | |
| 8 | 7 | use crate::database::Database; |
| 9 | 8 | use crate::db::meal_attendance; |
src/service/meal_booking.rsmodified+5 -5
| @@ -9,9 +9,10 @@ | ||
| 9 | 9 | //! |
| 10 | 10 | //! **No process-wide lock guards this domain**, and deliberately: every |
| 11 | 11 | //! invariant booking depends on is a *single-record* conditional write (the |
| 12 | -//! menu's `seats_booked` counter and the attempt-fenced row flip), which | |
| 13 | -//! SurrealDB itself serializes — a cross-record lock would add contention | |
| 14 | -//! without deciding anything the transactions do not already. What the | |
| 12 | +//! menu's `seats_booked` counter and the attempt-fenced row flip), which the | |
| 13 | +//! guarded writes themselves serialize — a cross-record lock would add | |
| 14 | +//! contention without deciding anything the transactions do not already. | |
| 15 | +//! What the | |
| 15 | 16 | //! service layer owns here is the *sequence*: read the menu, refuse a past |
| 16 | 17 | //! day or a closed cutoff before anything is claimed, settle the attempt |
| 17 | 18 | //! number before the charge id exists, and map the claim's outcomes |
| @@ -62,7 +63,6 @@ pub async fn book( | ||
| 62 | 63 | cutoff: &MealCutoff, |
| 63 | 64 | ) -> Result<MealBooking, AppError> { |
| 64 | 65 | let id = MealBookingId::composite(menu, student); |
| 65 | - let seats = menu.record(); | |
| 66 | 66 | for attempt in 0..CAP_WRITE_TRIES { |
| 67 | 67 | backoff(attempt).await; |
| 68 | 68 | let fresh = menu::read(db, menu).await?.ok_or(AppError::NotFound)?; |
| @@ -135,7 +135,7 @@ pub async fn book( | ||
| 135 | 135 | let charge = MealLedger::charge_for(&fresh_row, booked_by); |
| 136 | 136 | match meal_booking::claim_and_place( |
| 137 | 137 | db, |
| 138 | - &seats, | |
| 138 | + menu, | |
| 139 | 139 | fresh.get_capacity().unwrap_or(cap::UNLIMITED), |
| 140 | 140 | fresh.get_version(), |
| 141 | 141 | &fresh_row, |
src/service/meal_ledger.rsmodified+1 -1
| @@ -77,7 +77,7 @@ pub async fn reverse_booking( | ||
| 77 | 77 | /// resending the identical body after a timeout gets back the line the |
| 78 | 78 | /// first attempt wrote, not a second credit — nothing on this API can edit |
| 79 | 79 | /// or delete one, so a doubled credit is corrected only by a compensating |
| 80 | -/// line. Without one the id is a fresh ulid and two identical calls are two | |
| 80 | +/// line. Without one the id is a fresh uuid and two identical calls are two | |
| 81 | 81 | /// credits, which is what a desk taking the same amount twice really means. |
| 82 | 82 | pub async fn credit( |
| 83 | 83 | db: &Database, |
src/service/menu.rsmodified+31 -57
| @@ -1,24 +1,16 @@ | ||
| 1 | 1 | //! The kitchen's workflows: publishing and unpublishing menus, and every |
| 2 | -//! dish write — which all hold [`MENU_LOCK`], the lock that makes the | |
| 3 | -//! per-menu dish cap (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB | |
| 4 | -//! does not conflict-check) more than a wish. The queries live in | |
| 5 | -//! [`crate::db::menu`] and [`crate::db::menu_dish`]; the row shapes and the | |
| 6 | -//! date/slot/capacity rules in [`crate::domain::menu`] and | |
| 7 | -//! [`crate::domain::menu_dish`]. | |
| 2 | +//! dish write. The queries live in [`crate::db::menu`] and | |
| 3 | +//! [`crate::db::menu_dish`]; the row shapes and the date/slot/capacity | |
| 4 | +//! rules in [`crate::domain::menu`] and [`crate::domain::menu_dish`]. | |
| 8 | 5 | //! |
| 9 | -//! [`MENU_LOCK`] spans a **multi-call** sequence (read the menu, count the | |
| 10 | -//! dishes, write the dish), which is why it lives here and not in the db | |
| 11 | -//! layer: a single-call atomicity lock would be the store's to own, but | |
| 12 | -//! count-then-write is write-skew only this process can serialize. | |
| 13 | -//! | |
| 14 | -//! **A leaf**: every dish write held under it moves the menu's revision | |
| 15 | -//! inside its *own* transaction ([`crate::db::menu::bump_menu_and_write`]), | |
| 16 | -//! so no path under this lock reaches `cap`'s counter lock any more. Should | |
| 17 | -//! one ever need both, the order is `MENU_LOCK` → `CLAIM_LOCK` and nothing | |
| 18 | -//! may take this lock while holding a counter lock: that is the invariant a | |
| 19 | -//! new caller must keep, and it is what would keep the pair deadlock-free. | |
| 20 | - | |
| 21 | -use tokio::sync::Mutex; | |
| 6 | +//! **No process-wide lock guards this domain.** The dish cap | |
| 7 | +//! (`MAX_DISHES_PER_MENU`) used to be a count-then-write pair only a | |
| 8 | +//! process mutex could make safe; it is now one guarded statement — the | |
| 9 | +//! menu row is taken `FOR NO KEY UPDATE` inside the dish write's own | |
| 10 | +//! transaction and the `INSERT … WHERE count(*) < cap` runs behind that | |
| 11 | +//! lock, so two racing writers serialize on the row the database owns. | |
| 12 | +//! Every dish write moves the menu's revision in that same transaction, and | |
| 13 | +//! a booking claims its seat at the revision it priced itself against. | |
| 22 | 14 | |
| 23 | 15 | use crate::constant::MAX_DISHES_PER_MENU; |
| 24 | 16 | use crate::database::Database; |
| @@ -30,20 +22,6 @@ use crate::domain::menu_dish::{ | ||
| 30 | 22 | use crate::domain::user::UserId; |
| 31 | 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 | 25 | /// Publish a menu for one day and meal slot. The caller has validated the |
| 48 | 26 | /// date (a real calendar day, not already over), the slot (one the school |
| 49 | 27 | /// 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 | 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-write | |
| 96 | -/// is write-skew, so the count and the insert have to be one step. The | |
| 97 | -/// *price* no longer needs it — a dish write moves the menu's revision, and | |
| 98 | -/// a booking claims its seat at the revision it priced itself against. | |
| 99 | -/// The lock is a leaf again: the revision bump rides the dish write's own | |
| 100 | -/// transaction now, so nothing held under it takes `cap`'s counter lock. It | |
| 101 | -/// stays a leaf only while that holds — see [`MENU_LOCK`] for the order a | |
| 102 | -/// caller that changes it must keep. | |
| 73 | +/// The cap is the database's to enforce, not this process's: the write | |
| 74 | +/// locks the menu row `FOR NO KEY UPDATE` and its `INSERT` carries a | |
| 75 | +/// `count(*) < cap` guard, so a writer that queued behind a concurrent one | |
| 76 | +/// re-counts after the lock and is refused (`409`) instead of overfilling | |
| 77 | +/// — the count and the insert are one decision, with no window a second | |
| 78 | +/// writer can slip through. | |
| 103 | 79 | /// |
| 104 | -/// The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` | |
| 105 | -/// running in the gap takes its cascade with it and this dish lands on a menu | |
| 106 | -/// that no longer exists. | |
| 80 | +/// The *price* needs no lock — a dish write moves the menu's revision, and | |
| 81 | +/// a booking claims its seat at the revision it priced itself against. | |
| 107 | 82 | pub async fn add_dish( |
| 108 | 83 | db: &Database, |
| 109 | 84 | menu_id: &MenuId, |
| @@ -112,14 +87,16 @@ pub async fn add_dish( | ||
| 112 | 87 | price_minor: DishPrice, |
| 113 | 88 | tags: DishTags, |
| 114 | 89 | ) -> Result<MenuDish, AppError> { |
| 115 | - let _guard = MENU_LOCK.lock().await; | |
| 116 | - let menu = menu::read(db, menu_id).await?.ok_or(AppError::NotFound)?; | |
| 117 | - if menu_dish::count_for_menu(db, menu.get_id()).await? >= MAX_DISHES_PER_MENU { | |
| 118 | - return Err(AppError::Conflict( | |
| 119 | - "the menu already carries the maximum number of dishes", | |
| 120 | - )); | |
| 121 | - } | |
| 122 | - menu_dish::create(db, menu.get_id(), name, description, price_minor, tags).await | |
| 90 | + menu_dish::create( | |
| 91 | + db, | |
| 92 | + menu_id, | |
| 93 | + name, | |
| 94 | + description, | |
| 95 | + price_minor, | |
| 96 | + tags, | |
| 97 | + MAX_DISHES_PER_MENU as i64, | |
| 98 | + ) | |
| 99 | + .await | |
| 123 | 100 | } |
| 124 | 101 | |
| 125 | 102 | /// One dish, for callers that only inspect it. |
| @@ -140,8 +117,7 @@ pub async fn list_dishes_for_menus( | ||
| 140 | 117 | menu_dish::list_for_menus(db, menus).await |
| 141 | 118 | } |
| 142 | 119 | |
| 143 | -/// Edit a dish. Under [`MENU_LOCK`] like every dish write — see | |
| 144 | -/// [`add_dish`]. Only what the request carried is written. | |
| 120 | +/// Edit a dish. Only what the request carried is written. | |
| 145 | 121 | pub async fn update_dish( |
| 146 | 122 | db: &Database, |
| 147 | 123 | dish: MenuDish, |
| @@ -150,12 +126,10 @@ pub async fn update_dish( | ||
| 150 | 126 | price_minor: Option<DishPrice>, |
| 151 | 127 | tags: Option<DishTags>, |
| 152 | 128 | ) -> Result<MenuDish, AppError> { |
| 153 | - let _guard = MENU_LOCK.lock().await; | |
| 154 | 129 | 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 | 133 | pub async fn delete_dish(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { |
| 159 | - let _guard = MENU_LOCK.lock().await; | |
| 160 | 134 | menu_dish::delete(db, dish).await |
| 161 | 135 | } |
src/web/meals.rsmodified+9 -9
| @@ -438,11 +438,11 @@ async fn add_dish( | ||
| 438 | 438 | &req.tags, |
| 439 | 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) | |
| 442 | - // lease live in the service: count-then-write is write-skew, so the count | |
| 443 | - // and the insert have to be one step, and the menu is read *inside* the | |
| 444 | - // lock — read before it, a `DELETE /menus/{id}` running in the gap takes | |
| 445 | - // its cascade with it and this dish lands on a menu that no longer exists. | |
| 441 | + // The dish-cap gate lives in the service: the cap is one guarded | |
| 442 | + // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the | |
| 443 | + // dish write's own transaction and the insert carries the | |
| 444 | + // `count(*) < cap` guard, so a dish can never land on a menu that no | |
| 445 | + // longer exists, and two racing writers cannot overfill it either. | |
| 446 | 446 | let dish = service::menu::add_dish( |
| 447 | 447 | &st.db, |
| 448 | 448 | &MenuId::from_key(&id), |
| @@ -502,8 +502,8 @@ async fn update_dish( | ||
| 502 | 502 | )?), |
| 503 | 503 | None => None, |
| 504 | 504 | }; |
| 505 | - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) | |
| 506 | - // inside the service, like every dish write — see `add_dish`. | |
| 505 | + // The dish write locks the menu row inside its own transaction — see | |
| 506 | + // `add_dish`. | |
| 507 | 507 | let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; |
| 508 | 508 | let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; |
| 509 | 509 | Ok(Json(DishResponse::new(&updated, &viewer_tags))) |
| @@ -531,8 +531,8 @@ async fn delete_dish( | ||
| 531 | 531 | let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) |
| 532 | 532 | .await? |
| 533 | 533 | .ok_or(AppError::NotFound)?; |
| 534 | - // The dish write holds [`MENU_LOCK`](crate::service::menu::MENU_LOCK) | |
| 535 | - // inside the service, like every dish write — see `add_dish`. | |
| 534 | + // The dish write locks the menu row inside its own transaction — see | |
| 535 | + // `add_dish`. | |
| 536 | 536 | service::menu::delete_dish(&st.db, dish).await?; |
| 537 | 537 | Ok(StatusCode::NO_CONTENT) |
| 538 | 538 | } |