forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/meal_booking'

Browse files at this commit

78600f57e08f427b4245eb625b41308b315fc18eAhmet Kaan GümüşParent: f199cd920bf36b
# Conflicts:
#	src/service/mod.rs

8 changed files +1268 -1111

src/db/meal_booking.rsadded+621 -0
@@ -0,0 +1,621 @@
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`].
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};
12+use crate::db::cap::Claimed;
13+use crate::db::page::PagedList;
14+use crate::domain::meal_booking::{MealBooking, MealBookingId};
15+use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
16+use crate::domain::menu::MenuId;
17+use crate::domain::timestamp::Timestamp;
18+use crate::domain::user::UserId;
19+use crate::error::AppError;
20+
21+pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {
22+ Ok(db.select(id.record()).await?)
23+}
24+
25+/// Every booking on a menu, cancelled ones included — the kitchen's list.
26+pub async fn list_for_menu(
27+ db: &Database,
28+ menu: &MenuId,
29+ limit: Option<i64>,
30+ offset: i64,
31+) -> Result<(Vec<MealBooking>, i64), AppError> {
32+ PagedList::new(
33+ "meal_booking WHERE menu = $menu",
34+ "ORDER BY created_at DESC, id DESC",
35+ )
36+ .bind("menu", menu.record())
37+ .run(limit, offset, db)
38+ .await
39+}
40+
41+/// Every seat held for one of `students`, newest first — a caller's own
42+/// list is themselves plus whoever they hold a *live* parent link to.
43+///
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
48+/// cancellations made long after the link died — exactly what
49+/// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The
50+/// caller re-derives the list from the links on every read, so the view
51+/// dies with the link.
52+pub async fn list_for_students(
53+ db: &Database,
54+ students: &[UserId],
55+ limit: Option<i64>,
56+ offset: i64,
57+) -> 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<_>>(),
65+ )
66+ .run(limit, offset, db)
67+ .await
68+}
69+
70+/// Take the seat **and** place the row in one transaction, at the menu
71+/// revision the price was read at.
72+///
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.
83+///
84+/// 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
86+/// opened the seat, and when.
87+///
88+/// **The charge rides this transaction too**, for the same reason the
89+/// refund rides the cancel's: appended a write later, a cancel landing in
90+/// the gap finds no charge, reverses nothing, and the charge lands after it
91+/// — the seat given back and the money still owed, unreversible by any
92+/// route, because every ledger id carries the attempt the cancel has already
93+/// moved past. That is why `row.attempt` is minted by the *caller*: the
94+/// charge's id is (seat, attempt), so the number cannot be the revival's own
95+/// `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.
99+///
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
102+/// billed twice is the one thing money code may never do.
103+pub(crate) async fn claim_and_place(
104+ db: &Database,
105+ seats: &RecordId,
106+ cap: i64,
107+ seen: i64,
108+ row: &MealBooking,
109+ price: Option<LedgerAmount>,
110+ charge: Option<&MealLedger>,
111+) -> 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 };"
117+ }
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+ {
178+ return Ok(Claimed::Full);
179+ }
180+ if errors
181+ .values()
182+ .any(|error| error.to_string().contains("held") || error.is_already_exists())
183+ {
184+ 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+ };
196+ }
197+ Err(AppError::Conflict(
198+ "the menu kept changing underneath this booking",
199+ ))
200+}
201+
202+/// Flip the seat to `cancelled` and give it back to the menu's counter **in
203+/// one transaction**, so the two can never disagree: a decrement that ran
204+/// 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.
208+///
209+/// **The refund rides this transaction too**, and it has to: the flip and a
210+/// reversal appended after it are two writes, and a crash in between leaves
211+/// the seat free with the charge standing — after which a re-book moves the
212+/// row to attempt N+1 and *no* route can ever write the `(booking, N)`
213+/// reversal, because the money is keyed to the attempt. Folded in here the
214+/// seat cannot come back without the money, the same way the counter cannot
215+/// move without the flip. The reversal is written only when the charge it
216+/// undoes is really there (checked in the transaction, so no round trip can
217+/// invalidate it): a refund with no charge behind it invents money.
218+///
219+/// The book side is folded the same way ([`claim_and_place`]), so there is
220+/// no half-second anywhere in which a seat is held with no charge against
221+/// it, or a charge stands with no seat behind it.
222+///
223+/// **The flip is fenced on the attempt it read**, exactly as the revival on
224+/// the book side is. `status = 'booked'` alone matches a seat somebody else
225+/// took in the round trip [`crate::service::meal_booking::cancel`] spends
226+/// re-reading the menu: the flip then cancels attempt N+1, hands its seat
227+/// back, and refunds nothing at all — the ids bound here are attempt N's,
228+/// and N's reversal is already written — so a `POST` answered `201` a moment
229+/// ago loses its seat with its charge standing, and the `(booking, N+1)`
230+/// reversal id is burnt for good.
231+///
232+/// `None` = the row was not this call's own `booked` attempt any more.
233+/// Retried while the store reports a write conflict: the menu row is
234+/// contended by every booking on it, and that contention is the cap
235+/// working, not an error.
236+pub async fn release_seat(
237+ db: &Database,
238+ booked: &MealBooking,
239+ recorded_by: &UserId,
240+) -> Result<Option<MealBooking>, AppError> {
241+ 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)
291+ }
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()),
297+ }
298+ }
299+ Err(AppError::Conflict(
300+ "the menu kept changing underneath this cancellation",
301+ ))
302+}
303+
304+#[cfg(test)]
305+mod tests {
306+ use super::*;
307+ use crate::database::init_mem;
308+ use crate::db::cap;
309+ use crate::domain::meal_booking::{MealBookingStatus, MealCutoff};
310+ use crate::domain::menu::{Menu, MenuDate, MenuSlot};
311+ use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish};
312+ use crate::domain::settings::MealSlotDef;
313+ use crate::service::meal_booking;
314+
315+ /// A published menu on a fresh in-memory database, plus a student. Dated
316+ /// well ahead on purpose: a menu whose day has passed refuses every
317+ /// booking, so a date the calendar overtakes would fail this whole module.
318+ async fn menu(capacity: Option<i64>) -> (Database, MenuId) {
319+ menu_on("2099-09-14", capacity).await
320+ }
321+
322+ async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
323+ let db = init_mem().await.unwrap();
324+ let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
325+ let menu = Menu::create(
326+ MenuDate::try_new(date).unwrap(),
327+ MenuSlot::try_new("lunch", &slots).unwrap(),
328+ capacity,
329+ &UserId::generate(),
330+ &db,
331+ )
332+ .await
333+ .unwrap();
334+ (db, menu.get_id().clone())
335+ }
336+
337+ /// The stored counter, absent reading as zero — the number the cap's
338+ /// `WHERE` actually compares, not one recomputed from the rows.
339+ async fn seats(menu: &MenuId, db: &Database) -> i64 {
340+ let mut result = db
341+ .query("SELECT VALUE seats_booked FROM $id")
342+ .bind(("id", menu.record()))
343+ .await
344+ .unwrap()
345+ .check()
346+ .unwrap();
347+ result
348+ .take::<Vec<Option<i64>>>(0)
349+ .unwrap()
350+ .into_iter()
351+ .next()
352+ .flatten()
353+ .unwrap_or(0)
354+ }
355+
356+ async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
357+ MenuDish::create(
358+ menu,
359+ DishName::try_new("çorba").unwrap(),
360+ None,
361+ DishPrice::try_new(price).unwrap(),
362+ DishTags::try_new(&[], &[]).unwrap(),
363+ db,
364+ )
365+ .await
366+ .unwrap()
367+ }
368+
369+ /// The price a seat is billed must be one the menu carried *at the moment
370+ /// the seat was taken*. The claim carries the revision the price was read
371+ /// at, so a dish written in between refuses it — this is that refusal,
372+ /// driven by hand because no single-process interleaving can produce it.
373+ #[tokio::test]
374+ async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() {
375+ let (db, menu) = menu(None).await;
376+ let ali = UserId::generate();
377+ let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
378+ // A dish lands: the price a booking read a moment ago is now stale.
379+ add_dish(&menu, 1_000, &db).await;
380+ let row = MealBooking {
381+ id: MealBookingId::composite(&menu, &ali),
382+ menu: menu.clone(),
383+ student: ali.clone(),
384+ booked_by: ali,
385+ status: MealBookingStatus::Booked,
386+ attempt: 1,
387+ price_minor: None,
388+ cancelled_at: None,
389+ created_at: Timestamp::now(),
390+ };
391+ let place = async |seen| {
392+ claim_and_place(&db, &menu.record(), cap::UNLIMITED, seen, &row, None, None)
393+ .await
394+ .unwrap()
395+ };
396+ assert!(
397+ matches!(place(seen).await, Claimed::Full),
398+ "a claim at a revision the menu has left must be refused"
399+ );
400+ assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");
401+ assert!(
402+ read(&db, row.get_id()).await.unwrap().is_none(),
403+ "the refused transaction must not leave the row behind either"
404+ );
405+
406+ // Re-read, and the same seat is taken with the row it belongs to.
407+ let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
408+ assert!(now > seen);
409+ assert!(matches!(place(now).await, Claimed::Made(_)));
410+ assert_eq!(seats(&menu, &db).await, 1);
411+ // …and a second placement of that very row owes no second seat.
412+ assert!(matches!(place(now).await, Claimed::Duplicate));
413+ assert_eq!(
414+ seats(&menu, &db).await,
415+ 1,
416+ "a duplicate rolls its seat back"
417+ );
418+ }
419+
420+ /// Every write that can move what a seat costs moves the revision — the
421+ /// half of the rule the CAS above cannot enforce by itself. A dish added,
422+ /// re-priced or removed, and the capacity moved: each must leave the menu at
423+ /// a revision no in-flight booking is still holding.
424+ #[tokio::test]
425+ async fn every_menu_write_that_moves_the_price_moves_the_revision() {
426+ let (db, id) = menu(None).await;
427+ let mut seen = 0;
428+ let mut moved = async |db: &Database| {
429+ let now = Menu::read(&id, db).await.unwrap().unwrap().get_version();
430+ let stepped = now > seen;
431+ seen = now;
432+ stepped
433+ };
434+ assert!(!moved(&db).await, "a fresh menu starts where it starts");
435+
436+ let dish = add_dish(&id, 1_000, &db).await;
437+ assert!(moved(&db).await, "a dish added");
438+ let dish = dish
439+ .update(
440+ None,
441+ None,
442+ Some(DishPrice::try_new(2_000).unwrap()),
443+ None,
444+ &db,
445+ )
446+ .await
447+ .unwrap();
448+ assert!(moved(&db).await, "a dish re-priced");
449+ dish.delete(&db).await.unwrap();
450+ assert!(moved(&db).await, "a dish removed");
451+ Menu::read(&id, &db)
452+ .await
453+ .unwrap()
454+ .unwrap()
455+ .update(Some(Some(5)), &db)
456+ .await
457+ .unwrap();
458+ assert!(moved(&db).await, "the capacity moved");
459+ }
460+
461+ /// A cancel may only ever release the attempt it read. The stale handle
462+ /// here is what a cancel holds across its own `Menu::read` round trip: by
463+ /// the time the flip runs, that seat has been cancelled and taken again, so
464+ /// the flip must refuse — unfenced it cancelled the *new* attempt, freeing a
465+ /// seat the API had just answered `201` for, without refunding it (the
466+ /// reversal is keyed to the stale attempt, which is already refunded) and
467+ /// burning the new attempt's own reversal id for good.
468+ #[tokio::test]
469+ async fn a_cancel_cannot_release_an_attempt_it_never_read() {
470+ let (db, menu) = menu(Some(1)).await;
471+ let (ali, veli) = (UserId::generate(), UserId::generate());
472+ let open = MealCutoff::default();
473+ add_dish(&menu, 1_000, &db).await;
474+
475+ let stale = meal_booking::book(&db, &menu, &ali, &ali, &open)
476+ .await
477+ .unwrap();
478+ meal_booking::cancel(&db, stale.clone(), &open, &ali)
479+ .await
480+ .unwrap();
481+ let live = meal_booking::book(&db, &menu, &ali, &ali, &open)
482+ .await
483+ .unwrap();
484+ assert_eq!(live.get_attempt(), stale.get_attempt() + 1);
485+
486+ assert!(
487+ release_seat(&db, &stale, &ali).await.unwrap().is_none(),
488+ "the attempt this call read is gone, so it releases nothing"
489+ );
490+ // Stored state, not the returned value: the mem engine forges wins.
491+ let stored = read(&db, live.get_id()).await.unwrap().unwrap();
492+ assert_eq!(stored.get_status(), MealBookingStatus::Booked);
493+ assert_eq!(stored.get_attempt(), live.get_attempt());
494+ assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
495+ assert_eq!(
496+ MealLedger::balance_of(&ali, &db).await.unwrap(),
497+ -1_000,
498+ "the live attempt's charge stands: it was never cancelled"
499+ );
500+ // The seat is still really held — the cap says so too.
501+ assert!(matches!(
502+ meal_booking::book(&db, &menu, &veli, &veli, &open).await,
503+ Err(AppError::Conflict(_))
504+ ));
505+ }
506+
507+ /// The seat may not come back without the money. Driven against
508+ /// [`release_seat`] rather than through
509+ /// [`crate::service::meal_booking::cancel`], because what is under test is
510+ /// precisely what a *crash right after the flip* leaves behind: appended a
511+ /// write later, the reversal is lost with the process, and a re-book then
512+ /// moves the row to the next attempt and locks the `(booking, attempt)`
513+ /// reversal id out for good — the charge is unreversible by any route on
514+ /// the API.
515+ #[tokio::test]
516+ async fn the_seat_cannot_be_freed_without_its_refund() {
517+ let (db, menu) = menu(None).await;
518+ let ali = UserId::generate();
519+ let open = MealCutoff::default();
520+ add_dish(&menu, 1_000, &db).await;
521+ let booked = meal_booking::book(&db, &menu, &ali, &ali, &open)
522+ .await
523+ .unwrap();
524+
525+ // The flip alone — nothing else runs afterwards, as after a crash.
526+ let freed = release_seat(&db, &booked, &ali)
527+ .await
528+ .unwrap()
529+ .expect("the seat was held, so the flip must take it back");
530+ assert_eq!(freed.get_status(), MealBookingStatus::Cancelled);
531+ assert_eq!(seats(&menu, &db).await, 0);
532+ assert_eq!(
533+ MealLedger::balance_of(&ali, &db).await.unwrap(),
534+ 0,
535+ "the reversal must have committed with the flip, not after it"
536+ );
537+
538+ // And the re-book that used to strand the charge now finds it settled:
539+ // a fresh attempt, billed once more, with the old one squared away.
540+ meal_booking::book(&db, &menu, &ali, &ali, &open)
541+ .await
542+ .unwrap();
543+ assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
544+ }
545+
546+ /// The seat may not be held without its money. Driven against
547+ /// [`claim_and_place`] rather than through
548+ /// [`crate::service::meal_booking::book`], because what is under test is
549+ /// precisely what the gap between the two writes leaves behind: a cancel
550+ /// landing there finds no charge to reverse, reverses nothing, and the
551+ /// charge then lands anyway — a student holding no seat and owing money,
552+ /// with the `(booking, attempt)` reversal id burnt for good.
553+ #[tokio::test]
554+ async fn the_seat_cannot_be_claimed_without_its_charge() {
555+ let (db, menu) = menu(None).await;
556+ let ali = UserId::generate();
557+ add_dish(&menu, 1_000, &db).await;
558+ let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
559+ let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
560+ let row = MealBooking {
561+ id: MealBookingId::composite(&menu, &ali),
562+ menu: menu.clone(),
563+ student: ali.clone(),
564+ booked_by: ali.clone(),
565+ status: MealBookingStatus::Booked,
566+ attempt: 1,
567+ price_minor: price,
568+ cancelled_at: None,
569+ created_at: Timestamp::now(),
570+ };
571+ let charge = MealLedger::charge_for(&row, &ali);
572+ // The claim alone — nothing else runs afterwards, as after a crash.
573+ let place = async || {
574+ claim_and_place(
575+ &db,
576+ &menu.record(),
577+ cap::UNLIMITED,
578+ seen,
579+ &row,
580+ price,
581+ charge.as_ref(),
582+ )
583+ .await
584+ .unwrap()
585+ };
586+ assert!(matches!(place().await, Claimed::Made(_)));
587+ assert_eq!(seats(&menu, &db).await, 1);
588+ assert_eq!(
589+ MealLedger::balance_of(&ali, &db).await.unwrap(),
590+ -1_000,
591+ "the charge must have committed with the claim, not after it"
592+ );
593+
594+ // Replayed: the seat is already held, so the whole transaction rolls
595+ // back — no second seat and, just as importantly, no second charge.
596+ assert!(matches!(place().await, Claimed::Duplicate));
597+ assert_eq!(seats(&menu, &db).await, 1);
598+ assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
599+ }
600+
601+ /// A free menu owes no refund, so the flip must carry no ledger line at all
602+ /// — the branch the reversal's conditional statement adds.
603+ #[tokio::test]
604+ async fn a_seat_that_was_never_billed_frees_without_a_line() {
605+ let (db, menu) = menu(None).await;
606+ let ali = UserId::generate();
607+ let booked = meal_booking::book(&db, &menu, &ali, &ali, &MealCutoff::default())
608+ .await
609+ .unwrap();
610+
611+ release_seat(&db, &booked, &ali)
612+ .await
613+ .unwrap()
614+ .expect("a free seat is still a seat");
615+ assert_eq!(seats(&menu, &db).await, 0);
616+ let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
617+ .await
618+ .unwrap();
619+ assert!(lines.is_empty() && total == 0, "a free seat moves no money");
620+ }
621+}
src/db/mod.rsmodified+1 -0
@@ -9,6 +9,7 @@ pub mod course_session;
9 pub mod exam_attempt;9 pub mod exam_attempt;
10 pub mod exam_question;10 pub mod exam_question;
11 pub mod field_update;11 pub mod field_update;
12+pub mod meal_booking;
12 pub mod note;13 pub mod note;
13 pub mod page;14 pub mod page;
14 pub mod payment_ledger;15 pub mod payment_ledger;
src/domain/meal_booking.rsmodified+34 -1092
@@ -3,7 +3,14 @@
3 //! same record, so booking is a single atomic UPSERT with no find-then-insert3 //! same record, so booking is a single atomic UPSERT with no find-then-insert
4 //! race and one-row-per-pair by construction.4 //! race and one-row-per-pair by construction.
5 //!5 //!
6-//! Two things are deliberate:6+//! This module is the pure row shape: the id and status, the booking row, and
7+//! the meal deadline policy — [`MealCutoff`] with the two checks that enforce
8+//! it, [`check_day_not_past`] and [`check_cutoff`]. The workflows that take
9+//! and free a seat live in [`crate::service::meal_booking`], and the
10+//! transactions that move the seat, its row and its money together in
11+//! [`crate::db::meal_booking`].
12+//!
13+//! Things that are deliberate:
7 //!14 //!
8 //! - **A cancel is a status transition, not a delete.** The row stays, flipped15 //! - **A cancel is a status transition, not a delete.** The row stays, flipped
9 //! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still16 //! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still
@@ -11,34 +18,29 @@
11 //! the menu's capacity, which is what makes the seat genuinely free again —18 //! the menu's capacity, which is what makes the seat genuinely free again —
12 //! and re-booking is the same UPSERT flipping it back.19 //! and re-booking is the same UPSERT flipping it back.
13 //! - **Capacity is the menu's `seats_booked` counter**, claimed by a20 //! - **Capacity is the menu's `seats_booked` counter**, claimed by a
14-//! conditional single-record write ([`cap`]). Counting the rows instead is21+//! conditional single-record write ([`cap`](crate::db::cap)). Counting the rows instead is
15 //! write-skew — SurrealDB does not conflict-check a cross-record count22 //! write-skew — SurrealDB does not conflict-check a cross-record count
16 //! against a concurrent insert — and a process-wide lock around that count23 //! against a concurrent insert — and a process-wide lock around that count
17 //! is released around the very round trip the racing insert lands in.24 //! is released around the very round trip the racing insert lands in.
18 //! Cancelling gives the seat back in the *same transaction* as the flip.25 //! Cancelling gives the seat back in the *same transaction* as the flip.
19 //! - **The price is claimed, not just read.** The seat is taken at the menu26 //! - **The price is claimed, not just read.** The seat is taken at the menu
20 //! revision the price was read at, in the same transaction as the row27 //! revision the price was read at, in the same transaction as the row
21-//! ([`MealBooking::claim_and_place`]), so a dish re-priced mid-booking loses28+//! ([`claim_and_place`](crate::db::meal_booking::claim_and_place)), so a dish re-priced mid-booking loses
22 //! the claim and the booking re-reads both. A seat can only ever be billed a29 //! the claim and the booking re-reads both. A seat can only ever be billed a
23 //! price its menu genuinely carried.30 //! price its menu genuinely carried.
24 //! - **The seat and its money move together.** Booking charges and cancelling31 //! - **The seat and its money move together.** Booking charges and cancelling
25-//! reverses right here, not in the web layer — a seam between the two let32+//! reverses in the service workflow ([`crate::service::meal_booking`]), not
26-//! concurrent `POST`s bill one seat twice — and *both* ledger lines are33+//! in the web layer — a seam between the two let concurrent `POST`s bill one
27-//! written by the very transaction that moves the seat, because money that34+//! seat twice — and *both* ledger lines are written by the very transaction
35+//! that moves the seat ([`crate::db::meal_booking`]), because money that
28 //! trails the seat by one write can be overtaken by the next attempt and36 //! trails the seat by one write can be overtaken by the next attempt and
29 //! stranded forever: every ledger id carries the attempt it belongs to.37 //! stranded forever: every ledger id carries the attempt it belongs to.
30 38
31 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};39 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
32 40
33-use crate::constant::{41+use crate::constant::MEAL_BOOKING_TABLE;
34- CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD,42+use crate::domain::meal_ledger::LedgerAmount;
35- MENU_VERSION_FIELD,43+use crate::domain::menu::{MenuDate, MenuId, MenuSlot};
36-};
37-use crate::database::{Database, backoff, lost_the_race};
38-use crate::db::cap::{self, Claimed};
39-use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
40-use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot};
41-use crate::db::page::PagedList;
42 use crate::domain::settings::{MealSlotDef, Settings};44 use crate::domain::settings::{MealSlotDef, Settings};
43 use crate::domain::timestamp::Timestamp;45 use crate::domain::timestamp::Timestamp;
44 use crate::domain::user::UserId;46 use crate::domain::user::UserId;
@@ -111,23 +113,23 @@ impl MealBookingStatus {
111 113
112 #[derive(Debug, Clone, SurrealValue)]114 #[derive(Debug, Clone, SurrealValue)]
113 pub struct MealBooking {115 pub struct MealBooking {
114- id: MealBookingId,116+ pub(crate) id: MealBookingId,
115- menu: MenuId,117+ pub(crate) menu: MenuId,
116- student: UserId,118+ pub(crate) student: UserId,
117- booked_by: UserId,119+ pub(crate) booked_by: UserId,
118- status: MealBookingStatus,120+ pub(crate) status: MealBookingStatus,
119 /// How many times this seat has been taken: 1 on the first booking, +1 on121 /// How many times this seat has been taken: 1 on the first booking, +1 on
120 /// every revival after a cancel. It is the *attempt* half of the ledger's122 /// every revival after a cancel. It is the *attempt* half of the ledger's
121 /// idempotence key, so a re-book bills afresh while a repeat `POST` of a123 /// idempotence key, so a re-book bills afresh while a repeat `POST` of a
122 /// seat already held bills nothing.124 /// seat already held bills nothing.
123- attempt: i64,125+ pub(crate) attempt: i64,
124 /// What the menu cost when the current attempt took the seat; `None` means126 /// What the menu cost when the current attempt took the seat; `None` means
125 /// it was free *then*. Recorded rather than inferred: without it, "the menu127 /// it was free *then*. Recorded rather than inferred: without it, "the menu
126 /// was free" is indistinguishable from "not billed yet", and a dish added128 /// was free" is indistinguishable from "not billed yet", and a dish added
127 /// afterwards bills a seat that was free when taken.129 /// afterwards bills a seat that was free when taken.
128- price_minor: Option<LedgerAmount>,130+ pub(crate) price_minor: Option<LedgerAmount>,
129- cancelled_at: Option<Timestamp>,131+ pub(crate) cancelled_at: Option<Timestamp>,
130- created_at: Timestamp,132+ pub(crate) created_at: Timestamp,
131 }133 }
132 134
133 impl MealBooking {135 impl MealBooking {
@@ -166,511 +168,6 @@ impl MealBooking {
166 pub fn get_created_at(&self) -> Timestamp {168 pub fn get_created_at(&self) -> Timestamp {
167 self.created_at169 self.created_at
168 }170 }
169-
170- /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already
171- /// booked is returned as-is, claiming nothing; a cancelled row is revived as
172- /// a fresh attempt at the current price. A full menu refuses the seat (409),
173- /// decided by the counter's own `WHERE` rather than by a count this process
174- /// took a moment ago.
175- ///
176- /// The price is read from the menu and then **claimed with it**: the seat is
177- /// only taken while the menu still stands at the revision the price was read
178- /// at, so a dish added, re-priced or removed in that gap loses the claim and
179- /// the whole decision is made again on fresh figures. What is frozen onto
180- /// the row is therefore always a price the menu genuinely carried at the
181- /// instant the seat was taken — a guarantee a lock around the read could
182- /// not give, since the price is read a round trip before the claim.
183- ///
184- /// The charge rides that same transaction, keyed by (seat, attempt): eight
185- /// concurrent `POST`s of one seat hold one seat and write one charge line.
186- /// The price is `None` when the menu is free, and that `None` is stored, so
187- /// a dish added later never bills a seat retroactively.
188- ///
189- /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
190- /// serving time is that close, the seat is fixed either way.
191- pub async fn book(
192- menu: &MenuId,
193- student: &UserId,
194- booked_by: &UserId,
195- cutoff: &MealCutoff,
196- db: &Database,
197- ) -> Result<MealBooking, AppError> {
198- let id = MealBookingId::composite(menu, student);
199- let seats = menu.record();
200- for attempt in 0..CAP_WRITE_TRIES {
201- backoff(attempt).await;
202- let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
203- check_day_not_past(fresh.get_date())?;
204- check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
205- let existing: Option<MealBooking> = db.select(id.record()).await?;
206- // The seat is already held: same attempt, same price it was taken
207- // at. Today's menu price bills nobody who booked yesterday's. No
208- // seat is claimed, so a double-click cannot count two.
209- //
210- // Answered *before* the menu is priced, and that ordering is the
211- // rule: pricing first made a repeat POST of a seat already held 400
212- // ("amount_minor must be between…") as soon as the menu's dishes
213- // summed past the chargeable maximum — refusing to replay a seat
214- // the student holds, over a price that seat was never going to be
215- // billed.
216- if let Some(held) = existing
217- .clone()
218- .filter(|row| row.status == MealBookingStatus::Booked)
219- {
220- MealLedger::charge_booking(&held, booked_by, db).await?;
221- // Answered off a re-read, never off the row read a round trip
222- // ago: a cancel committing in that gap has freed the seat,
223- // given the money back and left the row `cancelled`, and
224- // returning `held` then reports a seat — `"status": "booked"`,
225- // `cancelled_at: null` — the store does not hold. The stored
226- // state was right all along; only the answer lied. Gone or
227- // cancelled, the decision is simply made again, exactly as
228- // `Claimed::Duplicate` below does, so the caller ends up with
229- // the seat they asked for rather than a `201` about a seat
230- // somebody already released.
231- match Self::read(&id, db).await? {
232- Some(live) if live.status == MealBookingStatus::Booked => return Ok(live),
233- _ => continue,
234- }
235- }
236- // The attempt is settled *here*, not by the revival's `attempt + 1`,
237- // because the charge id is (seat, attempt) and the charge has to be
238- // built before the transaction that writes it. `existing` is either
239- // absent or cancelled — a booked row returned above.
240- let attempt = existing.as_ref().map_or(1, |prior| prior.attempt + 1);
241- // A seat retaken without end is a ledger without end: each cycle
242- // appends a charge and its reversal, both permanent, and every
243- // later balance read is answered over the lot. Refused *before* the
244- // menu is priced, so the answer is the ceiling rather than whatever
245- // the pricing happens to say. A row already past the ceiling — an
246- // upgrade's leftovers — is untouched by this: cancelling consults
247- // no cap, so its seat and its money stay reachable, and only one
248- // more revival is refused.
249- if attempt > MAX_MEAL_BOOKING_ATTEMPTS {
250- return Err(AppError::Conflict(
251- "this seat has been booked and cancelled its maximum number of times",
252- ));
253- }
254- // Before the seat: an unchargeable menu (dishes summing past the
255- // cap) must refuse the booking outright, never leave a
256- // booked-but-unbilled row behind.
257- let price = MealLedger::price_snapshot(menu, db).await?;
258- let fresh_row = MealBooking {
259- id: id.clone(),
260- menu: menu.clone(),
261- student: student.clone(),
262- booked_by: booked_by.clone(),
263- status: MealBookingStatus::Booked,
264- attempt,
265- price_minor: price,
266- cancelled_at: None,
267- created_at: Timestamp::now(),
268- };
269- let charge = MealLedger::charge_for(&fresh_row, booked_by);
270- match Self::claim_and_place(
271- &seats,
272- fresh.get_capacity().unwrap_or(cap::UNLIMITED),
273- fresh.get_version(),
274- &fresh_row,
275- price,
276- charge.as_ref(),
277- db,
278- )
279- .await?
280- {
281- // Seat, row and charge committed together; nothing is owed
282- // after this call, which is the whole point of folding them.
283- Claimed::Made(booking) => return Ok(booking),
284- // Another `POST` of this very pair moved the row first, and this
285- // caller never took a seat (the whole transaction rolled back).
286- // The decision is simply made again rather than answered off a
287- // row read here: the winner may have left it `cancelled` at an
288- // attempt this call never saw, and the loop's own held-seat path
289- // is what returns a live seat *and* replays its charge.
290- Claimed::Duplicate => continue,
291- // Full, moved, or gone — one `WHERE` refused all three, so the
292- // reason is re-read rather than guessed. A moved menu is not a
293- // refusal: the price above is stale, so price and seat are
294- // taken again together.
295- Claimed::Full => match Menu::read(menu, db).await? {
296- None => return Err(AppError::NotFound),
297- Some(now) if now.get_version() != fresh.get_version() => continue,
298- Some(_) => return Err(AppError::Conflict("the menu is fully booked")),
299- },
300- }
301- }
302- Err(AppError::Conflict(
303- "the menu kept changing underneath this booking",
304- ))
305- }
306-
307- /// Take the seat **and** place the row in one transaction, at the menu
308- /// revision the price was read at.
309- ///
310- /// The seat and the row cannot be two steps. The id is the (menu, student)
311- /// pair, so two `POST`s of the same seat both find no row and both claim —
312- /// and on a tight cap the second is then told "full" for a seat it never
313- /// owed, while the winner's row may not even be visible yet. Here the
314- /// duplicate `CREATE` aborts the transaction, which takes its increment with
315- /// it: the counter never counts a row that does not exist, and a loser is
316- /// answered with the winner's booking instead of a refusal. Same shape as
317- /// [`cap::claim_and_create`], with the revision guard and the revival of a
318- /// cancelled row that the general form does not carry.
319- ///
320- /// A cancelled row is revived in place (a fresh attempt at `price`) rather
321- /// than recreated: `booked_by` and `created_at` are READONLY history — who
322- /// opened the seat, and when.
323- ///
324- /// **The charge rides this transaction too**, for the same reason the
325- /// refund rides the cancel's: appended a write later, a cancel landing in
326- /// the gap finds no charge, reverses nothing, and the charge lands after it
327- /// — the seat given back and the money still owed, unreversible by any
328- /// route, because every ledger id carries the attempt the cancel has already
329- /// moved past. That is why `row.attempt` is minted by the *caller*: the
330- /// charge's id is (seat, attempt), so the number cannot be the revival's own
331- /// `attempt + 1` any more. The revival is fenced on the attempt it read
332- /// instead, so a rival that revived first loses this claim (the `CREATE`
333- /// below then finds the row and aborts the whole transaction) rather than
334- /// billing its attempt at this call's id.
335- ///
336- /// The charge is created only if it is not already there — a duplicate
337- /// `CREATE` would abort the transaction and cost the seat, and an attempt
338- /// billed twice is the one thing money code may never do.
339- async fn claim_and_place(
340- seats: &RecordId,
341- cap: i64,
342- seen: i64,
343- row: &MealBooking,
344- price: Option<LedgerAmount>,
345- charge: Option<&MealLedger>,
346- db: &Database,
347- ) -> Result<Claimed<MealBooking>, AppError> {
348- // Empty when the menu is free: a seat that costs nothing owes no line.
349- let bill = match charge {
350- Some(_) => {
351- "IF array::len((SELECT VALUE id FROM $charge)) = 0 \
352- { CREATE $charge CONTENT $line };"
353- }
354- None => "",
355- };
356- // Slots count BEGIN, three LETs, three IFs and — when there is money to
357- // take — the charge's IF, so the RETURN is slot 7 or 8.
358- let returned = if charge.is_some() { 8 } else { 7 };
359- // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.
360- let sql = format!(
361- "BEGIN TRANSACTION;
362- LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked');
363- IF array::len($held) > 0 {{ THROW 'held' }};
364- LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \
365- ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \
366- WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \
367- AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);
368- IF array::len($seat) = 0 {{ THROW 'no_seat' }};
369- LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \
370- price_minor = $price, cancelled_at = NONE \
371- WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER);
372- IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};
373- {bill}
374- RETURN SELECT * FROM ONLY $id;
375- COMMIT TRANSACTION;"
376- );
377- // Every booking on one menu contends on that menu's single counter row,
378- // which is one HTTP burst of racers on a single parent — the case
379- // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no
380- // backoff just re-synchronized them and 409'd the fourth student.
381- // Admissible: a lost round aborts the whole transaction (nothing
382- // written, no seat, no charge), and the two `CREATE`s that could
383- // legitimately answer "already exists" are read as `Claimed::Duplicate`
384- // below *before* the conflict check, so no decision is ever re-asked.
385- for attempt in 0..CAP_WRITE_TRIES {
386- backoff(attempt).await;
387- let query = db
388- .query(sql.as_str())
389- .bind(("menu", seats.clone()))
390- .bind(("cap", cap))
391- .bind(("seen", seen))
392- .bind(("id", row.id.record()))
393- .bind(("attempt", row.attempt))
394- .bind(("price", price))
395- .bind(("row", row.clone()));
396- let query = match charge {
397- Some(line) => query
398- .bind(("charge", line.get_id().record()))
399- .bind(("line", line.clone())),
400- None => query,
401- };
402- let mut result = match query.await {
403- Ok(result) => result,
404- Err(err) if lost_the_race(&err) => continue,
405- Err(err) => return Err(err.into()),
406- };
407- // An aborted transaction errors *every* slot, most with a generic
408- // "not executed" — only the failing slot says why, so scan them all.
409- let mut errors = result.take_errors();
410- if errors
411- .values()
412- .any(|error| error.to_string().contains("no_seat"))
413- {
414- return Ok(Claimed::Full);
415- }
416- if errors
417- .values()
418- .any(|error| error.to_string().contains("held") || error.is_already_exists())
419- {
420- return Ok(Claimed::Duplicate);
421- }
422- if errors.values().any(lost_the_race) {
423- continue;
424- }
425- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
426- return Err(error.into());
427- }
428- return match result.take::<Option<MealBooking>>(returned)? {
429- Some(placed) => Ok(Claimed::Made(placed)),
430- None => Err(AppError::Internal("failed to book the meal".into())),
431- };
432- }
433- Err(AppError::Conflict(
434- "the menu kept changing underneath this booking",
435- ))
436- }
437-
438- /// Free the seat: flip to `cancelled`, stamp the moment, **and give the
439- /// money back**. Refused (409) only once the cutoff has passed.
440- ///
441- /// The row is re-read here and the flip is conditional on it still being
442- /// `booked`: the caller's copy may predate a concurrent re-book, and
443- /// cancelling a stale attempt would strand that attempt's charge forever.
444- /// The reversal is keyed to the attempt, so a retried cancel refunds once.
445- ///
446- /// **The refund is not a second write.** It is appended by the very
447- /// transaction that flips the row (see [`Self::release_seat`]), so a
448- /// handler future dropped mid-cancel, a proxy timing out or the store going
449- /// away cannot leave the seat free with the charge standing — the state a
450- /// re-book then made permanent, since every ledger id carries the attempt
451- /// the re-book has already moved past.
452- ///
453- /// **Idempotent all the same**, which is what heals a seat flipped before
454- /// that was true: a cancelled row replays the reversal instead of being
455- /// refused, and that either completes an old missing line or writes nothing
456- /// at all. The cutoff is not re-checked on that path: the seat is already
457- /// given back, and refusing to finish the refund because the meal has since
458- /// closed would strand the money exactly as before.
459- pub async fn cancel(
460- self,
461- cutoff: &MealCutoff,
462- recorded_by: &UserId,
463- db: &Database,
464- ) -> Result<MealBooking, AppError> {
465- let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
466- if fresh.status == MealBookingStatus::Cancelled {
467- MealLedger::reverse_booking(&fresh, recorded_by, db).await?;
468- return Ok(fresh);
469- }
470- let menu = Menu::read(&fresh.menu, db)
471- .await?
472- .ok_or(AppError::NotFound)?;
473- check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
474- // Lost the flip: the row is no longer the `booked` attempt this call
475- // read — another cancel took the seat back first, or a booking took it
476- // again. Its row is the truth, but only the attempt *this* call was
477- // cancelling may be refunded off it (see
478- // [`Self::refundable_after_lost_flip`]).
479- let saved = match Self::release_seat(&fresh, recorded_by, db).await? {
480- Some(cancelled) => cancelled,
481- None => {
482- let live = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
483- if !Self::refundable_after_lost_flip(&fresh, &live)? {
484- return Ok(live);
485- }
486- live
487- }
488- };
489- MealLedger::reverse_booking(&saved, recorded_by, db).await?;
490- Ok(saved)
491- }
492-
493- /// May a cancel that released *nothing* still refund what it read?
494- ///
495- /// Only when the row it finds is the very attempt it was cancelling, still
496- /// cancelled. A cancel is two writes, and between them the seat can be
497- /// re-booked: the row then reads `booked` at attempt N+1 with a live charge
498- /// against it, and reversing that — as re-reading and refunding blindly did
499- /// — refunds a seat that is still held *and* still counted, and burns the
500- /// `(booking, attempt)` ledger id that attempt's own cancel needs, so it
501- /// could never be refunded afterwards. A row at another attempt is the same
502- /// story one step further on: whoever cancelled attempt N appended its
503- /// reversal, and this call has nothing left to heal.
504- ///
505- /// A seat that is `booked` again is a **409**, not a `200`: the flip was
506- /// fenced on the attempt this call read, so the row can only be held by a
507- /// booking that landed inside this very cancel — one the API answered `201`
508- /// for and which no caller here has seen, let alone decided to free. `200`
509- /// with a `booked` row would report a cancellation that did not happen; the
510- /// client is told to look again instead, and a fresh `DELETE` then cancels
511- /// the attempt it really read. (A repeat cancel of an *unchanged* seat never
512- /// reaches here: `cancel` answers an already-cancelled row above.)
513- fn refundable_after_lost_flip(
514- seen: &MealBooking,
515- live: &MealBooking,
516- ) -> Result<bool, AppError> {
517- if live.status == MealBookingStatus::Booked {
518- return Err(AppError::Conflict(
519- "the seat was booked again while this cancellation ran",
520- ));
521- }
522- Ok(live.attempt == seen.attempt)
523- }
524-
525- /// Flip the seat to `cancelled` and give it back to the menu's counter **in
526- /// one transaction**, so the two can never disagree: a decrement that ran
527- /// without the flip frees a seat still held, and a flip without the
528- /// decrement locks a seat nothing can ever release. The counter follows the
529- /// flip's own result (`array::len`), so a row already cancelled — by a
530- /// racing cancel, or by this call retried — decrements nothing.
531- ///
532- /// **The refund rides this transaction too**, and it has to: the flip and a
533- /// reversal appended after it are two writes, and a crash in between leaves
534- /// the seat free with the charge standing — after which a re-book moves the
535- /// row to attempt N+1 and *no* route can ever write the `(booking, N)`
536- /// reversal, because the money is keyed to the attempt. Folded in here the
537- /// seat cannot come back without the money, the same way the counter cannot
538- /// move without the flip. The reversal is written only when the charge it
539- /// undoes is really there (checked in the transaction, so no round trip can
540- /// invalidate it): a refund with no charge behind it invents money.
541- ///
542- /// The book side is folded the same way ([`Self::claim_and_place`]), so
543- /// there is no half-second anywhere in which a seat is held with no charge
544- /// against it, or a charge stands with no seat behind it.
545- ///
546- /// **The flip is fenced on the attempt it read**, exactly as the revival on
547- /// the book side is. `status = 'booked'` alone matches a seat somebody else
548- /// took in the round trip [`Self::cancel`] spends re-reading the menu: the
549- /// flip then cancels attempt N+1, hands its seat back, and refunds nothing
550- /// at all — the ids bound here are attempt N's, and N's reversal is already
551- /// written — so a `POST` answered `201` a moment ago loses its seat with its
552- /// charge standing, and the `(booking, N+1)` reversal id is burnt for good.
553- ///
554- /// `None` = the row was not this call's own `booked` attempt any more.
555- /// Retried while the store reports a write conflict: the menu row is
556- /// contended by every booking on it, and that contention is the cap
557- /// working, not an error.
558- async fn release_seat(
559- booked: &MealBooking,
560- recorded_by: &UserId,
561- db: &Database,
562- ) -> Result<Option<MealBooking>, AppError> {
563- let refund = MealLedger::reversal_for(booked, recorded_by);
564- // Guarded three ways: nothing was flipped (a rival cancelled first, and
565- // its own transaction carried the refund), the charge never landed, or
566- // this attempt is already refunded — none of which may abort the flip.
567- let reverse = match refund {
568- Some(_) => {
569- "IF array::len($flipped) > 0 \
570- AND array::len((SELECT VALUE id FROM $charge)) > 0 \
571- AND array::len((SELECT VALUE id FROM $reversal)) = 0 \
572- { CREATE $reversal CONTENT $line };"
573- }
574- None => "",
575- };
576- // Slots count BEGIN, the LET, the seat UPDATE and — when there is money
577- // to give back — the IF.
578- let returned = if refund.is_some() { 4 } else { 3 };
579- // Same burst on the same counter as the book side, so the same patience
580- // (see [`Self::claim_and_place`]) — a cancel that gave up left the seat
581- // held with the charge standing. Admissible: the round aborts having
582- // written nothing, and a re-send finds the row already `cancelled`, so
583- // the flip matches nothing, the counter moves nothing and the guarded
584- // reversal — keyed to (seat, attempt) — is not written twice.
585- for attempt in 0..CAP_WRITE_TRIES {
586- backoff(attempt).await;
587- let attempted = async {
588- let query = db
589- .query(format!(
590- "BEGIN TRANSACTION;
591- LET $flipped = (UPDATE $id SET status = 'cancelled', \
592- cancelled_at = $now \
593- WHERE status = 'booked' AND attempt = $attempt RETURN AFTER);
594- UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\
595- ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);
596- {reverse}
597- RETURN $flipped;
598- COMMIT TRANSACTION;"
599- ))
600- .bind(("id", booked.id.record()))
601- .bind(("menu", booked.menu.record()))
602- .bind(("attempt", booked.attempt))
603- .bind(("now", Timestamp::now()));
604- let query = match &refund {
605- Some((charge, line)) => query
606- .bind(("charge", charge.record()))
607- .bind(("reversal", line.get_id().record()))
608- .bind(("line", line.clone())),
609- None => query,
610- };
611- let mut result = query.await?.check()?;
612- result.take::<Vec<MealBooking>>(returned)
613- }
614- .await;
615- match attempted {
616- Ok(rows) => return Ok(rows.into_iter().next()),
617- Err(err) if lost_the_race(&err) => {}
618- Err(err) => return Err(err.into()),
619- }
620- }
621- Err(AppError::Conflict(
622- "the menu kept changing underneath this cancellation",
623- ))
624- }
625-
626- pub async fn read(id: &MealBookingId, db: &Database) -> Result<Option<MealBooking>, AppError> {
627- Ok(db.select(id.record()).await?)
628- }
629-
630- /// Every booking on a menu, cancelled ones included — the kitchen's list.
631- pub async fn list_for_menu(
632- menu: &MenuId,
633- limit: Option<i64>,
634- offset: i64,
635- db: &Database,
636- ) -> Result<(Vec<MealBooking>, i64), AppError> {
637- PagedList::new(
638- "meal_booking WHERE menu = $menu",
639- "ORDER BY created_at DESC, id DESC",
640- )
641- .bind("menu", menu.record())
642- .run(limit, offset, db)
643- .await
644- }
645-
646- /// Every seat held for one of `students`, newest first — a caller's own
647- /// list is themselves plus whoever they hold a *live* parent link to.
648- ///
649- /// Deliberately **not** `booked_by = $usr`: who placed a booking is history
650- /// written onto a READONLY column, and history is not a read grant. A
651- /// parent whose link was revoked (by an unlink or by the student-side role
652- /// sweep) would otherwise keep a live view of the child's seat, watching
653- /// cancellations made long after the link died — exactly what
654- /// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The
655- /// caller re-derives the list from the links on every read, so the view
656- /// dies with the link.
657- pub async fn list_for_students(
658- students: &[UserId],
659- limit: Option<i64>,
660- offset: i64,
661- db: &Database,
662- ) -> Result<(Vec<MealBooking>, i64), AppError> {
663- PagedList::new(
664- "meal_booking WHERE student IN $students",
665- "ORDER BY created_at DESC, id DESC",
666- )
667- .bind(
668- "students",
669- students.iter().map(UserId::record).collect::<Vec<_>>(),
670- )
671- .run(limit, offset, db)
672- .await
673- }
674 }171 }
675 172
676 /// The school's meal deadline policy, resolved once per request: how many173 /// The school's meal deadline policy, resolved once per request: how many
@@ -686,8 +183,8 @@ impl MealBooking {
686 /// keeps a retired slot's history readable.183 /// keeps a retired slot's history readable.
687 #[derive(Debug, Clone, Default)]184 #[derive(Debug, Clone, Default)]
688 pub struct MealCutoff {185 pub struct MealCutoff {
689- minutes: Option<i64>,186+ pub(crate) minutes: Option<i64>,
690- slots: Vec<MealSlotDef>,187+ pub(crate) slots: Vec<MealSlotDef>,
691 }188 }
692 189
693 impl MealCutoff {190 impl MealCutoff {
@@ -743,7 +240,7 @@ fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp>
743 /// or not: a cancel *reverses* a charge, and money already taken has to stay240 /// or not: a cancel *reverses* a charge, and money already taken has to stay
744 /// reachable (that is the same reason manager+ bypasses the cutoff in241 /// reachable (that is the same reason manager+ bypasses the cutoff in
745 /// [`cancel_booking`](crate::web::meals)).242 /// [`cancel_booking`](crate::web::meals)).
746-fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> {243+pub(crate) fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> {
747 // An unparsable day is left to `check_cutoff`, which fails it closed244 // An unparsable day is left to `check_cutoff`, which fails it closed
748 // whenever a cutoff is configured: guessing "past" from text no calendar245 // whenever a cutoff is configured: guessing "past" from text no calendar
749 // can place would shut the canteen for a school that set no deadline.246 // can place would shut the canteen for a school that set no deadline.
@@ -780,7 +277,11 @@ fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> {
780 /// the one menu with no cutoff at all would be the one nobody meant to publish.277 /// the one menu with no cutoff at all would be the one nobody meant to publish.
781 /// Refusing is the only answer that keeps "the deadline binds every menu" true;278 /// Refusing is the only answer that keeps "the deadline binds every menu" true;
782 /// the menu has to be republished on a real day to become bookable again.279 /// the menu has to be republished on a real day to become bookable again.
783-fn check_cutoff(date: &MenuDate, slot: &MenuSlot, cutoff: &MealCutoff) -> Result<(), AppError> {280+pub(crate) fn check_cutoff(
281+ date: &MenuDate,
282+ slot: &MenuSlot,
283+ cutoff: &MealCutoff,
284+) -> Result<(), AppError> {
784 // A school with no cutoff configured closes nothing anyway, so an285 // A school with no cutoff configured closes nothing anyway, so an
785 // impossible date is not refused there either — that would take the canteen286 // impossible date is not refused there either — that would take the canteen
786 // offline for a deadline the school never set.287 // offline for a deadline the school never set.
@@ -814,7 +315,6 @@ mod tests {
814 use surrealdb::types::Value;315 use surrealdb::types::Value;
815 316
816 use super::*;317 use super::*;
817- use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish};
818 318
819 /// The `status` column is `TYPE string`: an object-wrapped enum would be319 /// The `status` column is `TYPE string`: an object-wrapped enum would be
820 /// rejected on write, and the `status = 'booked'` capacity count would320 /// rejected on write, and the `status = 'booked'` capacity count would
@@ -828,470 +328,6 @@ mod tests {
828 }328 }
829 }329 }
830 330
831- /// A published menu on a fresh in-memory database, plus a student. Dated
832- /// well ahead on purpose: a menu whose day has passed refuses every
833- /// booking, so a date the calendar overtakes would fail this whole module.
834- async fn menu(capacity: Option<i64>) -> (Database, MenuId) {
835- menu_on("2099-09-14", capacity).await
836- }
837-
838- async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
839- let db = crate::database::init_mem().await.unwrap();
840- let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
841- let menu = Menu::create(
842- MenuDate::try_new(date).unwrap(),
843- MenuSlot::try_new("lunch", &slots).unwrap(),
844- capacity,
845- &UserId::generate(),
846- &db,
847- )
848- .await
849- .unwrap();
850- (db, menu.get_id().clone())
851- }
852-
853- /// The stored counter, absent reading as zero — the number the cap's
854- /// `WHERE` actually compares, not one recomputed from the rows.
855- async fn seats(menu: &MenuId, db: &Database) -> i64 {
856- let mut result = db
857- .query("SELECT VALUE seats_booked FROM $id")
858- .bind(("id", menu.record()))
859- .await
860- .unwrap()
861- .check()
862- .unwrap();
863- result
864- .take::<Vec<Option<i64>>>(0)
865- .unwrap()
866- .into_iter()
867- .next()
868- .flatten()
869- .unwrap_or(0)
870- }
871-
872- async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
873- MenuDish::create(
874- menu,
875- DishName::try_new("çorba").unwrap(),
876- None,
877- DishPrice::try_new(price).unwrap(),
878- DishTags::try_new(&[], &[]).unwrap(),
879- db,
880- )
881- .await
882- .unwrap()
883- }
884-
885- /// The counter is the cap's authority, so it has to track the seats exactly:
886- /// a repeat booking must not count twice, a cancel must hand its seat back
887- /// in the same breath as the flip, and a second cancel must not hand back a
888- /// seat that was already returned (which would open the cap by one forever).
889- #[tokio::test]
890- async fn the_seat_counter_follows_the_seats_it_guards() {
891- let (db, menu) = menu(Some(1)).await;
892- let (ali, veli) = (UserId::generate(), UserId::generate());
893- let open = MealCutoff::default();
894-
895- let booking = MealBooking::book(&menu, &ali, &ali, &open, &db)
896- .await
897- .unwrap();
898- assert_eq!(seats(&menu, &db).await, 1);
899- // The same seat again is a no-op, not a second claim.
900- MealBooking::book(&menu, &ali, &ali, &open, &db)
901- .await
902- .unwrap();
903- assert_eq!(seats(&menu, &db).await, 1);
904- // …and the cap bites for anyone else while it is held.
905- assert!(matches!(
906- MealBooking::book(&menu, &veli, &veli, &open, &db).await,
907- Err(AppError::Conflict(_))
908- ));
909-
910- let cancelled = booking.cancel(&open, &ali, &db).await.unwrap();
911- assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
912- assert_eq!(seats(&menu, &db).await, 0);
913- // Cancelling again is idempotent all the way down to the counter.
914- cancelled.cancel(&open, &ali, &db).await.unwrap();
915- assert_eq!(seats(&menu, &db).await, 0);
916-
917- // The freed seat is real, and taking it again counts once.
918- let revived = MealBooking::book(&menu, &veli, &veli, &open, &db)
919- .await
920- .unwrap();
921- assert_eq!(revived.get_attempt(), 1);
922- assert_eq!(seats(&menu, &db).await, 1);
923- }
924-
925- /// A menu whose row is gone or whose seats are held refuses its own delete,
926- /// in the `WHERE` rather than in a read the delete then trusts.
927- #[tokio::test]
928- async fn a_held_seat_refuses_the_menu_delete() {
929- let (db, id) = menu(None).await;
930- let ali = UserId::generate();
931- let booking = MealBooking::book(&id, &ali, &ali, &MealCutoff::default(), &db)
932- .await
933- .unwrap();
934- let row = Menu::read(&id, &db).await.unwrap().unwrap();
935- assert!(matches!(
936- row.clone().delete(&db).await,
937- Err(AppError::Conflict(_))
938- ));
939- booking
940- .cancel(&MealCutoff::default(), &ali, &db)
941- .await
942- .unwrap();
943- assert!(row.delete(&db).await.is_ok());
944- }
945-
946- /// The price a seat is billed must be one the menu carried *at the moment
947- /// the seat was taken*. The claim carries the revision the price was read
948- /// at, so a dish written in between refuses it — this is that refusal,
949- /// driven by hand because no single-process interleaving can produce it.
950- #[tokio::test]
951- async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() {
952- let (db, menu) = menu(None).await;
953- let ali = UserId::generate();
954- let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
955- // A dish lands: the price a booking read a moment ago is now stale.
956- add_dish(&menu, 1_000, &db).await;
957- let row = MealBooking {
958- id: MealBookingId::composite(&menu, &ali),
959- menu: menu.clone(),
960- student: ali.clone(),
961- booked_by: ali,
962- status: MealBookingStatus::Booked,
963- attempt: 1,
964- price_minor: None,
965- cancelled_at: None,
966- created_at: Timestamp::now(),
967- };
968- let place = async |seen| {
969- MealBooking::claim_and_place(
970- &menu.record(),
971- cap::UNLIMITED,
972- seen,
973- &row,
974- None,
975- None,
976- &db,
977- )
978- .await
979- .unwrap()
980- };
981- assert!(
982- matches!(place(seen).await, Claimed::Full),
983- "a claim at a revision the menu has left must be refused"
984- );
985- assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");
986- assert!(
987- MealBooking::read(row.get_id(), &db)
988- .await
989- .unwrap()
990- .is_none(),
991- "the refused transaction must not leave the row behind either"
992- );
993-
994- // Re-read, and the same seat is taken with the row it belongs to.
995- let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
996- assert!(now > seen);
997- assert!(matches!(place(now).await, Claimed::Made(_)));
998- assert_eq!(seats(&menu, &db).await, 1);
999- // …and a second placement of that very row owes no second seat.
1000- assert!(matches!(place(now).await, Claimed::Duplicate));
1001- assert_eq!(
1002- seats(&menu, &db).await,
1003- 1,
1004- "a duplicate rolls its seat back"
1005- );
1006- }
1007-
1008- /// Every write that can move what a seat costs moves the revision — the
1009- /// half of the rule the CAS above cannot enforce by itself. A dish added,
1010- /// re-priced or removed, and the capacity moved: each must leave the menu at
1011- /// a revision no in-flight booking is still holding.
1012- #[tokio::test]
1013- async fn every_menu_write_that_moves_the_price_moves_the_revision() {
1014- let (db, id) = menu(None).await;
1015- let mut seen = 0;
1016- let mut moved = async |db: &Database| {
1017- let now = Menu::read(&id, db).await.unwrap().unwrap().get_version();
1018- let stepped = now > seen;
1019- seen = now;
1020- stepped
1021- };
1022- assert!(!moved(&db).await, "a fresh menu starts where it starts");
1023-
1024- let dish = add_dish(&id, 1_000, &db).await;
1025- assert!(moved(&db).await, "a dish added");
1026- let dish = dish
1027- .update(
1028- None,
1029- None,
1030- Some(DishPrice::try_new(2_000).unwrap()),
1031- None,
1032- &db,
1033- )
1034- .await
1035- .unwrap();
1036- assert!(moved(&db).await, "a dish re-priced");
1037- dish.delete(&db).await.unwrap();
1038- assert!(moved(&db).await, "a dish removed");
1039- Menu::read(&id, &db)
1040- .await
1041- .unwrap()
1042- .unwrap()
1043- .update(Some(Some(5)), &db)
1044- .await
1045- .unwrap();
1046- assert!(moved(&db).await, "the capacity moved");
1047- }
1048-
1049- /// A booking placed after a price edit is billed the new price, and one
1050- /// placed before keeps the old one — the seat's `price_minor` is history,
1051- /// never re-read from the menu.
1052- #[tokio::test]
1053- async fn a_seat_keeps_the_price_it_was_taken_at() {
1054- let (db, menu) = menu(None).await;
1055- let (ali, veli) = (UserId::generate(), UserId::generate());
1056- let open = MealCutoff::default();
1057- add_dish(&menu, 1_000, &db).await;
1058-
1059- let early = MealBooking::book(&menu, &ali, &ali, &open, &db)
1060- .await
1061- .unwrap();
1062- add_dish(&menu, 500, &db).await;
1063- let late = MealBooking::book(&menu, &veli, &veli, &open, &db)
1064- .await
1065- .unwrap();
1066-
1067- assert_eq!(
1068- early.get_price_minor().map(LedgerAmount::as_minor),
1069- Some(1_000)
1070- );
1071- assert_eq!(
1072- late.get_price_minor().map(LedgerAmount::as_minor),
1073- Some(1_500)
1074- );
1075- // The seat taken before the second dish is not re-billed for it.
1076- let held = MealBooking::book(&menu, &ali, &ali, &open, &db)
1077- .await
1078- .unwrap();
1079- assert_eq!(
1080- held.get_price_minor().map(LedgerAmount::as_minor),
1081- Some(1_000)
1082- );
1083- }
1084-
1085- /// A cancel that lost its flip may only refund the attempt it was actually
1086- /// cancelling. Driven against the predicate rather than through `cancel`:
1087- /// the row is re-read *inside* the call, so the only way it can disagree
1088- /// with what the flip found is a genuine concurrent write, which no
1089- /// single-process interleaving (and no in-memory engine) can stage.
1090- #[tokio::test]
1091- async fn a_lost_flip_refunds_only_the_attempt_it_released() {
1092- let (db, menu) = menu(None).await;
1093- let (ali, veli) = (UserId::generate(), UserId::generate());
1094- let open = MealCutoff::default();
1095- add_dish(&menu, 1_000, &db).await;
1096-
1097- let seen = MealBooking::book(&menu, &ali, &ali, &open, &db)
1098- .await
1099- .unwrap();
1100- let cancelled = seen.clone().cancel(&open, &ali, &db).await.unwrap();
1101- // The seat this cancel released: its own attempt, still cancelled.
1102- assert!(MealBooking::refundable_after_lost_flip(&seen, &cancelled).unwrap());
1103-
1104- // A re-book landed in the window. The row is `booked` again with a live
1105- // charge against it — refunding that frees money for a seat that is
1106- // still held, and burns the ledger id its own cancel will need. The
1107- // caller is refused rather than told it cancelled something.
1108- let rebooked = MealBooking::book(&menu, &ali, &ali, &open, &db)
1109- .await
1110- .unwrap();
1111- assert_eq!(rebooked.get_attempt(), seen.get_attempt() + 1);
1112- assert!(matches!(
1113- MealBooking::refundable_after_lost_flip(&seen, &rebooked),
1114- Err(AppError::Conflict(_))
1115- ));
1116-
1117- // Re-booked *and* cancelled again: that cancel appended the reversal
1118- // for its own attempt, and this call has nothing left to heal.
1119- let later = rebooked.cancel(&open, &ali, &db).await.unwrap();
1120- assert!(!MealBooking::refundable_after_lost_flip(&seen, &later).unwrap());
1121-
1122- // And the ordinary lost race — another cancel of the same attempt got
1123- // there first — still replays the refund, which is what heals a cancel
1124- // cut short between the flip and the ledger line.
1125- let other = MealBooking::book(&menu, &veli, &veli, &open, &db)
1126- .await
1127- .unwrap();
1128- let freed = other.clone().cancel(&open, &veli, &db).await.unwrap();
1129- assert!(MealBooking::refundable_after_lost_flip(&other, &freed).unwrap());
1130- }
1131-
1132- /// A cancel may only ever release the attempt it read. The stale handle
1133- /// here is what a cancel holds across its own `Menu::read` round trip: by
1134- /// the time the flip runs, that seat has been cancelled and taken again, so
1135- /// the flip must refuse — unfenced it cancelled the *new* attempt, freeing a
1136- /// seat the API had just answered `201` for, without refunding it (the
1137- /// reversal is keyed to the stale attempt, which is already refunded) and
1138- /// burning the new attempt's own reversal id for good.
1139- #[tokio::test]
1140- async fn a_cancel_cannot_release_an_attempt_it_never_read() {
1141- let (db, menu) = menu(Some(1)).await;
1142- let (ali, veli) = (UserId::generate(), UserId::generate());
1143- let open = MealCutoff::default();
1144- add_dish(&menu, 1_000, &db).await;
1145-
1146- let stale = MealBooking::book(&menu, &ali, &ali, &open, &db)
1147- .await
1148- .unwrap();
1149- stale.clone().cancel(&open, &ali, &db).await.unwrap();
1150- let live = MealBooking::book(&menu, &ali, &ali, &open, &db)
1151- .await
1152- .unwrap();
1153- assert_eq!(live.get_attempt(), stale.get_attempt() + 1);
1154-
1155- assert!(
1156- MealBooking::release_seat(&stale, &ali, &db)
1157- .await
1158- .unwrap()
1159- .is_none(),
1160- "the attempt this call read is gone, so it releases nothing"
1161- );
1162- // Stored state, not the returned value: the mem engine forges wins.
1163- let stored = MealBooking::read(live.get_id(), &db)
1164- .await
1165- .unwrap()
1166- .unwrap();
1167- assert_eq!(stored.get_status(), MealBookingStatus::Booked);
1168- assert_eq!(stored.get_attempt(), live.get_attempt());
1169- assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
1170- assert_eq!(
1171- MealLedger::balance_of(&ali, &db).await.unwrap(),
1172- -1_000,
1173- "the live attempt's charge stands: it was never cancelled"
1174- );
1175- // The seat is still really held — the cap says so too.
1176- assert!(matches!(
1177- MealBooking::book(&menu, &veli, &veli, &open, &db).await,
1178- Err(AppError::Conflict(_))
1179- ));
1180- }
1181-
1182- /// The seat may not come back without the money. Driven against
1183- /// [`MealBooking::release_seat`] rather than through `cancel`, because what
1184- /// is under test is precisely what a *crash right after the flip* leaves
1185- /// behind: appended a write later, the reversal is lost with the process,
1186- /// and a re-book then moves the row to the next attempt and locks the
1187- /// `(booking, attempt)` reversal id out for good — the charge is
1188- /// unreversible by any route on the API.
1189- #[tokio::test]
1190- async fn the_seat_cannot_be_freed_without_its_refund() {
1191- let (db, menu) = menu(None).await;
1192- let ali = UserId::generate();
1193- let open = MealCutoff::default();
1194- add_dish(&menu, 1_000, &db).await;
1195- let booked = MealBooking::book(&menu, &ali, &ali, &open, &db)
1196- .await
1197- .unwrap();
1198-
1199- // The flip alone — nothing else runs afterwards, as after a crash.
1200- let freed = MealBooking::release_seat(&booked, &ali, &db)
1201- .await
1202- .unwrap()
1203- .expect("the seat was held, so the flip must take it back");
1204- assert_eq!(freed.get_status(), MealBookingStatus::Cancelled);
1205- assert_eq!(seats(&menu, &db).await, 0);
1206- assert_eq!(
1207- MealLedger::balance_of(&ali, &db).await.unwrap(),
1208- 0,
1209- "the reversal must have committed with the flip, not after it"
1210- );
1211-
1212- // And the re-book that used to strand the charge now finds it settled:
1213- // a fresh attempt, billed once more, with the old one squared away.
1214- MealBooking::book(&menu, &ali, &ali, &open, &db)
1215- .await
1216- .unwrap();
1217- assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
1218- }
1219-
1220- /// The seat may not be held without its money. Driven against
1221- /// [`MealBooking::claim_and_place`] rather than through `book`, because what
1222- /// is under test is precisely what the gap between the two writes leaves
1223- /// behind: a cancel landing there finds no charge to reverse, reverses
1224- /// nothing, and the charge then lands anyway — a student holding no seat and
1225- /// owing money, with the `(booking, attempt)` reversal id burnt for good.
1226- #[tokio::test]
1227- async fn the_seat_cannot_be_claimed_without_its_charge() {
1228- let (db, menu) = menu(None).await;
1229- let ali = UserId::generate();
1230- add_dish(&menu, 1_000, &db).await;
1231- let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
1232- let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
1233- let row = MealBooking {
1234- id: MealBookingId::composite(&menu, &ali),
1235- menu: menu.clone(),
1236- student: ali.clone(),
1237- booked_by: ali.clone(),
1238- status: MealBookingStatus::Booked,
1239- attempt: 1,
1240- price_minor: price,
1241- cancelled_at: None,
1242- created_at: Timestamp::now(),
1243- };
1244- let charge = MealLedger::charge_for(&row, &ali);
1245- // The claim alone — nothing else runs afterwards, as after a crash.
1246- let place = async || {
1247- MealBooking::claim_and_place(
1248- &menu.record(),
1249- cap::UNLIMITED,
1250- seen,
1251- &row,
1252- price,
1253- charge.as_ref(),
1254- &db,
1255- )
1256- .await
1257- .unwrap()
1258- };
1259- assert!(matches!(place().await, Claimed::Made(_)));
1260- assert_eq!(seats(&menu, &db).await, 1);
1261- assert_eq!(
1262- MealLedger::balance_of(&ali, &db).await.unwrap(),
1263- -1_000,
1264- "the charge must have committed with the claim, not after it"
1265- );
1266-
1267- // Replayed: the seat is already held, so the whole transaction rolls
1268- // back — no second seat and, just as importantly, no second charge.
1269- assert!(matches!(place().await, Claimed::Duplicate));
1270- assert_eq!(seats(&menu, &db).await, 1);
1271- assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
1272- }
1273-
1274- /// A free menu owes no refund, so the flip must carry no ledger line at all
1275- /// — the branch the reversal's conditional statement adds.
1276- #[tokio::test]
1277- async fn a_seat_that_was_never_billed_frees_without_a_line() {
1278- let (db, menu) = menu(None).await;
1279- let ali = UserId::generate();
1280- let booked = MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db)
1281- .await
1282- .unwrap();
1283-
1284- MealBooking::release_seat(&booked, &ali, &db)
1285- .await
1286- .unwrap()
1287- .expect("a free seat is still a seat");
1288- assert_eq!(seats(&menu, &db).await, 0);
1289- let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
1290- .await
1291- .unwrap();
1292- assert!(lines.is_empty() && total == 0, "a free seat moves no money");
1293- }
1294-
1295 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {331 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
1296 MealCutoff {332 MealCutoff {
1297 minutes,333 minutes,
@@ -1382,100 +418,6 @@ mod tests {
1382 assert!(check_day_not_past(&impossible).is_ok());418 assert!(check_day_not_past(&impossible).is_ok());
1383 }419 }
1384 420
1385- /// The charge hole itself: a menu whose day has gone by must take no seat
1386- /// and mint no ledger line, with the shipped defaults in force.
1387- #[tokio::test]
1388- async fn a_past_day_takes_no_seat_and_writes_no_charge() {
1389- let (db, menu) = menu_on("2020-01-06", None).await;
1390- let ali = UserId::generate();
1391- add_dish(&menu, 4550, &db).await;
1392-
1393- assert!(matches!(
1394- MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await,
1395- Err(AppError::Conflict(_))
1396- ));
1397- assert_eq!(seats(&menu, &db).await, 0);
1398- let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
1399- .await
1400- .unwrap();
1401- assert!(
1402- lines.is_empty() && total == 0,
1403- "a refused booking bills nothing"
1404- );
1405- }
1406-
1407- /// The documented decision the past-day guard must not swallow: today's
1408- /// menu, on a slot with no serving hour, books exactly as it always did —
1409- /// with the cutoff knob set *and* unset.
1410- #[tokio::test]
1411- async fn todays_menu_still_books_without_a_serving_hour() {
1412- let (db, menu) = menu_on(&today(), None).await;
1413- let ali = UserId::generate();
1414- MealBooking::book(&menu, &ali, &ali, &cutoff(Some(60), None), &db)
1415- .await
1416- .expect("an unset serving hour is an unenforced cutoff");
1417- assert_eq!(seats(&menu, &db).await, 1);
1418- }
1419-
1420- /// Cancelling stays open on a day already gone — that is how money already
1421- /// taken is given back, and it is the same reason manager+ bypasses the
1422- /// cutoff. The guard binds `book` alone.
1423- #[tokio::test]
1424- async fn a_past_day_still_gives_the_seat_and_the_money_back() {
1425- let (db, menu) = menu_on("2020-01-06", None).await;
1426- let ali = UserId::generate();
1427- add_dish(&menu, 4550, &db).await;
1428- // The seat this student is holding was taken while the day was still
1429- // ahead — the shape the create-side check cannot reach. A test cannot
1430- // age a menu (`date` is READONLY), so the seat is placed on an
1431- // already-past menu by the very transaction `book` places it with.
1432- let fresh = Menu::read(&menu, &db).await.unwrap().unwrap();
1433- let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
1434- let row = MealBooking {
1435- id: MealBookingId::composite(&menu, &ali),
1436- menu: menu.clone(),
1437- student: ali.clone(),
1438- booked_by: ali.clone(),
1439- status: MealBookingStatus::Booked,
1440- attempt: 1,
1441- price_minor: price,
1442- cancelled_at: None,
1443- created_at: Timestamp::now(),
1444- };
1445- let charge = MealLedger::charge_for(&row, &ali);
1446- let booked = match MealBooking::claim_and_place(
1447- &menu.record(),
1448- cap::UNLIMITED,
1449- fresh.get_version(),
1450- &row,
1451- price,
1452- charge.as_ref(),
1453- &db,
1454- )
1455- .await
1456- .unwrap()
1457- {
1458- Claimed::Made(booking) => booking,
1459- _ => panic!("the seat was free"),
1460- };
1461- assert_eq!(seats(&menu, &db).await, 1);
1462-
1463- assert!(matches!(
1464- MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await,
1465- Err(AppError::Conflict(_)),
1466- ));
1467- let cancelled = booked
1468- .cancel(&MealCutoff::default(), &ali, &db)
1469- .await
1470- .expect("a cancel on a past day still frees the seat");
1471- assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
1472- assert_eq!(seats(&menu, &db).await, 0);
1473- let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db)
1474- .await
1475- .unwrap();
1476- assert_eq!(lines.len(), 2, "the charge and its reversal");
1477- }
1478-
1479 /// The instant the deadline counts back from: midnight UTC of the day plus421 /// The instant the deadline counts back from: midnight UTC of the day plus
1480 /// the slot's serving minute. The `None` case still resolves to midnight,422 /// the slot's serving minute. The `None` case still resolves to midnight,
1481 /// but only as the date's validity probe — `check_cutoff` never counts a423 /// but only as the date's validity probe — `check_cutoff` never counts a
src/domain/meal_ledger.rsmodified+8 -5
@@ -370,7 +370,8 @@ impl MealLedger {
370 /// The price comes off the *booking row*, never off the menu as it stands370 /// The price comes off the *booking row*, never off the menu as it stands
371 /// now: a seat taken while the menu was free carries `None` forever, so371 /// now: a seat taken while the menu was free carries `None` forever, so
372 /// "was free" is a recorded fact and a later dish never bills a seat372 /// "was free" is a recorded fact and a later dish never bills a seat
373- /// retroactively. Called from [`MealBooking::book`] alone, right after the seat373+ /// retroactively. Called from
374+ /// [`book`](crate::service::meal_booking::book) alone, right after the seat
374 /// was claimed, so the seat and its money move together.375 /// was claimed, so the seat and its money move together.
375 ///376 ///
376 /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate377 /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate
@@ -389,7 +390,7 @@ impl MealLedger {
389 }390 }
390 391
391 /// The charge `booking`'s current attempt owes — the line392 /// The charge `booking`'s current attempt owes — the line
392- /// [`MealBooking::claim_and_place`] appends inside the very transaction that393+ /// [`claim_and_place`](crate::db::meal_booking::claim_and_place) appends inside the very transaction that
393 /// takes the seat. `None` when the menu was free, which owes no line.394 /// takes the seat. `None` when the menu was free, which owes no line.
394 ///395 ///
395 /// Only the row is built here; whether it is already there is a read, and396 /// Only the row is built here; whether it is already there is a read, and
@@ -423,9 +424,10 @@ impl MealLedger {
423 ///424 ///
424 /// Keyed by `(booking, attempt)` like the charge, so a retried cancel425 /// Keyed by `(booking, attempt)` like the charge, so a retried cancel
425 /// refunds once. The line normally lands *inside* the flip's own426 /// refunds once. The line normally lands *inside* the flip's own
426- /// transaction ([`MealBooking::release_seat`]); this path is what heals a427+ /// transaction
428+ /// ([`release_seat`](crate::db::meal_booking::release_seat)); this path is what heals a
427 /// seat flipped before that was true, and it is why429 /// seat flipped before that was true, and it is why
428- /// [`MealBooking::cancel`] replays it on an already-cancelled row instead430+ /// [`cancel`](crate::service::meal_booking::cancel) replays it on an already-cancelled row instead
429 /// of refusing it. Nothing else on the API can append the missing line.431 /// of refusing it. Nothing else on the API can append the missing line.
430 pub async fn reverse_booking(432 pub async fn reverse_booking(
431 booking: &MealBooking,433 booking: &MealBooking,
@@ -443,7 +445,8 @@ impl MealLedger {
443 }445 }
444 446
445 /// The refund `booking`'s current attempt owes, as `(the charge it undoes,447 /// The refund `booking`'s current attempt owes, as `(the charge it undoes,
446- /// the reversal line)` — the two ids [`MealBooking::release_seat`] needs to448+ /// the reversal line)` — the two ids
449+ /// [`release_seat`](crate::db::meal_booking::release_seat) needs to
447 /// append the money back inside the transaction that frees the seat.450 /// append the money back inside the transaction that frees the seat.
448 /// `None` when the seat was never billed (a free menu), which owes no line.451 /// `None` when the seat was never billed (a free menu), which owes no line.
449 ///452 ///
src/service/meal_booking.rsadded+583 -0
@@ -0,0 +1,583 @@
1+//! Meal-booking workflows: taking a seat and giving it back, with the seat's
2+//! money folded into the very decision that moves it. Both writes are single
3+//! transactions in [`crate::db::meal_booking`] — [`book`] prices the seat,
4+//! claims it at the revision it priced against
5+//! ([`meal_booking::claim_and_place`]) and bills it in that same
6+//! transaction; [`cancel`] re-reads, re-checks the deadline, frees the seat
7+//! and reverses the charge through [`meal_booking::release_seat`] and its
8+//! heal-up paths.
9+//!
10+//! **No process-wide lock guards this domain**, and deliberately: every
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
15+//! service layer owns here is the *sequence*: read the menu, refuse a past
16+//! day or a closed cutoff before anything is claimed, settle the attempt
17+//! number before the charge id exists, and map the claim's outcomes
18+//! (made / duplicate / full) onto answers on fresh reads.
19+
20+use crate::constant::{CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS};
21+use crate::database::{Database, backoff};
22+use crate::db::cap;
23+use crate::db::meal_booking;
24+use crate::domain::meal_booking::{
25+ MealBooking, MealBookingId, MealBookingStatus, MealCutoff, check_cutoff, check_day_not_past,
26+};
27+use crate::domain::meal_ledger::MealLedger;
28+use crate::domain::menu::{Menu, MenuId};
29+use crate::domain::timestamp::Timestamp;
30+use crate::domain::user::UserId;
31+use crate::error::AppError;
32+
33+/// Book (idempotently) `student` onto `menu` **and bill the seat**. Already
34+/// booked is returned as-is, claiming nothing; a cancelled row is revived as
35+/// a fresh attempt at the current price. A full menu refuses the seat (409),
36+/// decided by the counter's own `WHERE` rather than by a count this process
37+/// took a moment ago.
38+///
39+/// The price is read from the menu and then **claimed with it**: the seat is
40+/// only taken while the menu still stands at the revision the price was read
41+/// at, so a dish added, re-priced or removed in that gap loses the claim and
42+/// the whole decision is made again on fresh figures. What is frozen onto
43+/// the row is therefore always a price the menu genuinely carried at the
44+/// instant the seat was taken — a guarantee a lock around the read could
45+/// not give, since the price is read a round trip before the claim.
46+///
47+/// The charge rides that same transaction, keyed by (seat, attempt): eight
48+/// concurrent `POST`s of one seat hold one seat and write one charge line.
49+/// The price is `None` when the menu is free, and that `None` is stored, so
50+/// a dish added later never bills a seat retroactively.
51+///
52+/// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
53+/// serving time is that close, the seat is fixed either way.
54+pub async fn book(
55+ db: &Database,
56+ menu: &MenuId,
57+ student: &UserId,
58+ booked_by: &UserId,
59+ cutoff: &MealCutoff,
60+) -> Result<MealBooking, AppError> {
61+ let id = MealBookingId::composite(menu, student);
62+ let seats = menu.record();
63+ for attempt in 0..CAP_WRITE_TRIES {
64+ backoff(attempt).await;
65+ let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
66+ check_day_not_past(fresh.get_date())?;
67+ check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
68+ let existing: Option<MealBooking> = meal_booking::read(db, &id).await?;
69+ // The seat is already held: same attempt, same price it was taken
70+ // at. Today's menu price bills nobody who booked yesterday's. No
71+ // seat is claimed, so a double-click cannot count two.
72+ //
73+ // Answered *before* the menu is priced, and that ordering is the
74+ // rule: pricing first made a repeat POST of a seat already held 400
75+ // ("amount_minor must be between…") as soon as the menu's dishes
76+ // summed past the chargeable maximum — refusing to replay a seat
77+ // the student holds, over a price that seat was never going to be
78+ // billed.
79+ if let Some(held) = existing
80+ .clone()
81+ .filter(|row| row.status == MealBookingStatus::Booked)
82+ {
83+ MealLedger::charge_booking(&held, booked_by, db).await?;
84+ // Answered off a re-read, never off the row read a round trip
85+ // ago: a cancel committing in that gap has freed the seat,
86+ // given the money back and left the row `cancelled`, and
87+ // returning `held` then reports a seat — `"status": "booked"`,
88+ // `cancelled_at: null` — the store does not hold. The stored
89+ // state was right all along; only the answer lied. Gone or
90+ // cancelled, the decision is simply made again, exactly as
91+ // `Claimed::Duplicate` below does, so the caller ends up with
92+ // the seat they asked for rather than a `201` about a seat
93+ // somebody already released.
94+ match meal_booking::read(db, &id).await? {
95+ Some(live) if live.status == MealBookingStatus::Booked => return Ok(live),
96+ _ => continue,
97+ }
98+ }
99+ // The attempt is settled *here*, not by the revival's `attempt + 1`,
100+ // because the charge id is (seat, attempt) and the charge has to be
101+ // built before the transaction that writes it. `existing` is either
102+ // absent or cancelled — a booked row returned above.
103+ let attempt = existing.as_ref().map_or(1, |prior| prior.attempt + 1);
104+ // A seat retaken without end is a ledger without end: each cycle
105+ // appends a charge and its reversal, both permanent, and every
106+ // later balance read is answered over the lot. Refused *before* the
107+ // menu is priced, so the answer is the ceiling rather than whatever
108+ // the pricing happens to say. A row already past the ceiling — an
109+ // upgrade's leftovers — is untouched by this: cancelling consults
110+ // no cap, so its seat and its money stay reachable, and only one
111+ // more revival is refused.
112+ if attempt > MAX_MEAL_BOOKING_ATTEMPTS {
113+ return Err(AppError::Conflict(
114+ "this seat has been booked and cancelled its maximum number of times",
115+ ));
116+ }
117+ // Before the seat: an unchargeable menu (dishes summing past the
118+ // cap) must refuse the booking outright, never leave a
119+ // booked-but-unbilled row behind.
120+ let price = MealLedger::price_snapshot(menu, db).await?;
121+ let fresh_row = MealBooking {
122+ id: id.clone(),
123+ menu: menu.clone(),
124+ student: student.clone(),
125+ booked_by: booked_by.clone(),
126+ status: MealBookingStatus::Booked,
127+ attempt,
128+ price_minor: price,
129+ cancelled_at: None,
130+ created_at: Timestamp::now(),
131+ };
132+ let charge = MealLedger::charge_for(&fresh_row, booked_by);
133+ match meal_booking::claim_and_place(
134+ db,
135+ &seats,
136+ fresh.get_capacity().unwrap_or(cap::UNLIMITED),
137+ fresh.get_version(),
138+ &fresh_row,
139+ price,
140+ charge.as_ref(),
141+ )
142+ .await?
143+ {
144+ // Seat, row and charge committed together; nothing is owed
145+ // after this call, which is the whole point of folding them.
146+ cap::Claimed::Made(booking) => return Ok(booking),
147+ // Another `POST` of this very pair moved the row first, and this
148+ // caller never took a seat (the whole transaction rolled back).
149+ // The decision is simply made again rather than answered off a
150+ // row read here: the winner may have left it `cancelled` at an
151+ // attempt this call never saw, and the loop's own held-seat path
152+ // is what returns a live seat *and* replays its charge.
153+ cap::Claimed::Duplicate => continue,
154+ // Full, moved, or gone — one `WHERE` refused all three, so the
155+ // reason is re-read rather than guessed. A moved menu is not a
156+ // refusal: the price above is stale, so price and seat are
157+ // taken again together.
158+ cap::Claimed::Full => match Menu::read(menu, db).await? {
159+ None => return Err(AppError::NotFound),
160+ Some(now) if now.get_version() != fresh.get_version() => continue,
161+ Some(_) => return Err(AppError::Conflict("the menu is fully booked")),
162+ },
163+ }
164+ }
165+ Err(AppError::Conflict(
166+ "the menu kept changing underneath this booking",
167+ ))
168+}
169+
170+/// The row, for callers that only inspect it — the web layer's authorization
171+/// gates read through here.
172+pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> {
173+ meal_booking::read(db, id).await
174+}
175+
176+/// Every booking on a menu, cancelled ones included — the kitchen's list.
177+pub async fn list_for_menu(
178+ db: &Database,
179+ menu: &MenuId,
180+ limit: Option<i64>,
181+ offset: i64,
182+) -> Result<(Vec<MealBooking>, i64), AppError> {
183+ meal_booking::list_for_menu(db, menu, limit, offset).await
184+}
185+
186+/// Every seat held for one of `students`, newest first — a caller's own
187+/// list is themselves plus whoever they hold a *live* parent link to.
188+/// The links are re-derived by the caller on every read, so the view dies
189+/// with the link.
190+pub async fn list_for_students(
191+ db: &Database,
192+ students: &[UserId],
193+ limit: Option<i64>,
194+ offset: i64,
195+) -> Result<(Vec<MealBooking>, i64), AppError> {
196+ meal_booking::list_for_students(db, students, limit, offset).await
197+}
198+
199+/// Free the seat: flip to `cancelled`, stamp the moment, **and give the
200+/// money back**. Refused (409) only once the cutoff has passed.
201+///
202+/// The row is re-read here and the flip is conditional on it still being
203+/// `booked`: the caller's copy may predate a concurrent re-book, and
204+/// cancelling a stale attempt would strand that attempt's charge forever.
205+/// The reversal is keyed to the attempt, so a retried cancel refunds once.
206+///
207+/// **The refund is not a second write.** It is appended by the very
208+/// transaction that flips the row (see
209+/// [`meal_booking::release_seat`]), so a
210+/// handler future dropped mid-cancel, a proxy timing out or the store going
211+/// away cannot leave the seat free with the charge standing — the state a
212+/// re-book then made permanent, since every ledger id carries the attempt
213+/// the re-book has already moved past.
214+///
215+/// **Idempotent all the same**, which is what heals a seat flipped before
216+/// that was true: a cancelled row replays the reversal instead of being
217+/// refused, and that either completes an old missing line or writes nothing
218+/// at all. The cutoff is not re-checked on that path: the seat is already
219+/// given back, and refusing to finish the refund because the meal has since
220+/// closed would strand the money exactly as before.
221+pub async fn cancel(
222+ db: &Database,
223+ cancelled: MealBooking,
224+ cutoff: &MealCutoff,
225+ recorded_by: &UserId,
226+) -> Result<MealBooking, AppError> {
227+ let fresh = meal_booking::read(db, &cancelled.id)
228+ .await?
229+ .ok_or(AppError::NotFound)?;
230+ if fresh.status == MealBookingStatus::Cancelled {
231+ MealLedger::reverse_booking(&fresh, recorded_by, db).await?;
232+ return Ok(fresh);
233+ }
234+ let menu = Menu::read(&fresh.menu, db)
235+ .await?
236+ .ok_or(AppError::NotFound)?;
237+ check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
238+ // Lost the flip: the row is no longer the `booked` attempt this call
239+ // read — another cancel took the seat back first, or a booking took it
240+ // again. Its row is the truth, but only the attempt *this* call was
241+ // cancelling may be refunded off it (see [`refundable_after_lost_flip`]).
242+ let saved = match meal_booking::release_seat(db, &fresh, recorded_by).await? {
243+ Some(cancelled) => cancelled,
244+ None => {
245+ let live = meal_booking::read(db, &cancelled.id)
246+ .await?
247+ .ok_or(AppError::NotFound)?;
248+ if !refundable_after_lost_flip(&fresh, &live)? {
249+ return Ok(live);
250+ }
251+ live
252+ }
253+ };
254+ MealLedger::reverse_booking(&saved, recorded_by, db).await?;
255+ Ok(saved)
256+}
257+
258+/// May a cancel that released *nothing* still refund what it read?
259+///
260+/// Only when the row it finds is the very attempt it was cancelling, still
261+/// cancelled. A cancel is two writes, and between them the seat can be
262+/// re-booked: the row then reads `booked` at attempt N+1 with a live charge
263+/// against it, and reversing that — as re-reading and refunding blindly did
264+/// — refunds a seat that is still held *and* still counted, and burns the
265+/// `(booking, attempt)` ledger id that attempt's own cancel needs, so it
266+/// could never be refunded afterwards. A row at another attempt is the same
267+/// story one step further on: whoever cancelled attempt N appended its
268+/// reversal, and this call has nothing left to heal.
269+///
270+/// A seat that is `booked` again is a **409**, not a `200`: the flip was
271+/// fenced on the attempt this call read, so the row can only be held by a
272+/// booking that landed inside this very cancel — one the API answered `201`
273+/// for and which no caller here has seen, let alone decided to free. `200`
274+/// with a `booked` row would report a cancellation that did not happen; the
275+/// client is told to look again instead, and a fresh `DELETE` then cancels
276+/// the attempt it really read. (A repeat cancel of an *unchanged* seat never
277+/// reaches here: [`cancel`] answers an already-cancelled row above.)
278+fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result<bool, AppError> {
279+ if live.status == MealBookingStatus::Booked {
280+ return Err(AppError::Conflict(
281+ "the seat was booked again while this cancellation ran",
282+ ));
283+ }
284+ Ok(live.attempt == seen.attempt)
285+}
286+
287+#[cfg(test)]
288+mod tests {
289+ use super::*;
290+ use crate::database::init_mem;
291+ use crate::domain::meal_booking::MealBookingStatus;
292+ use crate::domain::meal_ledger::LedgerAmount;
293+ use crate::domain::menu::{Menu, MenuDate, MenuSlot};
294+ use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish};
295+ use crate::domain::settings::MealSlotDef;
296+
297+ /// A published menu on a fresh in-memory database, plus a student. Dated
298+ /// well ahead on purpose: a menu whose day has passed refuses every
299+ /// booking, so a date the calendar overtakes would fail this whole module.
300+ async fn menu(capacity: Option<i64>) -> (Database, MenuId) {
301+ menu_on("2099-09-14", capacity).await
302+ }
303+
304+ async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
305+ let db = init_mem().await.unwrap();
306+ let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
307+ let menu = Menu::create(
308+ MenuDate::try_new(date).unwrap(),
309+ MenuSlot::try_new("lunch", &slots).unwrap(),
310+ capacity,
311+ &UserId::generate(),
312+ &db,
313+ )
314+ .await
315+ .unwrap();
316+ (db, menu.get_id().clone())
317+ }
318+
319+ /// The stored counter, absent reading as zero — the number the cap's
320+ /// `WHERE` actually compares, not one recomputed from the rows.
321+ async fn seats(menu: &MenuId, db: &Database) -> i64 {
322+ let mut result = db
323+ .query("SELECT VALUE seats_booked FROM $id")
324+ .bind(("id", menu.record()))
325+ .await
326+ .unwrap()
327+ .check()
328+ .unwrap();
329+ result
330+ .take::<Vec<Option<i64>>>(0)
331+ .unwrap()
332+ .into_iter()
333+ .next()
334+ .flatten()
335+ .unwrap_or(0)
336+ }
337+
338+ async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
339+ MenuDish::create(
340+ menu,
341+ DishName::try_new("çorba").unwrap(),
342+ None,
343+ DishPrice::try_new(price).unwrap(),
344+ DishTags::try_new(&[], &[]).unwrap(),
345+ db,
346+ )
347+ .await
348+ .unwrap()
349+ }
350+
351+ /// The counter is the cap's authority, so it has to track the seats exactly:
352+ /// a repeat booking must not count twice, a cancel must hand its seat back
353+ /// in the same breath as the flip, and a second cancel must not hand back a
354+ /// seat that was already returned (which would open the cap by one forever).
355+ #[tokio::test]
356+ async fn the_seat_counter_follows_the_seats_it_guards() {
357+ let (db, menu) = menu(Some(1)).await;
358+ let (ali, veli) = (UserId::generate(), UserId::generate());
359+ let open = MealCutoff::default();
360+
361+ let booking = book(&db, &menu, &ali, &ali, &open).await.unwrap();
362+ assert_eq!(seats(&menu, &db).await, 1);
363+ // The same seat again is a no-op, not a second claim.
364+ book(&db, &menu, &ali, &ali, &open).await.unwrap();
365+ assert_eq!(seats(&menu, &db).await, 1);
366+ // …and the cap bites for anyone else while it is held.
367+ assert!(matches!(
368+ book(&db, &menu, &veli, &veli, &open).await,
369+ Err(AppError::Conflict(_))
370+ ));
371+
372+ let cancelled = cancel(&db, booking, &open, &ali).await.unwrap();
373+ assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
374+ assert_eq!(seats(&menu, &db).await, 0);
375+ // Cancelling again is idempotent all the way down to the counter.
376+ cancel(&db, cancelled, &open, &ali).await.unwrap();
377+ assert_eq!(seats(&menu, &db).await, 0);
378+
379+ // The freed seat is real, and taking it again counts once.
380+ let revived = book(&db, &menu, &veli, &veli, &open).await.unwrap();
381+ assert_eq!(revived.get_attempt(), 1);
382+ assert_eq!(seats(&menu, &db).await, 1);
383+ }
384+
385+ /// A menu whose row is gone or whose seats are held refuses its own delete,
386+ /// in the `WHERE` rather than in a read the delete then trusts.
387+ #[tokio::test]
388+ async fn a_held_seat_refuses_the_menu_delete() {
389+ let (db, id) = menu(None).await;
390+ let ali = UserId::generate();
391+ let booking = book(&db, &id, &ali, &ali, &MealCutoff::default())
392+ .await
393+ .unwrap();
394+ let row = Menu::read(&id, &db).await.unwrap().unwrap();
395+ assert!(matches!(
396+ row.clone().delete(&db).await,
397+ Err(AppError::Conflict(_))
398+ ));
399+ cancel(&db, booking, &MealCutoff::default(), &ali)
400+ .await
401+ .unwrap();
402+ assert!(row.delete(&db).await.is_ok());
403+ }
404+
405+ /// A booking placed after a price edit is billed the new price, and one
406+ /// placed before keeps the old one — the seat's `price_minor` is history,
407+ /// never re-read from the menu.
408+ #[tokio::test]
409+ async fn a_seat_keeps_the_price_it_was_taken_at() {
410+ let (db, menu) = menu(None).await;
411+ let (ali, veli) = (UserId::generate(), UserId::generate());
412+ let open = MealCutoff::default();
413+ add_dish(&menu, 1_000, &db).await;
414+
415+ let early = book(&db, &menu, &ali, &ali, &open).await.unwrap();
416+ add_dish(&menu, 500, &db).await;
417+ let late = book(&db, &menu, &veli, &veli, &open).await.unwrap();
418+
419+ assert_eq!(
420+ early.get_price_minor().map(LedgerAmount::as_minor),
421+ Some(1_000)
422+ );
423+ assert_eq!(
424+ late.get_price_minor().map(LedgerAmount::as_minor),
425+ Some(1_500)
426+ );
427+ // The seat taken before the second dish is not re-billed for it.
428+ let held = book(&db, &menu, &ali, &ali, &open).await.unwrap();
429+ assert_eq!(
430+ held.get_price_minor().map(LedgerAmount::as_minor),
431+ Some(1_000)
432+ );
433+ }
434+
435+ /// A cancel that lost its flip may only refund the attempt it was actually
436+ /// cancelling. Driven against the predicate rather than through `cancel`:
437+ /// the row is re-read *inside* the call, so the only way it can disagree
438+ /// with what the flip found is a genuine concurrent write, which no
439+ /// single-process interleaving (and no in-memory engine) can stage.
440+ #[tokio::test]
441+ async fn a_lost_flip_refunds_only_the_attempt_it_released() {
442+ let (db, menu) = menu(None).await;
443+ let (ali, veli) = (UserId::generate(), UserId::generate());
444+ let open = MealCutoff::default();
445+ add_dish(&menu, 1_000, &db).await;
446+
447+ let seen = book(&db, &menu, &ali, &ali, &open).await.unwrap();
448+ let cancelled = cancel(&db, seen.clone(), &open, &ali).await.unwrap();
449+ // The seat this cancel released: its own attempt, still cancelled.
450+ assert!(refundable_after_lost_flip(&seen, &cancelled).unwrap());
451+
452+ // A re-book landed in the window. The row is `booked` again with a live
453+ // charge against it — refunding that frees money for a seat that is
454+ // still held, and burns the ledger id its own cancel will need. The
455+ // caller is refused rather than told it cancelled something.
456+ let rebooked = book(&db, &menu, &ali, &ali, &open).await.unwrap();
457+ assert_eq!(rebooked.get_attempt(), seen.get_attempt() + 1);
458+ assert!(matches!(
459+ refundable_after_lost_flip(&seen, &rebooked),
460+ Err(AppError::Conflict(_))
461+ ));
462+
463+ // Re-booked *and* cancelled again: that cancel appended the reversal
464+ // for its own attempt, and this call has nothing left to heal.
465+ let later = cancel(&db, rebooked, &open, &ali).await.unwrap();
466+ assert!(!refundable_after_lost_flip(&seen, &later).unwrap());
467+
468+ // And the ordinary lost race — another cancel of the same attempt got
469+ // there first — still replays the refund, which is what heals a cancel
470+ // cut short between the flip and the ledger line.
471+ let other = book(&db, &menu, &veli, &veli, &open).await.unwrap();
472+ let freed = cancel(&db, other.clone(), &open, &veli).await.unwrap();
473+ assert!(refundable_after_lost_flip(&other, &freed).unwrap());
474+ }
475+
476+ /// Through the crate's one clock ([`crate::domain::timestamp::Timestamp::today_utc`]),
477+ /// never `chrono::Utc::now` — the guard under test compares against that
478+ /// same clock, and a test reading a second one is how a timezone mix gets
479+ /// back in (`clippy.toml` denies it, tests included).
480+ fn today() -> String {
481+ Timestamp::today_utc().format("%Y-%m-%d").to_string()
482+ }
483+
484+ fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
485+ MealCutoff {
486+ minutes,
487+ slots: vec![MealSlotDef::try_new("lunch", serving_minute).unwrap()],
488+ }
489+ }
490+
491+ /// The charge hole itself: a menu whose day has gone by must take no seat
492+ /// and mint no ledger line, with the shipped defaults in force.
493+ #[tokio::test]
494+ async fn a_past_day_takes_no_seat_and_writes_no_charge() {
495+ let (db, menu) = menu_on("2020-01-06", None).await;
496+ let ali = UserId::generate();
497+ add_dish(&menu, 4550, &db).await;
498+
499+ assert!(matches!(
500+ book(&db, &menu, &ali, &ali, &MealCutoff::default()).await,
501+ Err(AppError::Conflict(_))
502+ ));
503+ assert_eq!(seats(&menu, &db).await, 0);
504+ let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
505+ .await
506+ .unwrap();
507+ assert!(
508+ lines.is_empty() && total == 0,
509+ "a refused booking bills nothing"
510+ );
511+ }
512+
513+ /// The documented decision the past-day guard must not swallow: today's
514+ /// menu, on a slot with no serving hour, books exactly as it always did —
515+ /// with the cutoff knob set *and* unset.
516+ #[tokio::test]
517+ async fn todays_menu_still_books_without_a_serving_hour() {
518+ let (db, menu) = menu_on(&today(), None).await;
519+ let ali = UserId::generate();
520+ book(&db, &menu, &ali, &ali, &cutoff(Some(60), None))
521+ .await
522+ .expect("an unset serving hour is an unenforced cutoff");
523+ assert_eq!(seats(&menu, &db).await, 1);
524+ }
525+
526+ /// Cancelling stays open on a day already gone — that is how money already
527+ /// taken is given back, and it is the same reason manager+ bypasses the
528+ /// cutoff. The guard binds `book` alone.
529+ #[tokio::test]
530+ async fn a_past_day_still_gives_the_seat_and_the_money_back() {
531+ let (db, menu) = menu_on("2020-01-06", None).await;
532+ let ali = UserId::generate();
533+ add_dish(&menu, 4550, &db).await;
534+ // The seat this student is holding was taken while the day was still
535+ // ahead — the shape the create-side check cannot reach. A test cannot
536+ // age a menu (`date` is READONLY), so the seat is placed on an
537+ // already-past menu by the very transaction `book` places it with.
538+ let fresh = Menu::read(&menu, &db).await.unwrap().unwrap();
539+ let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
540+ let row = MealBooking {
541+ id: MealBookingId::composite(&menu, &ali),
542+ menu: menu.clone(),
543+ student: ali.clone(),
544+ booked_by: ali.clone(),
545+ status: MealBookingStatus::Booked,
546+ attempt: 1,
547+ price_minor: price,
548+ cancelled_at: None,
549+ created_at: Timestamp::now(),
550+ };
551+ let charge = MealLedger::charge_for(&row, &ali);
552+ let booked = match meal_booking::claim_and_place(
553+ &db,
554+ &menu.record(),
555+ cap::UNLIMITED,
556+ fresh.get_version(),
557+ &row,
558+ price,
559+ charge.as_ref(),
560+ )
561+ .await
562+ .unwrap()
563+ {
564+ cap::Claimed::Made(booking) => booking,
565+ _ => panic!("the seat was free"),
566+ };
567+ assert_eq!(seats(&menu, &db).await, 1);
568+
569+ assert!(matches!(
570+ book(&db, &menu, &ali, &ali, &MealCutoff::default()).await,
571+ Err(AppError::Conflict(_)),
572+ ));
573+ let cancelled = cancel(&db, booked, &MealCutoff::default(), &ali)
574+ .await
575+ .expect("a cancel on a past day still frees the seat");
576+ assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
577+ assert_eq!(seats(&menu, &db).await, 0);
578+ let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db)
579+ .await
580+ .unwrap();
581+ assert_eq!(lines.len(), 2, "the charge and its reversal");
582+ }
583+}
src/service/mod.rsmodified+1 -0
@@ -8,6 +8,7 @@ pub mod course;
8 pub mod course_session;8 pub mod course_session;
9 pub mod exam_attempt;9 pub mod exam_attempt;
10 pub mod exam_question;10 pub mod exam_question;
11+pub mod meal_booking;
11 pub mod note;12 pub mod note;
12 pub mod payment_ledger;13 pub mod payment_ledger;
13 pub mod session;14 pub mod session;
src/web/meals.rsmodified+12 -9
@@ -861,11 +861,12 @@ async fn book_meal(
861 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;861 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
862 let cutoff = meal_cutoff(&st.db).await?;862 let cutoff = meal_cutoff(&st.db).await?;
863 let menu = MenuId::from_key(&id);863 let menu = MenuId::from_key(&id);
864- // Price, seat and charge land as one decision (see `MealBooking::book`),864+ // Price, seat and charge land as one decision (see
865- // keyed by (seat, attempt) — a double-click books one seat and bills it865+ // `service::meal_booking::book`), keyed by (seat, attempt) — a double-click
866- // once, and a dish landing between the price and the seat is refused by the866+ // books one seat and bills it once, and a dish landing between the price
867- // claim rather than billed.867+ // and the seat is refused by the claim rather than billed.
868- let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?;868+ let booking =
869+ service::meal_booking::book(&st.db, &menu, &student, user.get_id(), &cutoff).await?;
869 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;870 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
870 Ok((871 Ok((
871 StatusCode::CREATED,872 StatusCode::CREATED,
@@ -908,7 +909,8 @@ async fn my_bookings(
908 .map(|link| link.get_student().clone()),909 .map(|link| link.get_student().clone()),
909 );910 );
910 }911 }
911- let (rows, total) = MealBooking::list_for_students(&students, limit, offset, &st.db).await?;912+ let (rows, total) =
913+ service::meal_booking::list_for_students(&st.db, &students, limit, offset).await?;
912 let items = booking_responses(&rows, &st.db).await?;914 let items = booking_responses(&rows, &st.db).await?;
913 Ok(Json(Page::new(items, total, limit, offset)))915 Ok(Json(Page::new(items, total, limit, offset)))
914 }916 }
@@ -940,7 +942,8 @@ async fn list_menu_bookings(
940 let menu = Menu::read(&MenuId::from_key(&id), &st.db)942 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
941 .await?943 .await?
942 .ok_or(AppError::NotFound)?;944 .ok_or(AppError::NotFound)?;
943- let (rows, total) = MealBooking::list_for_menu(menu.get_id(), limit, offset, &st.db).await?;945+ let (rows, total) =
946+ service::meal_booking::list_for_menu(&st.db, menu.get_id(), limit, offset).await?;
944 let items = booking_responses(&rows, &st.db).await?;947 let items = booking_responses(&rows, &st.db).await?;
945 Ok(Json(Page::new(items, total, limit, offset)))948 Ok(Json(Page::new(items, total, limit, offset)))
946 }949 }
@@ -1034,10 +1037,10 @@ async fn cancel_booking(
1034 };1037 };
1035 // Flips the row and appends the reversal for that attempt's charge in one1038 // Flips the row and appends the reversal for that attempt's charge in one
1036 // transaction; the charge itself stays.1039 // transaction; the charge itself stays.
1037- let booking = MealBooking::read(&id, &st.db)1040+ let booking = service::meal_booking::read(&st.db, &id)
1038 .await?1041 .await?
1039 .ok_or(AppError::NotFound)?;1042 .ok_or(AppError::NotFound)?;
1040- let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;1043+ let cancelled = service::meal_booking::cancel(&st.db, booking, &cutoff, user.get_id()).await?;
1041 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;1044 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
1042 Ok(Json(1045 Ok(Json(
1043 items.into_iter().next().expect("one booking in, one out"),1046 items.into_iter().next().expect("one booking in, one out"),
tests/integration.rsmodified+8 -5
@@ -22181,7 +22181,7 @@ async fn concurrent_duplicate_menu_publishes_conflict_not_500() {
22181 /// writers before they can ever collide.22181 /// writers before they can ever collide.
22182 #[tokio::test]22182 #[tokio::test]
22183 async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {22183 async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {
22184- use hezarfen_backend::domain::meal_booking::{MealBooking, MealBookingId};22184+ use hezarfen_backend::domain::meal_booking::MealBookingId;
22185 use hezarfen_backend::domain::meal_ledger::MealLedger;22185 use hezarfen_backend::domain::meal_ledger::MealLedger;
22186 22186
22187 let (app, db) = app_and_db().await;22187 let (app, db) = app_and_db().await;
@@ -22218,10 +22218,13 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {
22218 )22218 )
22219 .await;22219 .await;
22220 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);22220 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
22221- let booking = MealBooking::read(&MealBookingId::from_key(&id_of(&res.body)), &db)22221+ let booking = hezarfen_backend::service::meal_booking::read(
22222- .await22222+ &db,
22223- .expect("read the booking")22223+ &MealBookingId::from_key(&id_of(&res.body)),
22224- .expect("the booking exists");22224+ )
22225+ .await
22226+ .expect("read the booking")
22227+ .expect("the booking exists");
22225 let student = booking.get_student().clone();22228 let student = booking.get_student().clone();
22226 assert_eq!(22229 assert_eq!(
22227 MealLedger::balance_of(&student, &db).await.unwrap(),22230 MealLedger::balance_of(&student, &db).await.unwrap(),