forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

menu.rs674 lines, 28.2 KiBHistoryRawDownload
1//! The `menu` table: publishing (the slot reference claimed inside the
2//! write's own transaction), row reads and listings, the compare-and-set
3//! every cap PATCH writes through, and the cascading delete. The kitchen
4//! workflows — the guarded dish-cap insert — live in
5//! [`crate::service::menu`].
6
7use crate::database::{Database, tx_with_retry, unique_violation};
8use crate::db::page::{PagedList, Param};
9use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, slot_ref};
10use crate::domain::timestamp::Timestamp;
11use crate::domain::user::UserId;
12use crate::error::AppError;
13
14/// Publish a menu. Refused (409) when the day+slot already carries one.
15///
16/// The day and slot *are* the row's primary key ([`MenuId::for_slot`]), so
17/// the refusal is decided by the store rather than by a check a concurrent
18/// publish can outrun: two publishes of the same meal write one row, and
19/// the loser's unique violation on `menu_pkey` becomes the same 409. The
20/// in-transaction pre-check stays for the ordinary case.
21///
22/// The menu takes a reference on its slot, which is what stops the slot
23/// being dropped from the settings while this menu (whose slot is only
24/// snapshotted text) still points at it. Claimed *inside* the write's own
25/// transaction, with the duplicate gate ahead of the retired check so
26/// "you already published this" still outranks "the slot is retired" (the
27/// [`crate::db::cap`] reference-claim recipe): the counted row and the
28/// count commit together or not at all, so no crash window is small enough
29/// to leave a slot counted by a menu that does not exist — a slot nobody
30/// could ever retire.
31pub async fn create(
32 db: &Database,
33 date: MenuDate,
34 slot: MenuSlot,
35 capacity: Option<i64>,
36 created_by: &UserId,
37) -> Result<Menu, AppError> {
38 let id_key = MenuId::for_slot(&date, &slot).key().to_string();
39 let counter = slot_ref(slot.as_str());
40 let date_s = date.as_str().to_string();
41 let slot_s = slot.as_str().to_string();
42 let created_by = *created_by;
43 let created_at = Timestamp::now();
44 tx_with_retry(db, false, async move |tx| {
45 // Duplicate gate ahead of the retired check: "already published"
46 // outranks "slot retired", on the very path a rival publish races.
47 let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,)
48 .fetch_optional(&mut *tx)
49 .await?;
50 if exists.is_some() {
51 return Err(AppError::Conflict(
52 "a menu is already published for that date and slot",
53 ));
54 }
55 let inserted = match sqlx::query_as!(
56 Menu,
57 "WITH ref AS (
58 INSERT INTO slot_ref (name, count) VALUES ($2, 1)
59 ON CONFLICT (name) DO UPDATE SET count = slot_ref.count + 1
60 WHERE slot_ref.retired = false
61 RETURNING 1 AS ref
62 )
63 INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at)
64 SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref)
65 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
66 id_key,
67 counter,
68 date_s,
69 slot_s,
70 capacity,
71 Some(0i64),
72 created_by.uuid(),
73 created_at.as_millis(),
74 )
75 .fetch_optional(&mut *tx)
76 .await
77 {
78 Ok(row) => row,
79 Err(err) => {
80 // A rival published the same meal after the pre-check: its
81 // row owns the key — or, for a legacy id a derived key can
82 // never collide with, its (date, slot) pair does — and the
83 // rival's publish is the answer either way.
84 if matches!(unique_violation(&err),
85 Some("menu_pkey") | Some("menu_date_slot"))
86 {
87 return Err(AppError::Conflict(
88 "a menu is already published for that date and slot",
89 ));
90 }
91 return Err(err.into());
92 }
93 };
94 match inserted {
95 Some(menu) => Ok(menu),
96 // The slot's ref row is retired — nothing was written.
97 None => Err(AppError::ConflictOwned(format!(
98 "the '{}' meal slot has been removed from the school's settings",
99 slot_s,
100 ))),
101 }
102 })
103 .await
104}
105
106pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> {
107 let row = sqlx::query_as!(
108 Menu,
109 "SELECT id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"
110 FROM menu WHERE id = $1",
111 id.key(),
112 )
113 .fetch_optional(db)
114 .await?;
115 Ok(row)
116}
117
118/// The menu for one day and slot, if any — the uniqueness check.
119pub async fn find(
120 db: &Database,
121 date: &MenuDate,
122 slot: &MenuSlot,
123) -> Result<Option<Menu>, AppError> {
124 let row = sqlx::query_as!(
125 Menu,
126 "SELECT id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"
127 FROM menu WHERE date = $1 AND slot = $2 LIMIT 1",
128 date.as_str(),
129 slot.as_str(),
130 )
131 .fetch_optional(db)
132 .await?;
133 Ok(row)
134}
135
136/// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
137/// either may be omitted (`NULL` bound). The comparison is lexical, which
138/// is chronological for this format. `slot`, when given, keeps only menus
139/// published under that exact snapshotted slot text — deliberately not
140/// checked against the school's current `meal_slots`, so a retired slot
141/// still finds its menus and an unknown name matches nothing.
142pub async fn list(
143 db: &Database,
144 from: Option<&MenuDate>,
145 to: Option<&MenuDate>,
146 slot: Option<&str>,
147 limit: Option<i64>,
148 offset: i64,
149) -> Result<(Vec<Menu>, i64), AppError> {
150 // One WHERE for the page and the count alike: a slot filter moves
151 // `total` with the items, so page numbers count the rows actually
152 // returned.
153 PagedList::new(
154 "menu WHERE ($1::text IS NULL OR date >= $1::text) \
155 AND ($2::text IS NULL OR date <= $2::text) \
156 AND ($3::text IS NULL OR slot = $3::text)",
157 "ORDER BY date DESC, slot ASC, id DESC",
158 )
159 .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
160 .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
161 .bind(Param::OptText(slot.map(|slot| slot.to_string())))
162 .run(limit, offset, db)
163 .await
164}
165
166/// Only `capacity` is writable: `date` and `slot` are fixed at publish,
167/// because moving a published menu to another day is a different menu.
168/// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
169///
170/// The revision moves **in the same statement** as the cap, indivisibly: a
171/// booking claims its seat against the revision it read the cap at, so a
172/// shrink that bumped in a query of its own left a window where the row
173/// carried the *new* revision and the *old* cap — and a booking arriving
174/// there passes a CAS meant to refuse it, over-admitting by exactly the
175/// seats in flight.
176pub async fn update(
177 db: &Database,
178 menu: Menu,
179 capacity: Option<Option<i64>>,
180) -> Result<Menu, AppError> {
181 let Some(capacity) = capacity else {
182 // A PATCH carrying nothing writes nothing and bumps nothing: no
183 // booking's price or cap has moved, so none owes a re-read.
184 return read(db, &menu.id).await?.ok_or(AppError::NotFound);
185 };
186 let row = sqlx::query_as!(
187 Menu,
188 "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1
189 WHERE id = $1
190 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
191 menu.id.key(),
192 capacity,
193 )
194 .fetch_optional(db)
195 .await?;
196 row.ok_or(AppError::NotFound)
197}
198
199/// Delete the menu and the dishes and marks on it — a dish or a mark has
200/// no meaning without its menu, and the menu key cannot be re-homed.
201///
202/// Refused (409) while a seat is still held, and the *row itself* decides
203/// that: the guard that unlocks the sweep reads the seat counter in its own
204/// `WHERE` under `FOR UPDATE`, so a booking landing at that instant either
205/// takes its seat before the delete (which then finds a non-zero counter
206/// and refuses) or after it (and finds no menu). A read-then-delete pair
207/// had a window where both happened — a paid seat on a menu that no longer
208/// exists. The lock is also what makes the sweep's order safe: the dishes
209/// and marks go first (both FKs are `ON DELETE NO ACTION`, so the parent
210/// row cannot leave while they stand) and the menu row goes last, with no
211/// window in between in which the children of a surviving menu could be
212/// destroyed.
213///
214/// The slot gets its reference back in that same transaction — a slot no
215/// menu is published for any more may leave the settings again. Released
216/// afterwards in a statement of its own, a crash between the two left the
217/// slot counted by a menu that no longer exists: a slot nobody can retire.
218///
219/// The marks go in that same sweep, for a sharper reason than tidiness:
220/// [`MenuId::for_slot`] is deterministic, so republishing the same day and
221/// slot mints the *same* row key. A mark left behind would come back as a
222/// mark on the new menu — the kitchen reading "served" for a student who
223/// never came — and until then the student's own report cites a menu that
224/// is gone. Attendance carries no money and no counter, so it is safe to
225/// drop; cancelled *bookings* deliberately stay (no foreign key ties them
226/// to the menu), because their `attempt` counter is what keeps the
227/// ledger's `(booking, attempt)` keys unique across the republish. Cut
228/// those and a re-book on a republished menu would reuse a charge id the
229/// ledger already holds, and the append (idempotent by design) would bill
230/// the seat nothing.
231///
232/// The dishes ride in the same sweep: run after the commit, a crash
233/// between the two would orphan them on the row key a republish mints
234/// again — a new menu serving (and pricing) the old one's food.
235pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
236 let key = menu.id.key().to_string();
237 let counter = slot_ref(menu.slot.as_str());
238 let deleted = tx_with_retry(db, true, async move |tx| {
239 // The row itself decides the guard, under its own lock: a booking
240 // racing this delete either committed first (the guard reads its
241 // seat and refuses before any child is touched) or queues on the
242 // lock and lands after the commit — and finds no menu.
243 let guard = sqlx::query!(
244 "SELECT 1 AS deletable FROM menu WHERE id = $1 AND seats_booked = 0 FOR UPDATE",
245 key,
246 )
247 .fetch_optional(&mut *tx)
248 .await?;
249 if guard.is_none() {
250 return Ok(None);
251 }
252 // The children go first: `menu_dish_tag.dish`, `menu_dish.menu` and
253 // `meal_attendance.menu` are all `ON DELETE NO ACTION`, so the
254 // parent rows cannot leave while they stand.
255 sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
256 .execute(&mut *tx)
257 .await?;
258 sqlx::query!(
259 "DELETE FROM menu_dish_tag WHERE dish IN (SELECT id FROM menu_dish WHERE menu = $1)",
260 key,
261 )
262 .execute(&mut *tx)
263 .await?;
264 sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
265 .execute(&mut *tx)
266 .await?;
267 let row = sqlx::query_as!(
268 Menu,
269 "DELETE FROM menu WHERE id = $1
270 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
271 key,
272 )
273 .fetch_optional(&mut *tx)
274 .await?;
275 // Unreachable while the guard holds the row's lock, but the match
276 // keeps the shape honest: `row` exists iff the guard passed.
277 let Some(row) = row else {
278 return Ok(None);
279 };
280 sqlx::query!(
281 "UPDATE slot_ref SET count = GREATEST(count - 1, 0) WHERE name = $1",
282 counter,
283 )
284 .execute(&mut *tx)
285 .await?;
286 Ok(Some(row))
287 })
288 .await?;
289 match deleted {
290 Some(menu) => Ok(menu),
291 // Nothing back: either seats are held, or the menu is already gone.
292 None => match read(db, &menu.id).await? {
293 Some(_) => Err(AppError::Conflict("the menu still has live bookings")),
294 None => Err(AppError::NotFound),
295 },
296 }
297}
298#[cfg(test)]
299mod tests {
300 use super::*;
301 use crate::database::init_test_db;
302 use crate::db::meal_attendance;
303 use crate::db::menu_dish;
304 use crate::domain::meal_attendance::MealAttendanceStatus;
305 use crate::domain::menu_dish::{DishName, DishPrice, DishTags};
306 use crate::domain::settings::MealSlotDef;
307
308 /// The one fixture person, by a fixed valid id every publish can name.
309 const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc";
310
311 async fn school() -> (Database, crate::database::TestDatabases) {
312 let (db, leases) = init_test_db().await;
313 sqlx::query(
314 "INSERT INTO app_user (id, username, created_at, role) \
315 VALUES ($1, 'teacher', 0, 'teacher')",
316 )
317 .bind(UserId::from_key(TEACHER).uuid())
318 .execute(&db)
319 .await
320 .unwrap();
321 (db, leases)
322 }
323
324 fn lunch() -> MenuSlot {
325 MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap()
326 }
327
328 /// The reference count, re-read out of the store — never off a return
329 /// value, which the in-memory engine forges wins on.
330 async fn refs(db: &Database) -> i64 {
331 use sqlx::Row as _;
332
333 sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'")
334 .fetch_optional(db)
335 .await
336 .unwrap()
337 .map(|row| row.try_get::<i64, _>(0).unwrap())
338 .unwrap_or(0)
339 }
340
341 /// The settings guard's retire switch, driven straight: `true` only when
342 /// this call flipped the bit.
343 async fn retire_lunch(db: &Database) -> bool {
344 sqlx::query(
345 "INSERT INTO slot_ref (name, count, retired) VALUES ('lunch', 0, TRUE)
346 ON CONFLICT (name) DO UPDATE SET retired = TRUE
347 WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE
348 RETURNING 1",
349 )
350 .fetch_optional(db)
351 .await
352 .unwrap()
353 .is_some()
354 }
355
356 async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> {
357 create(
358 db,
359 MenuDate::try_new(date).unwrap(),
360 lunch(),
361 None,
362 &UserId::from_key(TEACHER),
363 )
364 .await
365 }
366
367 /// Plant a menu row the pre-check will (or will not) find, without going
368 /// through the claim — a row published before the counter existed.
369 async fn plant(id: &MenuId, date: &str, db: &Database) {
370 sqlx::query(
371 "INSERT INTO menu (id, date, slot, created_by, created_at) \
372 VALUES ($1, $2, 'lunch', $3, 1)",
373 )
374 .bind(id.key())
375 .bind(date)
376 .bind(UserId::from_key(TEACHER).uuid())
377 .execute(db)
378 .await
379 .unwrap();
380 }
381
382 #[tokio::test]
383 async fn publishing_lands_the_menu_and_its_reference_together() {
384 let (db, _leases) = school().await;
385 let menu = publish("2026-08-02", &db).await.unwrap();
386 assert!(read(&db, menu.get_id()).await.unwrap().is_some());
387 assert_eq!(refs(&db).await, 1);
388
389 // The day+slot pre-check answers the second publish — and a refusal
390 // may not count the slot, or the menu would outlive its own reference.
391 let again = publish("2026-08-02", &db)
392 .await
393 .expect_err("that day and slot are taken");
394 assert!(matches!(again, AppError::Conflict(_)), "got {again:?}");
395 assert_eq!(refs(&db).await, 1);
396 }
397
398 #[tokio::test]
399 async fn a_retired_slot_refuses_and_writes_nothing() {
400 let (db, _leases) = school().await;
401 assert!(retire_lunch(&db).await);
402
403 let refused = publish("2026-08-02", &db)
404 .await
405 .expect_err("the slot left the settings");
406 assert!(
407 matches!(refused, AppError::ConflictOwned(_)),
408 "got {refused:?}"
409 );
410 assert_eq!(refs(&db).await, 0);
411 assert!(
412 find(&db, &MenuDate::try_new("2026-08-02").unwrap(), &lunch(),)
413 .await
414 .unwrap()
415 .is_none()
416 );
417 }
418
419 /// The race the fold exists for: a rival places the very row this publish
420 /// is placing, between the pre-check and the write. Only the claim's own
421 /// gate can answer it, and its answer must cost no reference.
422 #[tokio::test]
423 async fn a_rival_on_the_id_answers_taken_and_counts_nothing() {
424 let (db, _leases) = school().await;
425 let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch());
426 // Planted under another day, so `find` misses it exactly as it would
427 // in the instant before the rival's own row was visible.
428 plant(&id, "1999-01-01", &db).await;
429
430 let taken = publish("2026-08-02", &db)
431 .await
432 .expect_err("the id is taken");
433 assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}");
434 assert_eq!(refs(&db).await, 0);
435 }
436
437 /// Menus published before ids were derived keep a ULID key a new publish
438 /// cannot collide with, so the pre-check is the only thing that can refuse.
439 #[tokio::test]
440 async fn a_legacy_ulid_menu_still_answers_taken() {
441 let (db, _leases) = school().await;
442 plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await;
443
444 let taken = publish("2026-08-02", &db)
445 .await
446 .expect_err("that day and slot are taken");
447 assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}");
448 assert_eq!(refs(&db).await, 0);
449 }
450
451 /// The cap and the revision are one write. Nothing single-process can
452 /// observe the torn state the two-query version left (a bumped revision
453 /// over a cap that had not moved yet), so what is pinned here is the pair:
454 /// the revision steps exactly once per cap move, and never for a PATCH that
455 /// carried no cap at all — a booking re-reads only when something it priced
456 /// itself against actually changed.
457 #[tokio::test]
458 async fn the_cap_and_the_revision_move_together_or_not_at_all() {
459 let (db, _leases) = school().await;
460 let menu = publish("2026-08-05", &db).await.unwrap();
461 let id = menu.get_id().clone();
462 assert_eq!(menu.get_version(), 0);
463
464 let capped = update(&db, menu, Some(Some(5))).await.unwrap();
465 assert_eq!(capped.get_capacity(), Some(5));
466 assert_eq!(capped.get_version(), 1);
467 // Re-read out of the store, never off the return value.
468 let stored = read(&db, &id).await.unwrap().unwrap();
469 assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1));
470
471 // An empty PATCH moves neither, and reads the row back unchanged.
472 let same = update(&db, stored, None).await.unwrap();
473 assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1));
474
475 // Clearing the cap is a move like any other.
476 let uncapped = update(&db, same, Some(None)).await.unwrap();
477 assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2));
478 }
479
480 #[tokio::test]
481 async fn deleting_hands_the_reference_back_in_the_same_step() {
482 let (db, _leases) = school().await;
483 let monday = publish("2026-08-03", &db).await.unwrap();
484 publish("2026-08-04", &db).await.unwrap();
485 assert_eq!(refs(&db).await, 2);
486
487 let id = monday.get_id().clone();
488 let ghost = monday.clone();
489 delete(&db, monday).await.unwrap();
490 assert!(read(&db, &id).await.unwrap().is_none());
491 assert_eq!(refs(&db).await, 1, "the row and its reference go together");
492
493 // Deleting what is already gone hands nothing back: a second release
494 // would leave a slot one menu still uses free to be retired.
495 let gone = delete(&db, ghost).await.expect_err("already deleted");
496 assert!(matches!(gone, AppError::NotFound), "got {gone:?}");
497 assert_eq!(refs(&db).await, 1);
498 assert!(
499 !retire_lunch(&db).await,
500 "a slot a menu is still published for may not be retired"
501 );
502
503 // …and once the last menu goes, it may.
504 let last = find(&db, &MenuDate::try_new("2026-08-04").unwrap(), &lunch())
505 .await
506 .unwrap()
507 .unwrap();
508 delete(&db, last).await.unwrap();
509 assert_eq!(refs(&db).await, 0);
510 }
511
512 /// Nothing hanging off a menu may survive the delete that swept it — not a
513 /// dish, and not an attendance mark. Menu ids are deterministic on
514 /// (date, slot), so a survivor is not litter: republishing that meal mints
515 /// the *same* id and the orphan comes back attached to the new menu — the
516 /// kitchen reading "served" for a student who never came, or pricing the
517 /// old menu's food.
518 ///
519 /// The window is between [`delete`]'s `DELETE` and its cascade: a
520 /// child write committing in there is a phantom insert into a range the
521 /// delete already swept on an older snapshot, so the sweep removes nothing
522 /// and *both* commit. It is closed by making every child write **write** the
523 /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two
524 /// transactions then touch one key and the store refuses to commit both.
525 ///
526 /// The window the schema event used to force open is the menu row's own
527 /// lock now: every child write also writes the menu row, so a child racing
528 /// the delete serializes on that row instead of committing into a range
529 /// the sweep has already passed. Both orders are forced, for each child
530 /// kind, by awaiting one side to completion before the other starts. A
531 /// few rounds still start together; those may all lose the delete, and
532 /// that is not a failure.
533 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
534 async fn a_child_written_inside_a_delete_never_outlives_the_menu() {
535 use crate::domain::menu_dish::DishDescription;
536
537 let (db, _leases) = school().await;
538
539 async fn write_child(db: &Database, id: &MenuId, dish: bool) -> Result<(), AppError> {
540 if dish {
541 menu_dish::create(
542 db,
543 id,
544 DishName::try_new("Pilav").unwrap(),
545 None::<DishDescription>,
546 DishPrice::try_new(1).unwrap(),
547 DishTags::try_new(&[], &[]).unwrap(),
548 1_000,
549 )
550 .await
551 .map(|_| ())
552 } else {
553 meal_attendance::mark(
554 db,
555 id,
556 &UserId::from_key(TEACHER),
557 MealAttendanceStatus::try_new("served").unwrap(),
558 &UserId::from_key(TEACHER),
559 )
560 .await
561 .map(|_| ())
562 }
563 }
564
565 async fn children(db: &Database, id: &MenuId) -> (usize, i64) {
566 (
567 menu_dish::list_for_menu(db, id).await.unwrap().len(),
568 meal_attendance::list_for_menu(db, id, None, 0)
569 .await
570 .unwrap()
571 .1,
572 )
573 }
574
575 let mut day = 1u32;
576 // One child kind per round, never both: whichever wrote first forces
577 // the delete to re-send, and its second pass sweeps the other's row.
578 for dish in [true, false] {
579 let kind = if dish { "dish" } else { "mark" };
580
581 // Delete-first.
582 {
583 let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap();
584 day += 1;
585 let id = menu.get_id().clone();
586 let dropped = delete(&db, menu).await;
587 assert!(
588 !matches!(dropped, Err(AppError::Db(_))),
589 "{kind} delete-first: a delete must be answered, not 500: {dropped:?}"
590 );
591 assert!(
592 read(&db, &id).await.unwrap().is_none(),
593 "{kind} delete-first: the menu is still there after delete: {dropped:?}"
594 );
595 let child = write_child(&db, &id, dish).await;
596 assert!(
597 !matches!(child, Err(AppError::Db(_))),
598 "{kind} delete-first: a child write must be answered, not 500: {child:?}"
599 );
600 let (dishes, marks) = children(&db, &id).await;
601 assert_eq!(dishes, 0, "a dish outlived its menu");
602 assert_eq!(marks, 0, "a mark outlived its menu");
603 }
604
605 // Write-first.
606 {
607 let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap();
608 day += 1;
609 let id = menu.get_id().clone();
610 let child = write_child(&db, &id, dish).await;
611 assert!(
612 child.is_ok(),
613 "{kind} write-first: the child must land before the delete: {child:?}"
614 );
615 let dropped = delete(&db, menu).await;
616 assert!(
617 !matches!(dropped, Err(AppError::Db(_))),
618 "{kind} write-first: a delete must be answered, not 500: {dropped:?}"
619 );
620 assert!(
621 read(&db, &id).await.unwrap().is_none(),
622 "{kind} write-first: the menu is still there"
623 );
624 let (dishes, marks) = children(&db, &id).await;
625 assert_eq!(dishes, 0, "a dish outlived its menu");
626 assert_eq!(marks, 0, "a mark outlived its menu");
627 }
628 }
629
630 // Overlapped rounds. Delete may lose every one of them.
631 let mut swept = 0;
632 for round in 0..4 {
633 let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap();
634 day += 1;
635 let id = menu.get_id().clone();
636 let dish = round % 2 == 0;
637
638 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
639 let drop_it = {
640 let (db, gate, menu) = (db.clone(), gate.clone(), menu);
641 tokio::spawn(async move {
642 gate.wait().await;
643 delete(&db, menu).await
644 })
645 };
646 let child = {
647 let (id, db, gate) = (id.clone(), db.clone(), gate);
648 tokio::spawn(async move {
649 gate.wait().await;
650 write_child(&db, &id, dish).await
651 })
652 };
653 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
654 assert!(
655 !matches!(child, Err(AppError::Db(_))),
656 "round {round}: a raced child write must be answered, not 500: {child:?}"
657 );
658 assert!(
659 !matches!(drop_it, Err(AppError::Db(_))),
660 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
661 );
662
663 if read(&db, &id).await.unwrap().is_none() {
664 swept += 1;
665 let (dishes, marks) = children(&db, &id).await;
666 assert_eq!(dishes, 0, "round {round}: a dish outlived its menu");
667 assert_eq!(marks, 0, "round {round}: a mark outlived its menu");
668 } else if drop_it.is_ok() {
669 panic!("round {round}: the delete reported success but the menu is still there");
670 }
671 }
672 eprintln!("Menu::delete raced by its children: {swept}/4 concurrent rounds deleted the menu");
673 }
674}