diff --git a/README.md b/README.md index bc9943f..0525c8b 100644 --- a/README.md +++ b/README.md @@ -700,20 +700,20 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ — **not** an assigned teacher; `409` while anyone is still enrolled) | | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) | | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) | -| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) | -| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | +| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back | +| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label | | GET | `/classes` | teacher | List classes, newest first · paged | | GET | `/classes/{id}` | teacher | Get one class | | PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) | | DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses | -| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, or if already a member) | -| GET | `/classes/{id}/members` | teacher | List the class roster · paged | +| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) | +| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged | | DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) | -| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, or if already attached) | -| GET | `/classes/{id}/courses` | teacher | List the class's attached courses · paged | -| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis | +| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) | +| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged | +| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) · paged | | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` — add a curriculum subject (course manager) | @@ -829,34 +829,34 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` | -| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on "Invalid lists, bands, file limit, or chat limits"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see "Per-school policy") | +| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on "Invalid lists, bands, file limit, or chat limits" — a meal slot name carrying `/ \ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see "Per-school policy") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) | | DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course or class still links to it | -| POST | `/meals/menus` | manager | `{date, slot, capacity?}` — publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published | +| POST | `/meals/menus` | manager | `{date, slot, capacity?}` — publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots` and may not contain `/ \ ? # %` (it becomes part of the menu's URL id); `409` when that day+slot is already published | | GET | `/meals/menus` | student | List menus with their dishes, newest day first · `?from=&to=` inclusive `YYYY-MM-DD` range · paged | | GET | `/meals/menus/{id}` | student | One menu with its dishes | | PATCH | `/meals/menus/{id}` | manager | `{capacity}` — the only mutable field (`null` = uncapped); `date` and `slot` are immutable | -| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat | +| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes and its attendance marks go with it, in the same transaction; `409` while anyone still holds a seat | | POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` — add a dish (≤ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` | -| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it) | -| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu | +| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it); `404` once its menu is gone | +| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone | | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) | | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link | | PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` — record what a student may not eat (`tags` replaces the list, `"note": null` clears it); **manager+**, a student never edits their own | | POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` — take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned | | GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first · paged | | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged | -| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff | -| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` — mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** | +| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat | +| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` — mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; `404` if the menu is unpublished mid-request; **moves no money** | | GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu · paged | | GET | `/meals/attendance/{user}` | student | One student's meal-attendance history · `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day · paged · own id always, otherwise teacher+ or a parent link | | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) | -| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link | -| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate | -| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line | +| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt | +| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) | +| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) | | POST | `/payments/plans` | manager | `{name, installments}` — write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody | | GET | `/payments/plans` | manager | List fee plans, newest first · paged | | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule | @@ -887,7 +887,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included · `?epoch=` for one epoch · paged | | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) · paged | | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` — re-title (any participant); the roster and the lock are the creator's alone (`403`) | -| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap — nothing is deleted; `409` on a closed board | +| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap — nothing is deleted; `409` on a closed board, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) | | POST | `/boards/{id}/close` | student | **Creator only**: retire the board — permanently read-only, still fully readable; idempotent, and there is no reopen | | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats | | GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see "Collaborative whiteboard") | @@ -1263,7 +1263,7 @@ rewrites history: an exam keeps its retired kind, a roll-call row keeps its retired status — only **new writes** are held to the current lists (which is why grading an exam whose kind has left the list is refused). -The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). +The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Academic structure is data too. **Terms** (`/terms`) model whatever calendar the school runs — semester, trimester, quarter systems are just rows with a @@ -1299,6 +1299,22 @@ The school publishes **one menu per calendar day and meal slot** (`POST booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any menu was published for cannot be removed from the list (`409`), same contract exam kinds have with graded exams. +- **A slot name may not contain `/`, `\`, `?`, `#` or `%`** — a `400` at + `PATCH /settings` when the slot is defined, and again here when a menu is + published under one. The name goes verbatim into the menu's record id, and + that id is a URL path segment: a slot called `a/b` would publish a menu at + `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the + menu could not be read, edited or deleted. Ordinary names are untouched; + spaces and Turkish letters percent-encode into one segment as they always + have. +- **A name the school's stored list already carries is exempt from that rule.** + It is younger than the lists it validates, and `PATCH /settings` re-validates + the *whole* submitted list — so a school that stored `a/b` before the rule + existed could never edit `meal_slots` again: re-sending the name is a `400` + and dropping it is a `409` the moment a menu was published under it. The + grandfathered name is exactly as unusable as it already was — no menu may be + published under it — and dropping it is still the only way to be rid of it. + The rule stays in full force for every *new* name. The day+slot pair is unique: a second publish for the same meal answers `409` — edit the first one instead. Only `capacity` is patchable (`null` = uncapped) @@ -1309,7 +1325,11 @@ menu. `PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional description (blank or `null` clears it), dietary `tags` drawn from the school's `dietary_tags` list — an unknown tag is a `400`, never a stored -string — and a `price_minor`. +string — and a `price_minor`. Every dish write moves its **menu's** revision in +the same transaction (that is what keeps a booking from freezing a price the +menu has already left, below), which also makes the menu's existence part of +the write: editing or deleting a dish whose menu has since been unpublished is +a `404`, not a write onto a menu that is gone. ### Dietary profiles and conflicts @@ -1343,8 +1363,18 @@ many menus or dishes the page holds. is ever introduced by transport or by a client's JSON number parser. Reads are open to every authenticated user — a student has to see what is -being served — and every write is manager+. Deleting a menu takes its dishes -with it: a dish has no meaning apart from the menu it was published on. +being served — and every write is manager+. The exception is the money: +`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or +the student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes +**and its attendance marks** with it, in the same transaction as the row: a +dish has no meaning apart from the menu it was published on, and a menu's +record id is deterministic on day+slot, so anything left behind would come back +attached to the *next* menu published for that meal — the kitchen reading +"served" for a student who never came, priced off food nobody re-entered. +Cancelled **bookings** deliberately stay: their `attempt` counter is what keeps +the ledger's `(booking, attempt)` ids unique, and a re-book on a republished +menu would otherwise reuse an id the ledger already holds and bill the seat +nothing. **Bookings** are seats on a published menu (`POST /meals/menus/{id}/bookings`). One row per (menu, student), keyed by a @@ -1365,15 +1395,33 @@ teacher or manager ordering a child's lunch is a `403`. timed out) is recovered by sending it again. Refusing it as a `409` — as it once did — made that state permanent: no route could append the missing reversal, and the student stayed billed for a seat they no longer held. -- **The capacity check is serialized in-process.** Counting rows and then - writing one is write-skew: SurrealDB does not conflict-check a cross-record - count against a concurrent insert, so 24 students racing for 3 seats would - otherwise all pass the count. The whole check-then-write runs under the same - lock a menu publish takes, and the cap is re-read inside it. -- **One cutoff closes both ends.** Within the school's - `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new - booking nor a cancellation lands (`409`) — the kitchen's headcount has to - settle at some point. `null` (the default) means no cutoff at all. The +- **A manager+ may cancel anybody's seat.** Booking is student-and-parent + only, and cancelling used to be the same door — which left a seat nobody on + the API could give back the moment its student was promoted to staff or its + parent was unlinked: the menu refused its own deletion forever and the charge + could never be reversed, since cancelling is the only route that reverses + one. A role change deliberately sweeps no bookings on its own; moving money + is a decision, not a side effect. +- **The capacity check is a single conditional write, decided by the + database.** Counting rows and then writing one would be write-skew — + SurrealDB does not conflict-check a cross-record count against a concurrent + insert, so 24 students racing for 3 seats would all pass the count — so the + seat is instead claimed on a counter kept on the **menu row itself**, taken + and spent by one `UPDATE … WHERE` that also places the booking row in the + same transaction. No lock is involved and none would help: a duplicate + `POST` rolls its own seat back rather than costing a stranger their place. +- **One cutoff closes both ends — for the people it is aimed at.** Within the + school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a + new booking nor a cancellation lands (`409`) — the kitchen's headcount has to + settle at some point. `null` (the default) means no cutoff at all. It binds + **students and parents only**: a manager+ cancelling somebody's seat is not + held to it, because the deadline exists to stop students gaming the headcount + and that is no reason to leave staff holding a seat they cannot free. Past + the cutoff an uncancellable seat also made its menu undeletable forever (a + menu with a live booking refuses its own deletion) and its charge + unreversable, since cancelling is the only route that reverses one. A meal + already closed is therefore still freeable, and its menu still deletable, by + manager+ — the same state a school that set no cutoff at all runs under. The cutoff is measured back from the menu's `date` **plus the slot's `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served at `720` closes at 10:00 UTC that morning, not at 22:00 the night before. @@ -1412,6 +1460,13 @@ list meaning two things would let a school change one by editing the other. One row per (menu, student) keyed by a composite id, so a correction re-marks the same row instead of stacking a second one. +The menu has to still be there: a mark whose menu is unpublished mid-request is +a `404` and writes nothing. The existence check *is* the write's own target +rather than a read the write then trusts, because a menu's id is deterministic +on day+slot — an unconditional mark landing just after the delete committed +would be swept by nothing and would reappear as a mark on the next menu +published for that meal. + **Attendance has zero billing effect.** Booking is the sole charge trigger, so a student who booked and did not eat still pays — the kitchen bought the food. There is no no-show penalty, no refund-on-missed, and no auto-reversal: @@ -1459,29 +1514,54 @@ money on account. Amounts are stored positive; the sign lives in the `kind`. but the booking row records that it *was* free, so "free when taken" is never confused with "not billed yet": pricing the menu afterwards leaves every seat already taken on it free. -- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its - money move together under one in-process lock, and the ledger id is derived +- **Charge and reversal are keyed by `(booking, attempt)`.** The seat, its row + and its money move together in one transaction on *both* sides — the claim + writes the charge, the flip writes the reversal — and the ledger id is derived from the seat plus how many times it has been taken — so eight simultaneous `POST`s of one seat write one charge, a retried cancel refunds once, and a write that failed halfway heals when the request is repeated. Booking the same seat twice bills once because the *identity* is the same, never because a scan happened to see the first charge in time. - **Cancelling appends a `reversal`** for the charge's exact amount, with - `source` pointing at the charge it undoes. The charge row itself stays. A - cancel past the cutoff is already a `409`, so a reversal only ever follows a - legal cancel — and repeating a cancel replays the reversal, which is what - makes the refund recoverable rather than a one-shot the network can lose. - Re-booking afterwards is a **fresh** charge at the then-current price. -- **The price snapshot is taken under the booking lock**, and dish - create/edit/delete take that same lock. Taken outside it, a dish added - between the sum and the seat would be frozen onto the row as "the menu was - free then" — and nothing heals it, since a seat already held is returned - as-is, never re-priced. + `source` pointing at the charge it undoes, and it is written **by the same + transaction that flips the seat** — not appended after it. The two as + separate writes left a crash in between with a seat given back and the + student still billed, and no later cancel would ever repay it, because the + money is keyed to the attempt the flip had already consumed. Folded in, the + seat cannot come back without the money. Booking is folded the same way — the + charge rides the claim's own transaction, because a charge appended afterwards + let a cancel land in the gap, reverse nothing (there was no charge yet), and + the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when + the charge it undoes is really there, checked inside that same transaction — + a refund with no charge behind it invents money. The charge row itself stays. + Repeating a cancel replays the reversal, which is what heals a seat flipped + before that was true and makes the refund recoverable rather than a one-shot + the network can lose; the cutoff is deliberately not re-checked on that path, + since the seat is already given back. Re-booking afterwards is a **fresh** + charge at the then-current price. +- **The price snapshot is pinned by the menu's revision, not by a lock.** The + dishes are summed a round trip before the seat is claimed, so a dish landing + in between would otherwise be frozen onto the row as "the menu was free + then" — and nothing heals that, since a seat already held is returned as-is, + never re-priced. Instead every dish write bumps a revision counter on the + menu, and the claim that takes the seat *also* asserts the menu is still at + the revision the price was read at: the booking is refused, re-reads, and + prices and seats itself again together. A lock around the read could not have + promised this — the price is read a round trip before the claim either way — + so what is frozen is always a price the menu genuinely carried at the instant + the seat was taken. A menu edited over and over under one booking gives up + after a few rounds with a `409`. - **A no-show still pays.** Meal attendance has zero billing effect — nothing in the ledger reads or writes it. The seat was reserved and the food was cooked; there is no no-show penalty and no no-show refund. - **`POST /meals/credits` is admin-only**, not manager: writing down cash - received is the highest-trust action in the app. It appends a `credit` for a + received is the highest-trust action in the app. The target must be a + **student, or anyone who already carries meal-ledger lines**: only a student + runs up a meal balance, so crediting anyone else is a typo and a typo here is + money in the wrong ledger — but a debt outlives its debtor's role change, and + the student-only rule alone made a promoted student's debt permanently + unsettleable, since no other route appends a credit. A mistyped staff id + carries no lines, so it is still a `400`. It appends a `credit` for a student with a positive `amount_minor` (≤ 10 000 000), an optional `method` ("cash", "havale", …) and `note`, and records the admin as `recorded_by`. There is no payment gateway and no card data, ever. An over-credit is @@ -1490,7 +1570,10 @@ money on account. Amounts are stored positive; the sign lives in the `kind`. `GET /meals/balance/me` is the caller's own balance. `GET /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line first) read a student's: your own id always passes, anyone else's needs -teacher+ or a `parent_link` to that student. A charge's `source` is the +**manager+** or a `parent_link` to that student — **a teacher gets a `403`**, +the one pair in this block narrower than the rest of it. Canteen debt is +family debt: the money follows the `/payments` rule, not the classroom one, +while the dietary profile, booking and attendance reads stay teacher+. A charge's `source` is the booking id it came from, a reversal's is the charge line it reverses, and a credit has none. @@ -1505,7 +1588,8 @@ them would make either statement unreadable. Every write here is **manager+**. Reads are narrower than the other per-student reports: the student themselves, a parent holding a live link to them, or manager+ — **a teacher gets a `403` on every `/payments` route**, -because what a family owes the school is not classroom information. +because what a family owes the school is not classroom information. The +canteen's balance and ledger follow the same rule, for the same reason. ### Fee plans and what turns them into money @@ -2161,8 +2245,10 @@ already carries — and what gets written is an ordinary `enrollment` row, the same one `POST /courses/{id}/enrollments` writes, counted against the same `enrollment_count`. Each row a class writes is tagged with it as the row's `source`; **no `source` means placed by hand**, and that one bit is what makes -the sweeps below safe. It is internal bookkeeping, not API surface: no -enrollment response returns it. +the sweeps below safe. It rides back out on every enrollment response +(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a +hand-placed row — without it no client could tell which of the roster rows it +is showing a class change is about to remove. **Already enrolled is skipped.** A pair that already has an enrollment row is left exactly as it stands — no second seat charged, no `source` rewritten. A @@ -2178,6 +2264,14 @@ naming it (`course: is full, so the class cannot take this student`, claimed earlier in the same run: a half-enrolled class is worse than a refused one, and the refusal names the course whose capacity to raise. +A second `409` reads off the same claim and is deliberately told apart from it: +one of the class's attached courses **no longer exists** +(`course: no longer exists — detach it from this class first`). A seat +claim that matches nothing means "full" *or* "no such row", and reporting a +stale attachment as a full course would send staff off to raise a capacity that +is not there — on a class every member-add now fails on. Detach the link and +the class works again. + **Removals take back only what the class pumped, and repair before they delete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or detaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the @@ -2199,14 +2293,31 @@ remain a member, because the pump runs on writes, never on a schedule. Staff put them back by enrolling them by hand (which makes the row hand-placed) or by detaching and re-attaching the course. +**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments` +landing on a row a class pumped takes the row *off* that class — its `source` +is cleared, the response comes back with `"source": null` — so no later class +sweep can undo a placement an operator made on purpose. That is the mirror of +the rule above: hand-placed beats pumped in both directions, and without it +"hand-placed" was a state only a *first* enroll could ever reach. + **Delete guards.** A class still holding members or attached courses refuses deletion with a `409` ("remove its members and detach its courses first") — the roster it owes is never dropped out from under the courses silently. A term linked by any class refuses deletion the same way courses make it refuse. Deleting a **course** detaches it from every class it was on (its enrollments go with it), and a role change that takes a user off `student` drops their -class memberships exactly as it drops their enrollments — a membership left -behind would keep pumping them back into courses. +class memberships exactly as it drops their enrollments — in one transaction, +because a membership left behind would keep pumping them back into courses, +while an enrollment left behind would stay tagged with a class the released +counters had already made deletable, and nothing could ever sweep it again. + +**A link to a deleted course detaches instead of refusing.** Should a +`class_course` row ever be left pointing at a course row that is gone, +`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights +are read *off* the course, so a stale link had no readable owner and the detach +used to `404` forever — which also left the class permanently undeletable, its +attachment counter counting a row nothing could sweep. There is no roster left +to protect, and the caller is already teacher+. **Who may.** Creating, editing and deleting a class, and adding or removing its members, is **manager+** — a class is school structure, not classroom @@ -2214,15 +2325,37 @@ work. Attaching or detaching a course takes management rights on **that course** (its creator, a teacher assigned to it, or manager+), since the call writes that course's roster and nothing else: the same right enrolling one student takes. Every read (`GET /classes`, `/classes/{id}`, its members and -its courses, all paged, newest first) is **teacher+**. +its courses, all paged, newest first) is **teacher+** — and "newest" here means +when the student was *added* or the course *attached*, not the student's or the +course's own id, which is what a link row keyed on the pair would otherwise +sort by. Rows written before that stamp existed carry none, and sort last. **Codes.** Adding a member or attaching a course answers `201`; a repeat is a `409` ("the student is already in this class", "the course is already on this class"). An id in the **body** that names nothing — an unknown `user_id` or `course_id`, or a member who is not a `student` — is a `400`; an id in the **path** that names nothing (the class, or a member/course that was not on it) -is a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, both published in the -`course` group of `GET /limits`. +is a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students +and 50 courses** per class (`max_class_members`, `max_class_courses`), all four +published in the `course` group of `GET /limits`. Past either ceiling the +add or the attach is a `409` naming it ("this class already holds 200 +students") — a standing class someone can make room in, which is why it is not +the `404` a deleted class answers. Those two numbers are not comfort limits: +adding a member writes one enrollment per attached course and attaching a +course writes one per member, both in a *single* transaction, so each axis's +ceiling is the bound on the other axis's write loop — an unbounded class is an +unbounded transaction any manager could trigger. + +Which is why each write is refused on the **other** axis too. A class already +standing *above* a ceiling cannot take a member while it holds more than 50 +courses ("this class holds more than 50 courses — detach some before adding a +student"), nor a course while it holds more than 200 students ("this class +holds more than 200 students — remove some before attaching a course"), both +`409`. Room on the axis being written is not the question: the write loop's +length is set by the other one, and letting it run because *this* side has +space is exactly the unbounded transaction the ceilings exist to prevent. Only +a class that predates the ceilings can be there, and only shrinking the +overloaded axis clears it. ## Quick tour (curl) @@ -2652,6 +2785,13 @@ markers *are* the epoch index, which is why there is no epochs table and why the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`. `DELETE /boards/{id}` is the one operation here that really destroys marks. +**A blank canvas cannot be cleared** (`409` — as a closed board is, while a +participant who is not the creator gets the `403` the two doors above give +them). The marker is a real stored row and it is charged to the board's +lifetime budget, so a clear has to close at least one mark to be worth one — +without that rule every press of a button the creator can hold down minted a +free row, and the epoch index filled with zero-stroke sessions. + **Three caps, and only one of them is terminal** (all three published at `GET /limits` under `board`): @@ -2660,6 +2800,19 @@ the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`. history is kept, drawing resumes. - `max_board_strokes` bounds the board's **lifetime** storage — `total_stroke_count`, which never resets, because a clear keeps its history. + It counts **rows on the board**, not strokes drawn: a `clear` marker is a + stored row, so it costs one unit of the budget like any mark. The marker's + own unit is the one thing not refused at the ceiling — the last stroke of a + board's budget may well be closed by a clear, and refusing that would drop + the very marker the history needs to index the final epoch — so a board holds + at most `max_board_strokes + 1` rows. That held only for boards born after + the marker started paying, so **boot recomputes every board's + `total_stroke_count` from its actual rows**: a board an older binary cleared + is short exactly one per past clear, and an under-counting board is one that + keeps taking marks past the storage ceiling. This is the one backfill that is + not `= NONE`-guarded, and the one counter that may be recomputed — it is not + an opinion the live system maintains, it is the board's row count, so + recomputing converges instead of overwriting and the next boot writes nothing. Hitting it stamps `closed_at` and the board becomes **permanently read-only**: still fully readable and replayable, never deleted, and there is no reopen — open a new board. `POST /boards/{id}/close` is the manual form of @@ -2711,10 +2864,19 @@ value the client picks, echoed **verbatim** on that message's `saved` or server never reads it. `error` codes are a closed set: `epoch_full` (the live canvas is full — clear -it and keep drawing), `board_closed` (permanently read-only), `locked`, -`forbidden` (a creator-only command from a participant), `resync` (below), -`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`, -`unauthorized`, `too_many_requests`, `conflict`, `internal`. +it and keep drawing), `canvas_blank` (there was nothing on the canvas to clear +— the board is still live and still drawable), `board_closed` (permanently +read-only), `locked`, `forbidden` (a creator-only command from a participant), +`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload), +`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`. + +The two that look alike are the two that must not be confused: `board_closed` +is **terminal** and `canvas_blank` is **nothing to do**. A client that treats +them alike sends a live room off clearing a canvas it never needed to lose — +which is exactly what a code guessed from a *substring* of the refusal did +("the canvas is already blank" contains the word "closed"), so the server now +matches the refusal constants by value and a test pairs every one of them with +the code its client must act on. **Persist, then publish.** A stroke is fanned out only after its row has landed, so the channel can never carry a mark the database refused (a locked @@ -2812,7 +2974,11 @@ stop-the-world — `podman compose down` then `up`, never overlapping — and a release that adds or renames a stored counter *requires* it. An old binary writes rows without touching the new counter, the `= NONE` backfill guard (correctly) refuses to re-seed, and the resulting permanent under-count lets a -guard approve exactly what it exists to refuse. In-flight work does not survive +guard approve exactly what it exists to refuse. The one exception is a counter +that is not an opinion but a plain row count — a board's `total_stroke_count`, +recomputed from its strokes on every boot rather than seeded once, which is why +that repair heals an under-count the `= NONE` guard would have skipped. +In-flight work does not survive a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`. ## Layout diff --git a/src/constant.rs b/src/constant.rs index dc1eb82..e5dcd50 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -92,6 +92,24 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; pub const MAX_CLASS_NAME_LEN: usize = 200; pub const MAX_CLASS_GRADE_LEN: usize = 20; +/// How big one class may get, on each of its two axes. These are not comfort +/// numbers: attaching a course to a class writes one enrollment per member and +/// adding a member writes one per attached course, both in a *single* +/// transaction, so each axis's counter is the bound on the other axis's write +/// loop — a class with no ceiling is an unbounded transaction anyone with the +/// manager role can trigger. A şube is a homeroom (`MAX_HOMEWORK_ASSIGNED` +/// shares the 200) and its timetable is a school week, not a catalogue. +/// +/// Which is also why each write is refused on the *other* axis: a class created +/// before these numbers existed can stand above one of them, and the axis being +/// added to having room says nothing about the loop's length — that is set by +/// the axis it multiplies against. So the pump refuses a member while the class +/// holds more than `MAX_CLASS_COURSES` courses and a course while it holds more +/// than `MAX_CLASS_MEMBERS` students, and only shrinking the overloaded side +/// clears it. +pub const MAX_CLASS_MEMBERS: i64 = 200; +pub const MAX_CLASS_COURSES: i64 = 50; + pub const MAX_SUBJECT_NAME_LEN: usize = 200; pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000; diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index a4d49d9..e710fef 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -38,10 +38,34 @@ use crate::validate::validate_required; const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; -/// The `THROW` the clear transaction refuses with: not the creator, or the -/// board is already closed. A decision, so it outranks a lost round. +/// The `THROW` the clear transaction refuses with: a blank canvas, not the +/// creator, or the board is already closed. A decision, so it outranks a lost +/// round. const CLEAR_REFUSED: &str = "board_clear_refused"; +/// The public words of every refusal this module raises. `pub` because +/// `src/web/board_ws.rs` turns each into the machine-readable `code` its room +/// sends, and it matches these constants by value — a classifier that guessed +/// from a substring silently re-labelled a blank canvas as the *terminal* +/// `board_closed` the moment this wording changed. +pub const EPOCH_FULL: &str = "this board is full — clear it to keep drawing"; +pub const BOARD_LOCKED: &str = "this board is locked — the creator has paused drawing"; +pub const BOARD_CLOSED: &str = "this board is closed — it is permanently read-only"; +pub const BOARD_MOVED: &str = "this board changed while you were drawing — draw it again"; +pub const CANVAS_BLANK: &str = "there is nothing on this canvas to clear"; +pub const NOT_THE_CREATOR: &str = "only the board's creator can clear the board"; + +/// Every *conflict* refusal above — `NOT_THE_CREATOR` is a `Forbidden`, coded +/// by its variant alone. Listed so the room's classifier can be *proved* to +/// cover them all (src/web/board_ws.rs) rather than trusted to. +pub const REFUSALS: [&str; 5] = [ + EPOCH_FULL, + BOARD_LOCKED, + BOARD_CLOSED, + BOARD_MOVED, + CANVAS_BLANK, +]; + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BoardStrokeId(RecordId); @@ -165,9 +189,7 @@ impl BoardStroke { cap::ClaimedTwo::Made(saved) => Ok(saved), // The live canvas is full and nothing else: recoverable by a clear, // which resets this counter without losing a single mark. - cap::ClaimedTwo::FullSoft => Err(AppError::Conflict( - "this board is full — clear it to keep drawing", - )), + cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)), // Three refusals share this answer (lifetime full / guard failed / // board gone), so the board is re-read to tell them apart. A board // that changed state in between still gets told "no" — but only a @@ -180,9 +202,7 @@ impl BoardStroke { async fn why_refused(board: &BoardId, db: &Database) -> Result { let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; if board.is_locked() { - return Ok(AppError::Conflict( - "this board is locked — the creator has paused drawing", - )); + return Ok(AppError::Conflict(BOARD_LOCKED)); } if board.get_closed_at().is_none() { // Not closed yet. The lifetime counter has to say so *itself*: @@ -191,17 +211,13 @@ impl BoardStroke { // is open again now would otherwise be stamped read-only at one // stroke of a 50 000 budget — irreversibly, with no reopen. if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES { - return Ok(AppError::Conflict( - "this board changed while you were drawing — draw it again", - )); + return Ok(AppError::Conflict(BOARD_MOVED)); } // `Board::close` is the one-way idempotent stamp: a second append // takes this branch too and leaves the first `closed_at` standing. board.close(db).await?; } - Ok(AppError::Conflict( - "this board is closed — it is permanently read-only", - )) + Ok(AppError::Conflict(BOARD_CLOSED)) } /// The lifetime counter as the store holds it — the board struct @@ -223,6 +239,26 @@ impl BoardStroke { /// the epoch's final count — written apart, a crash between them would /// leave an epoch no marker indexes, and the playback would silently join /// two sessions into one. + /// + /// **The marker pays the lifetime counter.** It is a real `board_stroke` + /// row, so a marker that claimed nothing left `total_stroke_count` counting + /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES` + /// stopped bounding the table. Charged here, the counter is exactly the row + /// count again — the counter is reset and re-read in the same statement, so + /// the increment cannot be split off from the marker it pays for. + /// + /// **A blank canvas cannot be cleared.** Without it every call minted a row + /// for free, one per press of a button the creator can hold down. Requiring + /// the epoch counter to be non-zero pays for each marker with at least one + /// stroke it closes — and "there is nothing on this canvas to clear" is the + /// honest answer to the call it refuses. The epochs index keeps its meaning + /// too: no zero-stroke epoch can enter it. + /// + /// The marker's own increment is not capped: the last stroke of a board's + /// budget may be closed by a marker, so a board holds at most + /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that + /// files the final epoch in the index, which is the one clear the history + /// needs. pub async fn clear( board: &BoardId, by: &UserId, @@ -233,8 +269,10 @@ impl BoardStroke { // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699). let sql = format!( "BEGIN TRANSACTION; - LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0 \ - WHERE creator = $by AND closed_at = NONE RETURN BEFORE); + LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \ + {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \ + WHERE creator = $by AND closed_at = NONE \ + AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE); IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }}; CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \ epoch: $before[0].epoch, \ @@ -249,15 +287,18 @@ impl BoardStroke { ("kind".into(), KIND_CLEAR.into_value()), ("now".into(), Timestamp::now().as_millis().into_value()), ]; + // The epoch counter is reset here, which is a counter write like any + // other, so it owes the process the same one-at-a-time discipline + // (`cap::counter_lock`) — and unlike a lone conditional claim it is + // read back in the same statement, by the marker's `count`. + let _guard = cap::counter_lock().await; let (mut result, mut errors) = transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?; if errors .values() .any(|error| error.to_string().contains(CLEAR_REFUSED)) { - return Err(AppError::Conflict( - "this board cannot be cleared — it is closed, or you did not create it", - )); + return Err(Self::why_clear_refused(board, by, db).await?); } if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); @@ -271,6 +312,26 @@ impl BoardStroke { .ok_or_else(|| AppError::Internal("board clear wrote no marker".into())) } + /// Which of the clear guard's three conditions said no. One `WHERE` cannot + /// report that itself, so the board is re-read — on the refusal path only, + /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed + /// board is terminal for the room, a blank canvas is an ordinary "nothing + /// to do" and a room told otherwise stops drawing for good. + async fn why_clear_refused( + board: &BoardId, + by: &UserId, + db: &Database, + ) -> Result { + let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; + if board.get_closed_at().is_some() { + return Ok(AppError::Conflict(BOARD_CLOSED)); + } + if !board.is_creator(by) { + return Ok(AppError::Forbidden(NOT_THE_CREATOR)); + } + Ok(AppError::Conflict(CANVAS_BLANK)) + } + /// What a joining socket draws: the current epoch's marks only, in mint /// order, one [`BOARD_REPLAY_CHUNK`] at a time. /// @@ -606,13 +667,15 @@ mod tests { marker.get_epoch() ); } - // And the refused stroke claimed nothing: two marks, two epochs. + // And the refused stroke claimed nothing: two marks and the two + // markers that closed them, which is every row on the table. assert_eq!( BoardStroke::total_strokes(board.get_id(), &db) .await .unwrap(), - 2 + 4 ); + assert_eq!(stored.len(), 4); } /// The `next_ulid` hazard: rows minted inside one millisecond must replay diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 2a33e07..bea97b9 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -58,6 +58,17 @@ static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); /// instead of [`write`]'s — [`crate::domain::field_update::FieldUpdate`]'s term /// move claims and releases inside the very `UPDATE`'s transaction, and still /// owes the process one counter write at a time. +/// +/// **Is it load-bearing?** For the caps themselves, no — every one of them is a +/// single conditional write the store decides, and it decides it the same way +/// with a dozen writers in flight. So a counter write that skips this lock is +/// not a hole in a cap, and "every other site takes it" is not a correctness +/// argument. What the lock *is* load-bearing for is (a) the test suite, whose +/// in-memory engine forges wins under concurrency, and (b) any guard built out +/// of **two** statements that must not interleave with a rival's pair — +/// [`retire_name`] is exactly that, and it is why a skipped lock there would be +/// a real bug while a skipped lock around a lone `UPDATE … WHERE` is only +/// contention. pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> { CLAIM_LOCK.lock().await } @@ -149,7 +160,33 @@ pub(crate) async fn claim_and_create( content: &T, db: &Database, ) -> Result, AppError> { - claim_at_and_create(parent, field, cap, "", id, content, db).await + claim_at_and_create(parent, field, "$num", cap, "", id, content, db).await +} + +/// [`claim_and_create`] against a cap the *statement* reads rather than one the +/// caller snapshotted: `cap_expr` is SQL evaluated on the parent row at write +/// time (`audience.capacity ?? $num`, a subquery onto the settings singleton), +/// and `fallback` is the `$num` it coalesces to when the column is unset. +/// +/// A snapshotted cap is only ever a claim about the past. Bound as an integer, +/// a `PATCH` that *lowers* the cap while N requests are in flight admits all N +/// anyway — each one is measured against the number its own read saw, and the +/// single-record guard that makes concurrent claimers safe against each other +/// says nothing about the writer of the cap itself. Read inside the same +/// conditional write, the lowered cap refuses the very next claimer, because +/// the write that lowered it and the write that reads it contend on one record. +/// +/// `cap_expr` is always an in-crate SQL literal, never text from a client. +pub(crate) async fn claim_live_and_create( + parent: &RecordId, + field: &str, + cap_expr: &str, + fallback: i64, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + claim_at_and_create(parent, field, cap_expr, fallback, "", id, content, db).await } /// [`claim_and_create`], but only while `guard` — an extra predicate on that @@ -175,12 +212,14 @@ pub(crate) async fn claim_when_and_create( content: &T, db: &Database, ) -> Result, AppError> { - claim_at_and_create(parent, field, cap, guard, id, content, db).await + claim_at_and_create(parent, field, "$num", cap, guard, id, content, db).await } +#[allow(clippy::too_many_arguments)] async fn claim_at_and_create( parent: &RecordId, field: &str, + cap_expr: &str, cap: i64, extra: &str, id: &RecordId, @@ -197,7 +236,7 @@ async fn claim_at_and_create( LET $held = (SELECT VALUE id FROM $id); IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ - WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id); + WHERE ({field} ?? 0) < ({cap_expr}){extra} RETURN VALUE id); IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; CREATE $id CONTENT $row; COMMIT TRANSACTION;" @@ -390,17 +429,6 @@ pub(crate) async fn claim_two_when_and_create( .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } -/// Move `parent` to its next revision. A revision column is not a cap: it is -/// what a reader pins a value it took off the parent to, so that a write which -/// invalidates that value (a menu's price) can refuse the claim carrying the old -/// one. Every such mutation bumps *before* it writes, so a stale claim is -/// refused whether or not the mutation itself then lands. -pub(crate) async fn bump(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> { - let sql = format!("UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id"); - write(&sql, parent, UNLIMITED, db).await?; - Ok(()) -} - // --- reference counters -------------------------------------------------- // // The same single-record guard, pointed the other way. A cap asks "is there @@ -520,25 +548,104 @@ pub(crate) async fn claim_ref_and_create( .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } -/// Retire the name behind `id`: no further claim succeeds. `false` = something -/// still references it and the caller must refuse; nothing was written. -/// Idempotent — retiring an already-retired unused name lands again. -pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result { +/// What a retire / un-retire write did to the name's bit. +/// +/// The distinction a rollback lives on. Both writes are idempotent, so "it +/// ended up retired" says nothing about *who* retired it: a caller that undoes +/// a no-op undoes whoever really did flip the bit — two settings PATCHes each +/// dropping the same exam kind, one of them losing the row's compare-and-set, +/// left the kind gone from the list with its counter reading "in service", +/// which is a kind that grades again and can then never be removed. +pub(crate) enum Switched { + /// This call flipped the bit; a rollback owes the opposite write. + Flipped, + /// The bit already stood that way — this call wrote nothing, so there is + /// nothing to take back, and taking it back would undo somebody else. + Unchanged, + /// Retirement only: something still references the name and the caller must + /// refuse. Nothing was written. + InUse, +} + +/// Retire the name behind `id`: no further claim succeeds. Idempotent — a +/// retirement of an already-retired unused name lands again, and says so +/// ([`Switched::Unchanged`]) so the caller does not roll back a bit it never +/// set. +pub(crate) async fn retire_name(id: &RecordId, db: &Database) -> Result { // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which // is truthy for *every* row and would retire a name still in use. + // + // The bit as it stood is read in the *same round trip* as the write, so the + // pair is one hold of `CLAIM_LOCK` (see [`switch`]) and no rival in this + // process can retire the name between them and be undone by this caller. let sql = format!( - "UPSERT $parent SET {REF_RETIRED_FIELD} = true \ - WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id" + "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; + UPSERT $parent SET {REF_RETIRED_FIELD} = true \ + WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id" ); - Ok(!write(&sql, id, UNLIMITED, db).await?.is_empty()) + let (was, landed) = switch(&sql, id, db).await?; + Ok(match (landed, was) { + (false, _) => Switched::InUse, + (true, true) => Switched::Unchanged, + (true, false) => Switched::Flipped, + }) } /// Put a name back in service — it re-entered the list it was retired from, or -/// the edit that retired it never landed. -pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppError> { - let sql = format!("UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id"); - write(&sql, id, UNLIMITED, db).await?; - Ok(()) +/// the edit that retired it never landed. [`Switched::Flipped`] only when the +/// name really was retired, for [`retire_name`]'s reason pointed the other way. +pub(crate) async fn unretire_name(id: &RecordId, db: &Database) -> Result { + let sql = format!( + "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; + UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id" + ); + let (was, _) = switch(&sql, id, db).await?; + Ok(if was { + Switched::Flipped + } else { + Switched::Unchanged + }) +} + +/// [`retire_name`] as the yes/no the domain probes ask — did the name end up +/// retired? **Test-only**: production callers roll their edit back and need to +/// know which of the two "yes" answers they got. +#[cfg(test)] +pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result { + Ok(!matches!(retire_name(id, db).await?, Switched::InUse)) +} + +/// The read of the `retired` bit and the write that moves it, one round trip +/// under one [`CLAIM_LOCK`] hold: `(bit as it stood, did the write match)`. +async fn switch(sql: &str, parent: &RecordId, db: &Database) -> Result<(bool, bool), AppError> { + let _guard = CLAIM_LOCK.lock().await; + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let attempted = async { + let mut result = db + .query(sql) + .bind(("parent", parent.clone())) + .await? + .check()?; + let was = result + .take::>(0)? + .first() + .copied() + .unwrap_or(false); + let landed = !result.take::>(1)?.is_empty(); + Ok::<_, surrealdb::Error>((was, landed)) + } + .await; + match attempted { + Ok(answer) => return Ok(answer), + Err(err) if lost_the_race(&err) => last = Some(err), + Err(err) => return Err(err.into()), + } + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } /// Run one conditional counter write, retrying while the store reports a write @@ -550,8 +657,11 @@ pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppErro /// never letting two writers reach the database at once. So the queueing has to /// happen here. Backoff is exponential with jitter, because racers arrive in /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. -/// `num` is the statement's one number, bound as `$num`: a cap for the claims, -/// a step for the reference counters below. +/// `num` is the statement's one number, bound as `$num` — the cap. +/// +/// **Test-only**, like its one caller [`claim`]: every production counter write +/// now rides its child row's transaction and carries its own loop. +#[cfg(test)] async fn write( sql: &str, parent: &RecordId, @@ -853,6 +963,125 @@ mod tests { assert_eq!(menus(&db).await, 0); } + /// The `retired` bit as the store holds it, `None` when the row is absent. + async fn bit(db: &Database) -> Option { + let mut result = db + .query("SELECT VALUE retired FROM slot_ref:lunch") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().first().copied() + } + + fn lunch() -> RecordId { + RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch") + } + + /// Retirement is idempotent, so "it is retired now" is *not* "I retired + /// it" — and a caller that rolls back on the second answer un-retires a + /// name somebody else legitimately took out of service. That is the whole + /// settings-CAS wedge: the list drops the name, the counter says in + /// service, the name grades again and can then never be removed. + #[tokio::test] + async fn a_second_retirement_says_it_changed_nothing() { + let db = a_slot(0, false).await; + assert!(matches!( + retire_name(&lunch(), &db).await.unwrap(), + Switched::Flipped + )); + assert!(matches!( + retire_name(&lunch(), &db).await.unwrap(), + Switched::Unchanged + )); + assert_eq!(bit(&db).await, Some(true), "the winner's bit still stands"); + } + + /// The mirror: only the un-retire that really put a name back in service + /// owes a re-retirement, so a re-add that never lands cannot be undone + /// twice. + #[tokio::test] + async fn a_second_un_retirement_says_it_changed_nothing() { + let db = a_slot(0, true).await; + assert!(matches!( + unretire_name(&lunch(), &db).await.unwrap(), + Switched::Flipped + )); + assert!(matches!( + unretire_name(&lunch(), &db).await.unwrap(), + Switched::Unchanged + )); + assert_eq!(bit(&db).await, Some(false)); + } + + /// A referenced name is refused, and the refusal writes nothing — the + /// caller must not record an undo for it either. + #[tokio::test] + async fn a_referenced_name_refuses_and_leaves_the_bit_alone() { + let db = a_slot(1, false).await; + assert!(matches!( + retire_name(&lunch(), &db).await.unwrap(), + Switched::InUse + )); + assert_eq!(bit(&db).await, Some(false)); + } + + // --- claim_live_and_create ------------------------------------------ + + /// The cap the statement reads and the cap the caller remembers are + /// different numbers the moment anyone edits the cap. `epoch` stands in for + /// a capacity column here — any int on the parent row does. + #[tokio::test] + async fn a_live_cap_refuses_where_the_caller_s_snapshot_admits() { + let db = a_board(1, 0, false).await; + db.query("UPDATE board:b SET epoch = 1") + .await + .unwrap() + .check() + .unwrap(); + + // Live: one seat, one taken — full, and nothing written. + let live = claim_live_and_create( + &RecordId::new("board", "b"), + BOARD_EPOCH_STROKE_COUNT_FIELD, + "epoch ?? $num", + UNLIMITED, + &RecordId::new("board_stroke", "s1"), + &a_stroke(), + &db, + ) + .await + .unwrap(); + assert!(matches!(live, Claimed::Full)); + assert_eq!(stored(&db).await, (1, 0)); + assert_eq!(strokes(&db).await, 0); + + // The same row, the same instant, against a cap of 5 the caller read + // before it was lowered: admitted. That gap is the over-admission. + assert!(matches!(claim_one(&db, 5, "s2").await, Claimed::Made(_))); + assert_eq!(stored(&db).await, (2, 0)); + } + + /// An unset capacity column means "no cap", which is the bound `$num` + /// fallback — not a cap of zero that refuses everything. + #[tokio::test] + async fn an_absent_live_cap_falls_back_to_the_bound_number() { + let db = a_board(0, 0, false).await; + let made = claim_live_and_create( + &RecordId::new("board", "b"), + BOARD_EPOCH_STROKE_COUNT_FIELD, + "capacity ?? $num", + UNLIMITED, + &RecordId::new("board_stroke", "s1"), + &a_stroke(), + &db, + ) + .await + .unwrap(); + assert!(matches!(made, Claimed::Made(_))); + assert_eq!(stored(&db).await, (1, 0)); + } + #[tokio::test] async fn a_duplicate_row_claims_no_reference() { let db = a_slot(0, false).await; diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 7af8cbd..05fe701 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -7,12 +7,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::{ - CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN, + CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, DEFAULT_MAX_CHATBOT_THREADS, + MAX_CHATBOT_THREAD_TITLE_LEN, SETTINGS_KEY, SETTINGS_TABLE, }; use crate::database::Database; use crate::domain::cap; use crate::domain::page::PagedList; -use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -90,16 +90,24 @@ impl ChatbotThread { /// Start a thread unless `user` is already at the school's /// `max_chatbot_threads`. The slot is taken on the user row in the same - /// transaction as the thread ([`cap::claim_and_create`]) — an atomic + /// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic /// single-record write, so two requests racing the same user's last slot - /// cannot both win, the counter can never count a row that did not commit, - /// and the cap is read fresh so a concurrent settings PATCH is respected. + /// cannot both win and the counter can never count a row that did not + /// commit. + /// + /// The cap is the one *live* on the settings singleton, sub-queried inside + /// that same conditional write rather than bound as a number: this cap does + /// not live on the parent row (the seat is on the user, the limit is the + /// school's), and a snapshot of it admits every request already in flight + /// when a `PATCH /settings` lowers it. The subquery costs one extra record + /// read per claim on a path that already reads the row it writes. + /// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own + /// absent column means — no row, or a school that never set the knob. pub async fn create_capped( user: &UserId, title: Option, db: &Database, ) -> Result { - let limit = Settings::load(db).await?.get_max_chatbot_threads(); let now = Timestamp::now(); let thread = ChatbotThread { id: ChatbotThreadId::generate(), @@ -108,10 +116,13 @@ impl ChatbotThread { created_at: now, updated_at: now, }; - match cap::claim_and_create( + match cap::claim_live_and_create( &user.record(), CHATBOT_THREAD_COUNT_FIELD, - limit, + &format!( + "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num" + ), + DEFAULT_MAX_CHATBOT_THREADS, &thread.id.record(), &thread, db, @@ -237,7 +248,7 @@ impl ChatbotThread { #[cfg(test)] mod tests { use super::*; - use crate::domain::settings::SettingsParams; + use crate::domain::settings::{Settings, SettingsParams}; /// The owner's counter and the threads it counts, both re-read out of the /// store — never off a return value, which the in-memory engine forges diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index cff2498..8275a68 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -6,12 +6,13 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::CLASS_COURSE_TABLE; +use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id}; +use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; use crate::domain::course::CourseId; use crate::domain::page::PagedList; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -43,6 +44,11 @@ pub struct ClassCourse { class: ClassGroupId, course: CourseId, attached_by: UserId, + /// When it was attached, and the *only* thing "newest first" can mean here: + /// the row's id is the (class, course) pair, so ordering by it sorts the + /// list by the course's own ULID. Optional because rows written before this + /// column carry no stamp — see the migration note. + attached_at: Option, } impl ClassCourse { @@ -79,6 +85,7 @@ impl ClassCourse { class: class.clone(), course: course.clone(), attached_by: attached_by.clone(), + attached_at: Some(Timestamp::now()), }; match attach( class, @@ -94,9 +101,24 @@ impl ClassCourse { Attached::Made(saved) => Ok(saved), Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")), Attached::Gone => Err(AppError::NotFound), + Attached::ClassFull => Err(AppError::ConflictOwned(format!( + "this class already holds {MAX_CLASS_COURSES} courses" + ))), + // The other axis: attaching one course enrolls the whole roster, so + // a class over *that* ceiling cannot take a course however few it + // carries. Only a class predating the ceiling can be here. + Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!( + "this class holds more than {MAX_CLASS_MEMBERS} students — \ + remove some before attaching a course" + ))), Attached::Full(full) => Err(AppError::ConflictOwned(format!( "{full} cannot hold the whole class" ))), + // Another of the class's links points at a deleted course. This + // axis claims its own pivot, so it is never *this* course. + Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!( + "{course} no longer exists — detach it from this class first" + ))), } } @@ -114,7 +136,6 @@ impl ClassCourse { let gone = detach( "$link", Axis::Course, - Sweep::Rows, &[( "link".into(), ClassCourseId::composite(class, course) @@ -127,7 +148,10 @@ impl ClassCourse { (gone > 0).then_some(()).ok_or(AppError::NotFound) } - /// The courses a class is attached to, newest first. + /// The courses a class is attached to, newest first — by when they were + /// attached, not by the course's own id, which is what the composite record + /// id sorts on. A row older than the column carries no stamp at all, and + /// NONE sorts last under DESC — the honest place for a row of unknown age. pub async fn list_for_class( class: &ClassGroupId, limit: Option, @@ -136,7 +160,7 @@ impl ClassCourse { ) -> Result<(Vec, i64), AppError> { PagedList::new( format!("{CLASS_COURSE_TABLE} WHERE class = $class"), - "ORDER BY id DESC", + "ORDER BY attached_at DESC, id DESC", ) .bind("class", class.record()) .run(limit, offset, db) diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index eaeff53..8187191 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -7,11 +7,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::CLASS_MEMBER_TABLE; +use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::Database; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id}; +use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; use crate::domain::page::PagedList; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -43,6 +44,11 @@ pub struct ClassMember { class: ClassGroupId, user: UserId, added_by: UserId, + /// When they were added, and the *only* thing "newest first" can mean here: + /// the row's id is the (class, user) pair, so ordering by it sorts the + /// roster by the student's account ULID. Optional because rows written + /// before this column carry no stamp — see the migration note. + added_at: Option, } impl ClassMember { @@ -80,6 +86,7 @@ impl ClassMember { class: class.clone(), user: user.clone(), added_by: added_by.clone(), + added_at: Some(Timestamp::now()), }; match attach( class, @@ -95,9 +102,25 @@ impl ClassMember { Attached::Made(saved) => Ok(saved), Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")), Attached::Gone => Err(AppError::NotFound), + Attached::ClassFull => Err(AppError::ConflictOwned(format!( + "this class already holds {MAX_CLASS_MEMBERS} students" + ))), + // The other axis: adding one student enrolls them into every + // attached course, so a class over *that* ceiling cannot take a + // member however much room its roster has. + Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!( + "this class holds more than {MAX_CLASS_COURSES} courses — \ + detach some before adding a student" + ))), Attached::Full(course) => Err(AppError::ConflictOwned(format!( "{course} is full, so the class cannot take this student" ))), + // Not a capacity problem, and told apart from one on purpose: no + // number anyone can raise unblocks this class, only detaching the + // link the deleted course left behind. + Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!( + "{course} no longer exists — detach it from this class first" + ))), } } @@ -116,7 +139,6 @@ impl ClassMember { let gone = detach( "$link", Axis::Member, - Sweep::Rows, &[( "link".into(), ClassMemberId::composite(class, user).record().into_value(), @@ -127,23 +149,10 @@ impl ClassMember { (gone > 0).then_some(()).ok_or(AppError::NotFound) } - /// Drop every class `user` belongs to, giving each class its member count - /// back — and nothing else. The enrollments are - /// [`crate::domain::enrollment::Enrollment::delete_for_user`]'s to delete; - /// this sweeping them too would decrement the same seats twice. - pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> { - detach( - &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), - Axis::Member, - Sweep::CounterOnly, - &[("usr".into(), user.record().into_value())], - db, - ) - .await?; - Ok(()) - } - - /// The class's roster, newest first. + /// The class's roster, newest first — by when the student was added, not by + /// their account id, which is what the composite record id sorts on. + /// A row older than the column carries no stamp at all, and NONE sorts last + /// under DESC — which is the honest place for a row of unknown age. pub async fn list_for_class( class: &ClassGroupId, limit: Option, @@ -152,7 +161,7 @@ impl ClassMember { ) -> Result<(Vec, i64), AppError> { PagedList::new( format!("{CLASS_MEMBER_TABLE} WHERE class = $class"), - "ORDER BY id DESC", + "ORDER BY added_at DESC, id DESC", ) .bind("class", class.record()) .run(limit, offset, db) @@ -476,11 +485,12 @@ pub(crate) mod tests { assert_eq!(counter("class_member_count", class.record(), &db).await, 0); } - /// The role-demotion sweep: memberships go and their counters come back, - /// while the enrollment rows are left for `Enrollment::delete_for_user`. - /// Decrementing those seats here as well would take each one back twice. + /// The role-change sweep, which is now one transaction over both tables: + /// the memberships go with their counters, the enrollment rows go with + /// their seats, and each seat comes back exactly once — the double + /// decrement the old two-call split existed to avoid. #[tokio::test] - async fn delete_for_user_leaves_the_enrollments_alone() { + async fn the_role_sweep_takes_memberships_and_enrollments_together() { let db = crate::database::init_mem().await.unwrap(); let manager = UserId::from_key("manager"); let student = UserId::from_key("student"); @@ -497,7 +507,9 @@ pub(crate) mod tests { .await .unwrap(); - ClassMember::delete_for_user(&student, &db).await.unwrap(); + crate::domain::class_pump::sweep_non_student(&student, &db) + .await + .unwrap(); assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); for class in [&first, &second] { assert_eq!( @@ -508,18 +520,26 @@ pub(crate) mod tests { } assert_eq!( source_of(&algebra, &student, &db).await, - Some(Some(first.clone())), - "the enrollment is the other sweep's to delete" + None, + "the enrollment goes in the same transaction as the membership" ); assert_eq!( counter("enrollment_count", algebra.record(), &db).await, - 1, - "…and its seat is the other sweep's to release" + 0, + "…and its seat comes back once, not twice" + ); + // Which is the point of folding them: the class the student was in is + // free of them entirely — no membership, no count, and no enrollment + // row left tagged with a class that is about to be deletable. + assert!( + crate::domain::class_group::ClassGroup::read(&second, &db) + .await + .unwrap() + .unwrap() + .delete(&db) + .await + .unwrap(), + "a class holding neither members nor courses must delete" ); - - // Which is exactly what the demotion calls next, and the seat comes - // back once, not twice. - Enrollment::delete_for_user(&student, &db).await.unwrap(); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); } } diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index 1c81ee7..1983552 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -26,22 +26,44 @@ use surrealdb::types::{RecordId, SurrealValue, Value}; use crate::constant::{ CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, - ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, + ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; -use crate::domain::class_group::ClassGroupId; +use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::domain::user::UserId; use crate::error::AppError; -/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` is a *prefix*: the -/// record id of the course that had no seat is appended to it, because "the -/// class does not fit" is unanswerable without knowing which course to raise -/// the capacity of, and the loop only learns that at runtime. The whole id and -/// not just the key, so the refusal names something a caller can look up -/// without knowing which table it came from. +/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK` +/// are *prefixes*: the record id of the course the loop stopped on is appended +/// to them, because neither "the class does not fit" nor "that course is gone" +/// is answerable without naming the course, and the loop only learns which one +/// at runtime. The whole id and not just the key, so the refusal names +/// something a caller can look up without knowing which table it came from. +/// +/// `MISSING_MARK` is deliberately not `FULL_MARK`: a seat claim that matches +/// nothing means "full" *or* "no such row", and reporting a class-course link +/// left pointing at a deleted course as a full course sends the caller to raise +/// a capacity that does not exist, on a class every member add now fails on. +/// +/// `CAP_MARK` is the class counter's claim matching nothing, which is "the +/// class is full" *or* "the class is gone" — one conditional write cannot say +/// which, so it stays one marker and the read that tells them apart is paid for +/// only on that path (the same shape as +/// [`crate::domain::enrollment::Enrollment::enroll`]). It is not `GONE_MARK`: +/// that one is the *pivot* claim, which is a different row. +/// +/// `OVER_MARK` is the *other* axis already standing above its own ceiling — +/// which no claim on this axis can see, and which is what bounds this +/// transaction's write loop (see [`Axis::cap`]). It is its own marker because +/// "this class holds too many courses" is not an answer anyone can act on when +/// it is reported as "this class holds too many students". const HELD_MARK: &str = "class_held"; const GONE_MARK: &str = "class_gone"; +const CAP_MARK: &str = "class_cap"; +const OVER_MARK: &str = "class_over"; const FULL_MARK: &str = "class_full:"; +const MISSING_MARK: &str = "class_no_course:"; /// What [`attach`] settled. pub(crate) enum Attached { @@ -51,12 +73,26 @@ pub(crate) enum Attached { /// The link already exists — nothing was written, and no seat was spent /// finding that out. Duplicate, - /// The class row is gone (a concurrent delete won). Nothing was written. + /// The class row — or, on the course axis, the course being attached — is + /// gone (a concurrent delete won). Nothing was written. Gone, + /// The class is at its own ceiling on this axis. Nothing was written, and + /// it is told apart from [`Attached::Gone`] because a full class is a + /// standing row someone can make room in, not a 404. + ClassFull, + /// The class stands *above* the ceiling on the other axis, so the write + /// loop this attach would run is longer than any transaction is allowed to + /// be. Only a class predating the ceilings can be here, and only its own + /// axis can make room — which is why it is not [`Attached::ClassFull`]. + ClassOverloaded, /// One of the courses had no free seat, named by its key. Nothing was /// written — not one of the earlier seats in the same run, which is the /// whole point of doing this in a transaction. Full(String), + /// One of the courses the class carries no longer exists, named by its id: + /// a stale `class_course` link. Nothing was written, and no capacity anyone + /// can raise will change that answer. + CourseGone(String), } /// Which way the pump runs: the loop below needs a `(course, user)` pair per @@ -96,6 +132,37 @@ impl Axis { } } + /// The in-transaction proof that this axis's *pivot* row is still there, + /// as the statements that claim it. + /// + /// The class counter's conditional claim covers the class; nothing covered + /// the course. With an empty roster the pair loop in [`attach`] touches no + /// row at all, so a concurrent `DELETE /courses/{id}` conflicts with + /// nothing — SurrealDB does not conflict-check that (write-skew) — and the + /// attach commits a `class_course` row pointing at a course that no longer + /// exists. A conditional write on the course row *is* the check: it matches + /// nothing once the row is gone, and it puts this transaction on the very + /// record the course's delete guard writes. + /// + /// The counter is re-stated verbatim rather than incremented: the row must + /// be touched, not changed, and `count = count` leaves an absent counter + /// absent, so the boot backfill still sees the `NONE` it seeds off. + /// + /// The member axis claims nothing: its pivot is a user, whose row is no + /// class write's to touch, and a membership left pointing at a deleted user + /// is still removable by its own route — which is exactly what a link to a + /// deleted course was not. + fn pivot_claim(&self) -> String { + match self { + Axis::Member => String::new(), + Axis::Course => format!( + "LET $alive = (UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \ + {ENROLLMENT_COUNT_FIELD} RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }};" + ), + } + } + /// The class counter this axis's link rows are counted on. Taken off the /// axis rather than passed in beside it, because the two are one fact and a /// call site that paired the member axis with the course counter would @@ -107,15 +174,87 @@ impl Axis { Axis::Course => CLASS_COURSE_COUNT_FIELD, } } + + /// How many link rows this axis's counter may reach. Taken off the axis + /// beside the counter it bounds, for the same reason. + /// + /// This is what makes the pair loop in [`attach`] finite, and it does it + /// *crosswise*: the member axis's loop iterates the class's `class_course` + /// rows, which the course axis's counter caps, and the course axis's loop + /// iterates its `class_member` rows, which the member axis's counter caps. + /// So bounding the two counters bounds both write loops — one transaction + /// can never carry more than `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES` + /// enrollment writes. + /// + /// Crosswise is also why the claim alone is not enough. It bounds the axis + /// being *added*, and the loop it runs is the length of the *other* one: a + /// class that already holds more members than `MAX_CLASS_MEMBERS` — the + /// layer shipped before either ceiling existed, so a real volume can carry + /// one — could still have a course attached, and that attach writes one + /// enrollment per member. So [`attach`] checks the other axis too + /// ([`Axis::other`]), and the bound holds for stale classes as well. + fn cap(&self) -> i64 { + match self { + Axis::Member => MAX_CLASS_MEMBERS, + Axis::Course => MAX_CLASS_COURSES, + } + } + + /// The axis whose link rows this one's write loop iterates — its counter is + /// the length of that loop, and its ceiling is therefore the second half of + /// the bound. + fn other(&self) -> Axis { + match self { + Axis::Member => Axis::Course, + Axis::Course => Axis::Member, + } + } } -/// Whether a [`detach`] also reconciles the enrollment rows its links pumped. -pub(crate) enum Sweep { - /// Repair or delete them, per the rule in [`detach`]. - Rows, - /// Release the counters and touch nothing else, because something else owns - /// the enrollment side of this same event. - CounterOnly, +/// Everything a user's role change *off* `student` invalidates, in one +/// transaction: every class membership they hold (each class getting its member +/// count back) and every enrollment row they hold (each course getting its seat +/// back). +/// +/// One transaction because the two halves are one fact. Run as two, a failure +/// between them released the memberships and both class counters while the +/// enrollment rows kept `source = class_group:X` — the class then passed its +/// zero-zero delete guard, and the rows were left tagged with a class that no +/// longer existed and that no sweep could ever reach. Ordering them the other +/// way only swaps which corruption is reachable: memberships surviving on a +/// non-student are memberships the next attach pumps back into a course. +/// +/// The enrollment side takes *every* row, hand-placed ones included, and that +/// is the rule rather than an oversight: what the role change invalidates is +/// not "rows a class wrote" but enrollment itself — only students enroll, and +/// enrollment is what gates sitting exams, being graded and appearing on a +/// roster. A row kept for a teacher would grant nothing and count a seat. +/// Nothing restores them on a demotion back to `student`; a promotion is a +/// roster decision of its own. +pub(crate) async fn sweep_non_student(user: &UserId, db: &Database) -> Result<(), AppError> { + let sql = format!( + "BEGIN TRANSACTION; + LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE); + FOR $link IN ($links ?? []) {{ + UPDATE $link.class SET {CLASS_MEMBER_COUNT_FIELD} = \ + math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + LET $gone = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE); + FOR $row IN ($gone ?? []) {{ + UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \ + math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + COMMIT TRANSACTION;" + ); + // Admissible by construction: `DELETE` and `UPDATE` only, so no statement + // can answer "already exists" and every lost round is a plain re-send. + let (_, mut errors) = + transaction_with_retry(db, &sql, &[("usr".into(), user.record().into_value())], &[]) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(()) } /// Write `link` and enroll everything it implies, or write nothing at all. @@ -129,7 +268,9 @@ pub(crate) enum Sweep { /// The class counter is claimed by a conditional write rather than a bare /// increment, so a class deleted out from under this run matches nothing and /// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row -/// that no longer exists. +/// that no longer exists. The same write carries the axis's [`Axis::cap`], +/// which is what keeps the pair loop below — and therefore this transaction — +/// finite: [`Attached::ClassFull`] once the class is at its ceiling. /// /// Every enrollment in the loop is *skipped* when the pair already has a row — /// no seat charged, and the existing row's `source` left exactly as it was, so @@ -153,18 +294,29 @@ pub(crate) async fn attach( ) -> Result, AppError> { let count_field = axis.counter(); let pairs = axis.pairs(); + let alive = axis.pivot_claim(); + let other = axis.other(); + let over_field = other.counter(); + // Read off the class row inside the transaction that claims it, so the + // count this refuses on is the one the pair loop below would iterate. let sql = format!( "BEGIN TRANSACTION; LET $held = (SELECT VALUE id FROM $link); IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; + {alive} + LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap); + IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}; LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \ - WHERE ({count_field} ?? 0) < $unlimited RETURN VALUE id); - IF array::len($counted) = 0 {{ THROW '{GONE_MARK}' }}; + WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id); + IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}; CREATE $link CONTENT $row; FOR $pair IN (({pairs}) ?? []) {{ LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat( record::id($pair.course), '_', record::id($pair.user))); IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{ + IF array::len((SELECT VALUE id FROM $pair.course)) = 0 {{ + THROW '{MISSING_MARK}' + $pair.course + }}; LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \ ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \ WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \ @@ -188,8 +340,17 @@ pub(crate) async fn attach( ("pivot".into(), pivot.into_value()), ("by".into(), by.into_value()), ("unlimited".into(), cap::UNLIMITED.into_value()), + ("class_cap".into(), axis.cap().into_value()), + ("other_cap".into(), other.cap().into_value()), + ], + &[ + HELD_MARK, + GONE_MARK, + OVER_MARK, + CAP_MARK, + FULL_MARK, + MISSING_MARK, ], - &[HELD_MARK, GONE_MARK, FULL_MARK], ) .await?; // "Already linked" is read first: it outranks both refusals below, and the @@ -214,30 +375,60 @@ pub(crate) async fn attach( { return Ok(Attached::Gone); } + // Read before the ceiling below: a class over the *other* axis's ceiling is + // refused whether or not this axis has room, and being told it is full on + // an axis with places left is an answer nobody can act on. + if errors + .values() + .any(|error| error.to_string().contains(OVER_MARK)) + { + return Ok(Attached::ClassOverloaded); + } + // Full, or the class is gone — the counter claim matches nothing either + // way, and only this path pays for the read that tells them apart. + if errors + .values() + .any(|error| error.to_string().contains(CAP_MARK)) + { + return Ok(match ClassGroup::read(class, db).await? { + Some(_) => Attached::ClassFull, + None => Attached::Gone, + }); + } + // The stale link is read before "full": both come out of the same seat + // claim matching nothing, and only one of them is a capacity problem. + if let Some(course) = errors + .values() + .find_map(|error| named_course(&error.to_string(), MISSING_MARK)) + { + return Ok(Attached::CourseGone(course)); + } if let Some(course) = errors .values() - .find_map(|error| full_course(&error.to_string())) + .find_map(|error| named_course(&error.to_string(), FULL_MARK)) { return Ok(Attached::Full(course)); } if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + // Slots count BEGIN and three LET/IF pairs: the CREATE is slot 7 — or 9 on + // an axis that claims its pivot with a LET/IF pair of its own. + let made = if alive.is_empty() { 7 } else { 9 }; result - .take::>(5)? + .take::>(made)? .into_iter() .next() .map(Attached::Made) .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into())) } -/// The course id out of a `class_full::` abort. Table names and the +/// The course id out of a `
:` abort. Table names and the /// generated ULID keys here are alphanumeric and `:` joins them, so the id ends /// where the store's own wrapping around the thrown text begins. -fn full_course(message: &str) -> Option { +fn named_course(message: &str, mark: &str) -> Option { let id: String = message - .split_once(FULL_MARK)? + .split_once(mark)? .1 .chars() .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':')) @@ -264,28 +455,19 @@ fn full_course(message: &str) -> Option { /// "this class has a member" and "that member has a live pumped row" are /// independent facts and the loop simply finds nothing to sweep. /// -/// [`Sweep::CounterOnly`] is the deliberate half of this: dropping a *user's* -/// whole membership releases the counters and nothing else, because -/// `Enrollment::delete_for_user` owns the enrollment side of that same event and -/// a second decrement of the same seat is a bug, not a belt. -/// /// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in /// the cascade can answer "already exists" and every lost round is a plain /// re-send. pub(crate) async fn detach( links: &str, axis: Axis, - sweep: Sweep, bindings: &[(String, Value)], db: &Database, ) -> Result { let count_field = axis.counter(); - let sweep = match sweep { - Sweep::CounterOnly => String::new(), - Sweep::Rows => { - let scope = axis.scope(); - format!( - "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \ + let scope = axis.scope(); + let sweep = format!( + "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \ WHERE {scope} AND source = $link.class) ?? []) {{ LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \ WHERE course = $row.course AND class != $link.class); @@ -299,9 +481,7 @@ pub(crate) async fn detach( math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}; }};" - ) - } - }; + ); let sql = format!( "BEGIN TRANSACTION; LET $gone = (DELETE {links} RETURN BEFORE); @@ -386,7 +566,6 @@ mod tests { let gone = detach( &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), Axis::Member, - Sweep::CounterOnly, &[("usr".into(), student.record().into_value())], &db, ) @@ -409,7 +588,6 @@ mod tests { let again = detach( &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), Axis::Member, - Sweep::CounterOnly, &[("usr".into(), student.record().into_value())], &db, ) @@ -421,14 +599,22 @@ mod tests { #[test] fn a_full_abort_names_its_course() { assert_eq!( - full_course("An error occurred: class_full:course:01J8XZ0K3Q"), + named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK), Some("course:01J8XZ0K3Q".to_string()) ); assert_eq!( - full_course("class_full:course:algebra'"), + named_course("class_full:course:algebra'", FULL_MARK), + Some("course:algebra".into()) + ); + assert_eq!(named_course("class_held", FULL_MARK), None); + assert_eq!(named_course("class_full:", FULL_MARK), None); + // And the stale-link abort reads off the same shape, without the two + // markers ever matching each other's text. + assert_eq!( + named_course("class_no_course:course:algebra'", MISSING_MARK), Some("course:algebra".into()) ); - assert_eq!(full_course("class_held"), None); - assert_eq!(full_course("class_full:"), None); + assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None); + assert_eq!(named_course("class_full:course:a", MISSING_MARK), None); } } diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 2cc54ab..57bf1fe 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::class_group::ClassGroupId; use crate::domain::course::{Course, CourseId}; @@ -9,6 +9,11 @@ use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::AppError; +/// The `THROW` markers [`Enrollment::enroll`]'s claim aborts with: this pair +/// already holds a row, and the roster is full. +const HELD_MARK: &str = "enroll_held"; +const FULL_MARK: &str = "enroll_full"; + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EnrollmentId(RecordId); @@ -80,13 +85,22 @@ impl Enrollment { /// pair converge on one row instead of racing the unique index into a 500: /// the loser of the `CREATE` reads the winner's row back and returns it. /// When the course carries a capacity, a full roster refuses new members - /// (409) — the seat is taken by [`cap::claim`] on the course row, an atomic - /// single-record conditional write, so the cap holds against concurrent - /// enrolls and a concurrent capacity PATCH alike. An already enrolled user is - /// returned as-is even when the roster is full, and never charged a seat. - /// The same claim is the delete guard's other half: it is refused outright - /// once the course row is gone, and while it holds a seat the course cannot - /// be deleted — so no roster row can outlive its course. + /// (409) — the seat is taken by a single-record conditional write on the + /// course row whose bound is the row's *own* `capacity` column, read inside + /// the same statement that spends the seat. A snapshot integer taken by a + /// read beforehand would be exactly the number a concurrent capacity PATCH + /// invalidates, which is what this promised and did not do. An already + /// enrolled user is returned as-is even when the roster is full, and never + /// charged a seat. The same claim is the delete guard's other half: it + /// matches nothing once the course row is gone, and while it holds a seat + /// the course cannot be deleted — so no roster row can outlive its course. + /// + /// On admissibility ([`crate::database::transaction_with_retry`]): the + /// `CREATE` here *can* answer "already exists", but only to a rival that + /// landed inside this very window — and the re-send then sees that row at + /// the `$held` gate and takes the other branch, so the loop converges + /// instead of re-asking a settled question. Same shape, same reason, as + /// [`crate::domain::class_pump::attach`]. pub async fn enroll( course: &CourseId, user: &UserId, @@ -94,12 +108,8 @@ impl Enrollment { db: &Database, ) -> Result { if let Some(existing) = Self::read_for_user(course, user, db).await? { - return Ok(existing); + return Self::disown_if_pumped(existing, db).await; } - let capacity = Course::read(course, db) - .await? - .ok_or(AppError::NotFound)? - .get_capacity(); let enrollment = Enrollment { id: EnrollmentId::composite(course, user), course: course.clone(), @@ -113,30 +123,101 @@ impl Enrollment { // to be *seen*, or the pair's second writer would keep the seat it // claimed for a row that already existed and the counter would drift // above the roster forever. - match cap::claim_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - capacity.unwrap_or(cap::UNLIMITED), - &enrollment.id.record(), - &enrollment, + // + // Parenthesized `??` throughout: `n ?? 0 < cap` parses as + // `n ?? (0 < cap)`, which is truthy for every row and would enroll past + // the capacity. + let sql = format!( + "BEGIN TRANSACTION; + LET $held = (SELECT VALUE id FROM $id); + IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; + LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \ + ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \ + WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \ + RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; + CREATE $id CONTENT $row; + COMMIT TRANSACTION;" + ); + // The process still sends its counter writes one at a time (see + // [`cap::counter_lock`]); this statement moves the same counter every + // cap claim does. + let _guard = cap::counter_lock().await; + let (mut result, mut errors) = transaction_with_retry( db, + &sql, + &[ + ("id".into(), enrollment.id.record().into_value()), + ("row".into(), enrollment.clone().into_value()), + ("course".into(), course.record().into_value()), + ("unlimited".into(), cap::UNLIMITED.into_value()), + ], + &[HELD_MARK, FULL_MARK], ) - .await? + .await?; + // Someone placed this pair first; their row is the answer, and no seat + // was spent finding that out. It is read first: it outranks the refusal + // below, and the gate aborts before the seat is touched. + if errors + .values() + .any(|error| error.to_string().contains(HELD_MARK)) + { + return match Self::read_for_user(course, user, db).await? { + Some(existing) => Self::disown_if_pumped(existing, db).await, + None => Err(AppError::Internal("failed to enroll user".into())), + }; + } + // Full, or the course is gone — the conditional write matches nothing + // either way, and only this path pays for the read that tells them + // apart. + if errors + .values() + .any(|error| error.to_string().contains(FULL_MARK)) { - cap::Claimed::Made(saved) => Ok(saved), - // Someone placed this pair first; their row is the answer, and no - // seat was spent finding that out. - cap::Claimed::Duplicate => Self::read_for_user(course, user, db) - .await? - .ok_or_else(|| AppError::Internal("failed to enroll user".into())), - // Full, or the course was deleted between the read and the claim — - // the conditional write matches nothing either way, and only this - // path pays for the read that tells them apart. - cap::Claimed::Full => match Course::read(course, db).await? { + return match Course::read(course, db).await? { Some(_) => Err(AppError::Conflict("the course is full")), None => Err(AppError::NotFound), - }, + }; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); } + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + result + .take::>(5)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to enroll user".into())) + } + + /// A hand enroll landing on a row a class pumped takes the row *off* the + /// class: `source` goes, so no later class sweep can unenroll a student an + /// operator placed on purpose. The mirror of the rule the sweep already + /// holds in the other direction — a manual unenroll wins, permanently — and + /// without it "hand-placed" was a state only a first enroll could reach. + /// + /// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the + /// struct doc), and it is what a hand enroll writes on the create path. + async fn disown_if_pumped(existing: Enrollment, db: &Database) -> Result { + if existing.source.is_none() { + return Ok(existing); + } + let mut result = db + .query("UPDATE $id UNSET source RETURN AFTER") + .bind(("id", existing.id.record())) + .await? + .check()?; + // A row that is no longer there is not an internal error: an unenroll + // (or the class sweep a role change runs) landing between the read + // above and this write matches nothing, and the caller asked to be + // enrolled — which they were, by the row this call was handed. The + // disown is all that is lost, and it is lost to a delete that took the + // whole row with it. + Ok(result + .take::>(0)? + .into_iter() + .next() + .unwrap_or(existing)) } /// Some(_) iff `user` is enrolled in `course` — the grading gate. @@ -166,23 +247,6 @@ impl Enrollment { .await } - /// Drop every enrollment `user` holds, across all courses. Only students - /// enroll, so promotion out of `student` calls this to clear the rosters. - pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> { - db.query( - "BEGIN TRANSACTION; - LET $gone = (DELETE enrollment WHERE user = $usr RETURN BEFORE); - FOR $row IN ($gone ?? []) { - UPDATE $row.course SET enrollment_count = math::max([(enrollment_count ?? 0) - 1, 0]); - }; - COMMIT TRANSACTION;", - ) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } - pub async fn remove( course: &CourseId, user: &UserId, @@ -237,6 +301,31 @@ mod tests { assert_eq!(decoded.get_source(), None); } + /// A pumped row that vanishes under the disown — a concurrent unenroll, or + /// the sweep a role change runs — must answer the row the caller was + /// handed, not a 500. The `UPDATE` matches nothing and used to fall through + /// to `AppError::Internal`, turning a race the old code answered 200 into a + /// server error on an ordinary `POST /courses/{id}/enrollments`. + #[tokio::test] + async fn a_vanished_row_is_not_an_internal_error() { + let db = crate::database::init_mem().await.unwrap(); + let class = crate::domain::class_group::ClassGroupId::from_key("9a"); + let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); + // Never written: the same store state a delete in the window leaves. + let ghost = Enrollment { + id: EnrollmentId::composite(&course, &student), + course: course.clone(), + user: student.clone(), + enrolled_by: UserId::from_key("mgr"), + source: Some(class), + }; + + let answered = Enrollment::disown_if_pumped(ghost, &db).await.unwrap(); + assert_eq!(answered.get_user(), &student); + assert_eq!(answered.get_course(), &course); + } + /// And the other half of "absence is the meaning": a hand-placed enrollment /// must store *no* source key, or a class sweep would take back a row it /// never wrote. Asserted on the stored row, not the returned one. diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 177fd40..c8ce2fa 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -641,14 +641,16 @@ impl ExamQuestion { pub async fn delete(self, db: &Database) -> Result { let mut result = ExamAttempt::write_unfrozen( &self.exam, - "DELETE exam_answer WHERE question = $q; - DELETE question_image WHERE question = $q; - LET $gone = (DELETE $q RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) { - UPDATE $sub SET exam_question_count = - math::max([(exam_question_count ?? 0) - 1, 0]) - }; - RETURN $gone;", + &format!( + "DELETE exam_answer WHERE question = $q; + DELETE question_image WHERE question = $q; + LET $gone = (DELETE $q RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) {{ + UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} = + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone;" + ), vec![("q".into(), self.id.record().into_value())], db, ) diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index f464819..595e91b 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -221,6 +221,15 @@ impl FieldUpdate { let cas = moved .as_ref() .map(|(_, link, ..)| format!("{link} = $ref_expected")); + // The caller's own guards, kept apart from the CAS: the split below has + // to ask "did *only* the link move?", and a probe that ignores them + // answers "the link moved" to a write its `.guard()` refused outright. + let own = ordered + .iter() + .chain(extra.iter()) + .cloned() + .collect::>() + .join(" AND "); let conditions: Vec = ordered.into_iter().chain(extra).chain(cas).collect(); let guard = if conditions.is_empty() { String::new() @@ -234,7 +243,7 @@ impl FieldUpdate { // its guard reads, and the loser wrote nothing, so re-sending it is the // recovery — see [`write_with_retry`]. let rows: Vec = match moved { - Some(moved) => run_with_refcount(db, &sql, self.bindings, moved).await?, + Some(moved) => run_with_refcount(db, &sql, &own, self.bindings, moved).await?, None => write_with_retry(db, &sql, &self.bindings).await?, }; // No row back means the guard bit (or, in the window after the handler's @@ -265,6 +274,7 @@ impl FieldUpdate { async fn run_with_refcount( db: &Database, update: &str, + own_guards: &str, mut bindings: Vec<(String, Value)>, (field, link, expected, claim, release, refused): Refcount, ) -> Result, AppError> { @@ -295,13 +305,22 @@ async fn run_with_refcount( // Without this the claim would outlive a row write that matched nothing — // the very leak the transaction exists to close. Nothing was written yet // either way, so the probe that tells the two empty cases apart is free to - // be another `UPDATE`: it matches only a row that is *there* and whose link - // has moved off what the handler read, which is the CAS having bitten. A - // deleted row and a plain guard refusal both miss it and keep the answer - // they have always got. + // be another `UPDATE`: it matches only a row that is *there*, whose *own* + // guards still hold, and whose link has moved off what the handler read — + // which is the CAS, and nothing else, having bitten. A deleted row and a + // plain guard refusal both miss it and keep the answer they have always + // got. Carrying the caller's guards is what keeps that true when a write is + // refused for *both* reasons at once: a `.guard()`/`.ordered()` refusal is + // the caller's own answer to give, and reporting it as "the link moved" + // would send the client to re-read a link that was never its problem. + let still_mine = if own_guards.is_empty() { + String::new() + } else { + format!("({own_guards}) AND ") + }; statements.push(format!( "IF array::len($row) = 0 {{ \ - LET $live = (UPDATE $id WHERE {link} != $ref_expected RETURN VALUE id); \ + LET $live = (UPDATE $id WHERE {still_mine}{link} != $ref_expected RETURN VALUE id); \ IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}" )); statements.push("RETURN $row".into()); @@ -343,3 +362,131 @@ async fn run_with_refcount( // removes errored slots, which would renumber the rest. Ok(result.take::>(slot)?) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; + use crate::database::init_mem; + + /// Two subjects and one homework tagged with the first. The `course` and + /// `created_by` links point at rows that do not exist — a `record<…>` type + /// constrains the table, not the existence, and nothing here reads them. + async fn seeded() -> Database { + let db = init_mem().await.unwrap(); + db.query( + "CREATE subject:s1 SET course = course:c, name = 'a', description = ''; + CREATE subject:s2 SET course = course:c, name = 'b', description = ''; + CREATE homework:h1 SET course = course:c, subject = subject:s1, + title = 't', due_at = 1, created_by = user:u, created_at = 1;", + ) + .await + .unwrap() + .check() + .unwrap(); + db + } + + /// The two subjects' homework counters, re-read out of the store. + async fn counts(db: &Database) -> Vec { + let mut result = db + .query(format!( + "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM subject ORDER BY id" + )) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() + } + + fn homework() -> RecordId { + RecordId::new("homework", "h1") + } + + fn subject(key: &str) -> RecordId { + RecordId::new("subject", key) + } + + /// A write refused by the caller's *own* guard must answer with the + /// caller's own refusal, even when the link it carries has also moved since + /// the handler read it. Both are true; only one is the client's problem, + /// and "re-read the link and retry" sends them chasing a `409` that a retry + /// cannot clear — the guard will refuse the next attempt exactly the same. + #[tokio::test] + async fn a_guard_refusal_outranks_a_link_that_also_moved() { + let db = seeded().await; + let refused = FieldUpdate::new(homework()) + .set("subject", Some(subject("s2"))) + .guard("title = 'never'", AppError::Conflict("the caller's own no")) + .refcount( + SUBJECT_HOMEWORK_COUNT_FIELD, + "subject", + // Stale: the row says `s1`, so the CAS bites too. + Some(subject("s9")), + Some(subject("s2")), + Some(subject("s9")), + AppError::Conflict("the subject is gone"), + ) + .run::(&db) + .await + .unwrap_err(); + assert_eq!(refused.to_string(), "conflict: the caller's own no"); + // The abort took the claim with it, and the link never moved. + assert_eq!(counts(&db).await, vec![0, 0]); + } + + /// ...and with the guard satisfied, a moved link is still reported as a + /// moved link — the answer every current caller relies on. + #[tokio::test] + async fn a_moved_link_alone_is_still_the_stale_move_409() { + let db = seeded().await; + let refused = FieldUpdate::new(homework()) + .set("subject", Some(subject("s2"))) + .guard("title = 't'", AppError::Conflict("the caller's own no")) + .refcount( + SUBJECT_HOMEWORK_COUNT_FIELD, + "subject", + Some(subject("s9")), + Some(subject("s2")), + Some(subject("s9")), + AppError::Conflict("the subject is gone"), + ) + .run::(&db) + .await + .unwrap_err(); + assert!( + refused + .to_string() + .contains("the link this update moves changed"), + "{refused}" + ); + assert_eq!(counts(&db).await, vec![0, 0]); + } + + /// The unguarded shape every production caller uses today: the link moves, + /// the counters move with it, in one transaction. + #[tokio::test] + async fn an_unguarded_move_still_lands_with_both_counters() { + let db = seeded().await; + db.query("UPDATE subject:s1 SET homework_count = 1") + .await + .unwrap() + .check() + .unwrap(); + FieldUpdate::new(homework()) + .set("subject", Some(subject("s2"))) + .refcount( + SUBJECT_HOMEWORK_COUNT_FIELD, + "subject", + Some(subject("s1")), + Some(subject("s2")), + Some(subject("s1")), + AppError::Conflict("the subject is gone"), + ) + .run::(&db) + .await + .unwrap(); + assert_eq!(counts(&db).await, vec![0, 1]); + } +} diff --git a/src/domain/homework.rs b/src/domain/homework.rs index c78b8e1..6472563 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -348,16 +348,19 @@ impl Homework { pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( - "BEGIN TRANSACTION; - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); - DELETE homework_submission WHERE homework = $hw; - DELETE homework_result WHERE homework = $hw; - LET $gone = (DELETE $hw RETURN BEFORE); - FOR $sub IN ($gone.subject ?? []) { - UPDATE $sub SET homework_count = math::max([(homework_count ?? 0) - 1, 0]) - }; - RETURN $gone; - COMMIT TRANSACTION;", + format!( + "BEGIN TRANSACTION; + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); + DELETE homework_submission WHERE homework = $hw; + DELETE homework_result WHERE homework = $hw; + LET $gone = (DELETE $hw RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) {{ + UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = + math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), ) .bind(("hw", self.id.record())) .await? diff --git a/src/domain/meal_attendance.rs b/src/domain/meal_attendance.rs index 75f4bbc..b8c90b8 100644 --- a/src/domain/meal_attendance.rs +++ b/src/domain/meal_attendance.rs @@ -110,13 +110,22 @@ impl MealAttendance { /// Record (or overwrite) whether `student` ate off `menu`. One row per /// pair by construction, so a correction is the same UPSERT flipping the /// status. No ledger line, ever — see the module header. + /// + /// `None` = the menu is gone, and the mark was *not* written. The menu's + /// existence is the `UPSERT`'s own target rather than a read the write then + /// trusts: the id list comes out of a `SELECT` over the menu row, so a menu + /// deleted a moment ago yields no target and the statement writes nothing. + /// An unconditional upsert landing just after `DELETE /meals/menus/{id}` + /// committed left a mark its cascade had already swept — and since + /// [`MenuId::for_slot`] is deterministic, republishing that day and slot + /// resurrected it as a mark on the new menu. pub async fn mark( menu: &MenuId, student: &UserId, status: MealAttendanceStatus, marked_by: &UserId, db: &Database, - ) -> Result { + ) -> Result, AppError> { let row = MealAttendance { id: MealAttendanceId::composite(menu, student), menu: menu.clone(), @@ -125,8 +134,14 @@ impl MealAttendance { marked_by: marked_by.clone(), marked_at: Timestamp::now(), }; - let saved: Option = db.upsert(row.id.record()).content(row).await?; - saved.ok_or_else(|| AppError::Internal("failed to mark meal attendance".into())) + let mut result = db + .query("UPSERT (SELECT VALUE $id FROM $menu) CONTENT $row RETURN AFTER") + .bind(("id", row.id.record())) + .bind(("menu", menu.record())) + .bind(("row", row)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) } /// The kitchen's list for one menu. diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index 4825039..24c3299 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -23,7 +23,10 @@ //! price its menu genuinely carried. //! - **The seat and its money move together.** Booking charges and cancelling //! reverses right here, not in the web layer — a seam between the two let -//! concurrent `POST`s bill one seat twice. +//! concurrent `POST`s bill one seat twice — and *both* ledger lines are +//! written by the very transaction that moves the seat, because money that +//! trails the seat by one write can be overtaken by the next attempt and +//! stranded forever: every ledger id carries the attempt it belongs to. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; @@ -162,10 +165,10 @@ impl MealBooking { /// instant the seat was taken — a guarantee a lock around the read could /// not give, since the price is read a round trip before the claim. /// - /// The charge is appended after, keyed by (seat, attempt): eight concurrent - /// `POST`s of one seat hold one seat and write one charge line. The price is - /// `None` when the menu is free, and that `None` is stored, so a dish added - /// later never bills a seat retroactively. + /// The charge rides that same transaction, keyed by (seat, attempt): eight + /// concurrent `POST`s of one seat hold one seat and write one charge line. + /// The price is `None` when the menu is free, and that `None` is stored, so + /// a dish added later never bills a seat retroactively. /// /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once /// serving time is that close, the seat is fixed either way. @@ -181,14 +184,17 @@ impl MealBooking { for _ in 0..CAS_UPDATE_RETRIES { let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; - // Before the seat: an unchargeable menu (dishes summing past the - // cap) must refuse the booking outright, never leave a - // booked-but-unbilled row behind. - let price = MealLedger::price_snapshot(menu, db).await?; let existing: Option = db.select(id.record()).await?; // The seat is already held: same attempt, same price it was taken // at. Today's menu price bills nobody who booked yesterday's. No // seat is claimed, so a double-click cannot count two. + // + // Answered *before* the menu is priced, and that ordering is the + // rule: pricing first made a repeat POST of a seat already held 400 + // ("amount_minor must be between…") as soon as the menu's dishes + // summed past the chargeable maximum — refusing to replay a seat + // the student holds, over a price that seat was never going to be + // billed. if let Some(held) = existing .clone() .filter(|row| row.status == MealBookingStatus::Booked) @@ -196,32 +202,47 @@ impl MealBooking { MealLedger::charge_booking(&held, booked_by, db).await?; return Ok(held); } + // Before the seat: an unchargeable menu (dishes summing past the + // cap) must refuse the booking outright, never leave a + // booked-but-unbilled row behind. + let price = MealLedger::price_snapshot(menu, db).await?; + // The attempt is settled *here*, not by the revival's `attempt + 1`, + // because the charge id is (seat, attempt) and the charge has to be + // built before the transaction that writes it. `existing` is either + // absent or cancelled — a booked row returned above. let fresh_row = MealBooking { id: id.clone(), menu: menu.clone(), student: student.clone(), booked_by: booked_by.clone(), status: MealBookingStatus::Booked, - attempt: 1, + attempt: existing.map_or(1, |prior| prior.attempt + 1), price_minor: price, cancelled_at: None, created_at: Timestamp::now(), }; - let booking = match Self::claim_and_place( + let charge = MealLedger::charge_for(&fresh_row, booked_by); + match Self::claim_and_place( &seats, fresh.get_capacity().unwrap_or(cap::UNLIMITED), fresh.get_version(), &fresh_row, price, + charge.as_ref(), db, ) .await? { - Claimed::Made(booking) => booking, - // Another `POST` of this very pair placed the row first, and it - // owed no second seat: this caller never took one (the whole - // transaction rolled back), so the winner's row is the answer. - Claimed::Duplicate => Self::read(&id, db).await?.ok_or(AppError::NotFound)?, + // Seat, row and charge committed together; nothing is owed + // after this call, which is the whole point of folding them. + Claimed::Made(booking) => return Ok(booking), + // Another `POST` of this very pair moved the row first, and this + // caller never took a seat (the whole transaction rolled back). + // The decision is simply made again rather than answered off a + // row read here: the winner may have left it `cancelled` at an + // attempt this call never saw, and the loop's own held-seat path + // is what returns a live seat *and* replays its charge. + Claimed::Duplicate => continue, // Full, moved, or gone — one `WHERE` refused all three, so the // reason is re-read rather than guessed. A moved menu is not a // refusal: the price above is stale, so price and seat are @@ -231,11 +252,7 @@ impl MealBooking { Some(now) if now.get_version() != fresh.get_version() => continue, Some(_) => return Err(AppError::Conflict("the menu is fully booked")), }, - }; - // Writes nothing when this attempt is already billed, so the repeat - // POST above costs nothing and a charge that failed once self-heals. - MealLedger::charge_booking(&booking, booked_by, db).await?; - return Ok(booking); + } } Err(AppError::Conflict( "the menu kept changing underneath this booking", @@ -258,14 +275,42 @@ impl MealBooking { /// A cancelled row is revived in place (a fresh attempt at `price`) rather /// than recreated: `booked_by` and `created_at` are READONLY history — who /// opened the seat, and when. + /// + /// **The charge rides this transaction too**, for the same reason the + /// refund rides the cancel's: appended a write later, a cancel landing in + /// the gap finds no charge, reverses nothing, and the charge lands after it + /// — the seat given back and the money still owed, unreversible by any + /// route, because every ledger id carries the attempt the cancel has already + /// moved past. That is why `row.attempt` is minted by the *caller*: the + /// charge's id is (seat, attempt), so the number cannot be the revival's own + /// `attempt + 1` any more. The revival is fenced on the attempt it read + /// instead, so a rival that revived first loses this claim (the `CREATE` + /// below then finds the row and aborts the whole transaction) rather than + /// billing its attempt at this call's id. + /// + /// The charge is created only if it is not already there — a duplicate + /// `CREATE` would abort the transaction and cost the seat, and an attempt + /// billed twice is the one thing money code may never do. async fn claim_and_place( seats: &RecordId, cap: i64, seen: i64, row: &MealBooking, price: Option, + charge: Option<&MealLedger>, db: &Database, ) -> Result, AppError> { + // Empty when the menu is free: a seat that costs nothing owes no line. + let bill = match charge { + Some(_) => { + "IF array::len((SELECT VALUE id FROM $charge)) = 0 \ + { CREATE $charge CONTENT $line };" + } + None => "", + }; + // Slots count BEGIN, three LETs, three IFs and — when there is money to + // take — the charge's IF, so the RETURN is slot 7 or 8. + let returned = if charge.is_some() { 8 } else { 7 }; // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way. let sql = format!( "BEGIN TRANSACTION; @@ -276,24 +321,31 @@ impl MealBooking { WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \ AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id); IF array::len($seat) = 0 {{ THROW 'no_seat' }}; - LET $revived = (UPDATE $id SET status = 'booked', attempt = attempt + 1, \ + LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \ price_minor = $price, cancelled_at = NONE \ - WHERE status = 'cancelled' RETURN AFTER); + WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER); IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }}; + {bill} RETURN SELECT * FROM ONLY $id; COMMIT TRANSACTION;" ); for _ in 0..CAS_UPDATE_RETRIES { - let mut result = match db + let query = db .query(sql.as_str()) .bind(("menu", seats.clone())) .bind(("cap", cap)) .bind(("seen", seen)) .bind(("id", row.id.record())) + .bind(("attempt", row.attempt)) .bind(("price", price)) - .bind(("row", row.clone())) - .await - { + .bind(("row", row.clone())); + let query = match charge { + Some(line) => query + .bind(("charge", line.get_id().record())) + .bind(("line", line.clone())), + None => query, + }; + let mut result = match query.await { Ok(result) => result, Err(err) if lost_the_race(&err) => continue, Err(err) => return Err(err.into()), @@ -319,8 +371,7 @@ impl MealBooking { if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } - // Slots count BEGIN, three LETs and three IFs: the RETURN is slot 7. - return match result.take::>(7)? { + return match result.take::>(returned)? { Some(placed) => Ok(Claimed::Made(placed)), None => Err(AppError::Internal("failed to book the meal".into())), }; @@ -338,16 +389,19 @@ impl MealBooking { /// cancelling a stale attempt would strand that attempt's charge forever. /// The reversal is keyed to the attempt, so a retried cancel refunds once. /// - /// **Idempotent, and that is what makes the refund recoverable.** The flip - /// and the reversal are two writes; a handler future dropped between them - /// (the client closed the tab, a proxy timed out) or a `create` that errors - /// leaves the seat free and the charge standing. Refusing an - /// already-cancelled row — as this used to — made that state permanent: - /// no route on the API could ever append the missing reversal. So a - /// cancelled row replays the reversal instead, which either heals the gap - /// or writes nothing at all. The cutoff is not re-checked on that path: the - /// seat is already given back, and refusing to finish the refund because - /// the meal has since closed would strand the money exactly as before. + /// **The refund is not a second write.** It is appended by the very + /// transaction that flips the row (see [`Self::release_seat`]), so a + /// handler future dropped mid-cancel, a proxy timing out or the store going + /// away cannot leave the seat free with the charge standing — the state a + /// re-book then made permanent, since every ledger id carries the attempt + /// the re-book has already moved past. + /// + /// **Idempotent all the same**, which is what heals a seat flipped before + /// that was true: a cancelled row replays the reversal instead of being + /// refused, and that either completes an old missing line or writes nothing + /// at all. The cutoff is not re-checked on that path: the seat is already + /// given back, and refusing to finish the refund because the meal has since + /// closed would strand the money exactly as before. pub async fn cancel( self, cutoff: &MealCutoff, @@ -363,16 +417,38 @@ impl MealBooking { .await? .ok_or(AppError::NotFound)?; check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; - // Lost the flip to a concurrent cancel: its row is the truth, and the - // reversal replay below heals whatever it left unfinished. - let saved = match Self::release_seat(&fresh, db).await? { + // Lost the flip: another cancel took the seat back first. Its row is + // the truth — but only the attempt *this* call was cancelling may be + // refunded off it (see [`Self::refundable_after_lost_flip`]). + let saved = match Self::release_seat(&fresh, recorded_by, db).await? { Some(cancelled) => cancelled, - None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?, + None => { + let live = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?; + if !Self::refundable_after_lost_flip(&fresh, &live) { + return Ok(live); + } + live + } }; MealLedger::reverse_booking(&saved, recorded_by, db).await?; Ok(saved) } + /// May a cancel that released *nothing* still refund what it read? + /// + /// Only when the row it finds is the very attempt it was cancelling, still + /// cancelled. A cancel is two writes, and between them the seat can be + /// re-booked: the row then reads `booked` at attempt N+1 with a live charge + /// against it, and reversing that — as re-reading and refunding blindly did + /// — refunds a seat that is still held *and* still counted, and burns the + /// `(booking, attempt)` ledger id that attempt's own cancel needs, so it + /// could never be refunded afterwards. A row at another attempt is the same + /// story one step further on: whoever cancelled attempt N appended its + /// reversal, and this call has nothing left to heal. + fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> bool { + live.status == MealBookingStatus::Cancelled && live.attempt == seen.attempt + } + /// Flip the seat to `cancelled` and give it back to the menu's counter **in /// one transaction**, so the two can never disagree: a decrement that ran /// without the flip frees a seat still held, and a flip without the @@ -380,32 +456,69 @@ impl MealBooking { /// flip's own result (`array::len`), so a row already cancelled — by a /// racing cancel, or by this call retried — decrements nothing. /// + /// **The refund rides this transaction too**, and it has to: the flip and a + /// reversal appended after it are two writes, and a crash in between leaves + /// the seat free with the charge standing — after which a re-book moves the + /// row to attempt N+1 and *no* route can ever write the `(booking, N)` + /// reversal, because the money is keyed to the attempt. Folded in here the + /// seat cannot come back without the money, the same way the counter cannot + /// move without the flip. The reversal is written only when the charge it + /// undoes is really there (checked in the transaction, so no round trip can + /// invalidate it): a refund with no charge behind it invents money. + /// + /// The book side is folded the same way ([`Self::claim_and_place`]), so + /// there is no half-second anywhere in which a seat is held with no charge + /// against it, or a charge stands with no seat behind it. + /// /// `None` = the row was not `booked` any more. Retried while the store /// reports a write conflict: the menu row is contended by every booking on /// it, and that contention is the cap working, not an error. async fn release_seat( booked: &MealBooking, + recorded_by: &UserId, db: &Database, ) -> Result, AppError> { + let refund = MealLedger::reversal_for(booked, recorded_by); + // Guarded three ways: nothing was flipped (a rival cancelled first, and + // its own transaction carried the refund), the charge never landed, or + // this attempt is already refunded — none of which may abort the flip. + let reverse = match refund { + Some(_) => { + "IF array::len($flipped) > 0 \ + AND array::len((SELECT VALUE id FROM $charge)) > 0 \ + AND array::len((SELECT VALUE id FROM $reversal)) = 0 \ + { CREATE $reversal CONTENT $line };" + } + None => "", + }; + // Slots count BEGIN, the LET, the seat UPDATE and — when there is money + // to give back — the IF. + let returned = if refund.is_some() { 4 } else { 3 }; for _ in 0..CAS_UPDATE_RETRIES { let attempted = async { - let mut result = db + let query = db .query(format!( "BEGIN TRANSACTION; LET $flipped = (UPDATE $id SET status = 'cancelled', \ cancelled_at = $now WHERE status = 'booked' RETURN AFTER); UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\ ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]); + {reverse} RETURN $flipped; COMMIT TRANSACTION;" )) .bind(("id", booked.id.record())) .bind(("menu", booked.menu.record())) - .bind(("now", Timestamp::now())) - .await? - .check()?; - // Slots count BEGIN and the LET: the RETURN is slot 3. - result.take::>(3) + .bind(("now", Timestamp::now())); + let query = match &refund { + Some((charge, line)) => query + .bind(("charge", charge.record())) + .bind(("reversal", line.get_id().record())) + .bind(("line", line.clone())), + None => query, + }; + let mut result = query.await?.check()?; + result.take::>(returned) } .await; match attempted { @@ -687,9 +800,17 @@ mod tests { created_at: Timestamp::now(), }; let place = async |seen| { - MealBooking::claim_and_place(&menu.record(), cap::UNLIMITED, seen, &row, None, &db) - .await - .unwrap() + MealBooking::claim_and_place( + &menu.record(), + cap::UNLIMITED, + seen, + &row, + None, + None, + &db, + ) + .await + .unwrap() }; assert!( matches!(place(seen).await, Claimed::Full), @@ -795,6 +916,162 @@ mod tests { ); } + /// A cancel that lost its flip may only refund the attempt it was actually + /// cancelling. Driven against the predicate rather than through `cancel`: + /// the row is re-read *inside* the call, so the only way it can disagree + /// with what the flip found is a genuine concurrent write, which no + /// single-process interleaving (and no in-memory engine) can stage. + #[tokio::test] + async fn a_lost_flip_refunds_only_the_attempt_it_released() { + let (db, menu) = menu(None).await; + let (ali, veli) = (UserId::generate(), UserId::generate()); + let open = MealCutoff::default(); + add_dish(&menu, 1_000, &db).await; + + let seen = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + let cancelled = seen.clone().cancel(&open, &ali, &db).await.unwrap(); + // The seat this cancel released: its own attempt, still cancelled. + assert!(MealBooking::refundable_after_lost_flip(&seen, &cancelled)); + + // A re-book landed in the window. The row is `booked` again with a live + // charge against it — refunding that frees money for a seat that is + // still held, and burns the ledger id its own cancel will need. + let rebooked = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!(rebooked.get_attempt(), seen.get_attempt() + 1); + assert!(!MealBooking::refundable_after_lost_flip(&seen, &rebooked)); + + // Re-booked *and* cancelled again: that cancel appended the reversal + // for its own attempt, and this call has nothing left to heal. + let later = rebooked.cancel(&open, &ali, &db).await.unwrap(); + assert!(!MealBooking::refundable_after_lost_flip(&seen, &later)); + + // And the ordinary lost race — another cancel of the same attempt got + // there first — still replays the refund, which is what heals a cancel + // cut short between the flip and the ledger line. + let other = MealBooking::book(&menu, &veli, &veli, &open, &db) + .await + .unwrap(); + let freed = other.clone().cancel(&open, &veli, &db).await.unwrap(); + assert!(MealBooking::refundable_after_lost_flip(&other, &freed)); + } + + /// The seat may not come back without the money. Driven against + /// [`MealBooking::release_seat`] rather than through `cancel`, because what + /// is under test is precisely what a *crash right after the flip* leaves + /// behind: appended a write later, the reversal is lost with the process, + /// and a re-book then moves the row to the next attempt and locks the + /// `(booking, attempt)` reversal id out for good — the charge is + /// unreversible by any route on the API. + #[tokio::test] + async fn the_seat_cannot_be_freed_without_its_refund() { + let (db, menu) = menu(None).await; + let ali = UserId::generate(); + let open = MealCutoff::default(); + add_dish(&menu, 1_000, &db).await; + let booked = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + + // The flip alone — nothing else runs afterwards, as after a crash. + let freed = MealBooking::release_seat(&booked, &ali, &db) + .await + .unwrap() + .expect("the seat was held, so the flip must take it back"); + assert_eq!(freed.get_status(), MealBookingStatus::Cancelled); + assert_eq!(seats(&menu, &db).await, 0); + assert_eq!( + MealLedger::balance_of(&ali, &db).await.unwrap(), + 0, + "the reversal must have committed with the flip, not after it" + ); + + // And the re-book that used to strand the charge now finds it settled: + // a fresh attempt, billed once more, with the old one squared away. + MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); + } + + /// The seat may not be held without its money. Driven against + /// [`MealBooking::claim_and_place`] rather than through `book`, because what + /// is under test is precisely what the gap between the two writes leaves + /// behind: a cancel landing there finds no charge to reverse, reverses + /// nothing, and the charge then lands anyway — a student holding no seat and + /// owing money, with the `(booking, attempt)` reversal id burnt for good. + #[tokio::test] + async fn the_seat_cannot_be_claimed_without_its_charge() { + let (db, menu) = menu(None).await; + let ali = UserId::generate(); + add_dish(&menu, 1_000, &db).await; + let price = MealLedger::price_snapshot(&menu, &db).await.unwrap(); + let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + let row = MealBooking { + id: MealBookingId::composite(&menu, &ali), + menu: menu.clone(), + student: ali.clone(), + booked_by: ali.clone(), + status: MealBookingStatus::Booked, + attempt: 1, + price_minor: price, + cancelled_at: None, + created_at: Timestamp::now(), + }; + let charge = MealLedger::charge_for(&row, &ali); + // The claim alone — nothing else runs afterwards, as after a crash. + let place = async || { + MealBooking::claim_and_place( + &menu.record(), + cap::UNLIMITED, + seen, + &row, + price, + charge.as_ref(), + &db, + ) + .await + .unwrap() + }; + assert!(matches!(place().await, Claimed::Made(_))); + assert_eq!(seats(&menu, &db).await, 1); + assert_eq!( + MealLedger::balance_of(&ali, &db).await.unwrap(), + -1_000, + "the charge must have committed with the claim, not after it" + ); + + // Replayed: the seat is already held, so the whole transaction rolls + // back — no second seat and, just as importantly, no second charge. + assert!(matches!(place().await, Claimed::Duplicate)); + assert_eq!(seats(&menu, &db).await, 1); + assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000); + } + + /// A free menu owes no refund, so the flip must carry no ledger line at all + /// — the branch the reversal's conditional statement adds. + #[tokio::test] + async fn a_seat_that_was_never_billed_frees_without_a_line() { + let (db, menu) = menu(None).await; + let ali = UserId::generate(); + let booked = MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db) + .await + .unwrap(); + + MealBooking::release_seat(&booked, &ali, &db) + .await + .unwrap() + .expect("a free seat is still a seat"); + assert_eq!(seats(&menu, &db).await, 0); + let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db) + .await + .unwrap(); + assert!(lines.is_empty() && total == 0, "a free seat moves no money"); + } + fn cutoff(minutes: Option, serving_minute: Option) -> MealCutoff { MealCutoff { minutes, diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index 77bc0d0..1f6e75d 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -26,8 +26,12 @@ //! seat taken while the menu was free stays free, because "free" is recorded //! on the row rather than inferred from the absence of a charge. //! - **A cancel appends a `reversal`**, for the charge's exact amount, with -//! `source` pointing at the charge it undoes. The charge row stays. Booking -//! again after a cancel is a *fresh* charge at the then-current price. +//! `source` pointing at the charge it undoes, *in the same transaction as the +//! flip that frees the seat*. The charge row stays. Booking again after a +//! cancel is a *fresh* charge at the then-current price — and since every +//! line is keyed by the attempt, a reversal that landed a transaction later +//! than its flip could be overtaken by that re-book and then never be +//! writable at all. //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge //! and its reversal derive their record id from the seat and the attempt //! number, so replaying either writes nothing at all. Money must never @@ -348,31 +352,40 @@ impl MealLedger { recorded_by: &UserId, db: &Database, ) -> Result<(), AppError> { - let Some(amount) = booking.get_price_minor() else { + let Some(line) = Self::charge_for(booking, recorded_by) else { return Ok(()); }; - Self::append( - MealLedger { - id: MealLedgerId::for_attempt( - booking.get_id(), - booking.get_attempt(), - MealLedgerKind::Charge, - ), - student: booking.get_student().clone(), - kind: MealLedgerKind::Charge, - amount_minor: amount, - source: Some(booking.get_id().record()), - method: None, - note: None, - recorded_by: recorded_by.clone(), - created_at: Timestamp::now(), - }, - db, - ) - .await?; + Self::append(line, db).await?; Ok(()) } + /// The charge `booking`'s current attempt owes — the line + /// [`MealBooking::claim_and_place`] appends inside the very transaction that + /// takes the seat. `None` when the menu was free, which owes no line. + /// + /// Only the row is built here; whether it is already there is a read, and + /// the caller that writes in one transaction has to make it there. Note the + /// attempt has to be settled *before* the SQL runs, which is why the claim + /// mints the number itself rather than letting the revival increment it. + pub(crate) fn charge_for(booking: &MealBooking, recorded_by: &UserId) -> Option { + let amount = booking.get_price_minor()?; + Some(MealLedger { + id: MealLedgerId::for_attempt( + booking.get_id(), + booking.get_attempt(), + MealLedgerKind::Charge, + ), + student: booking.get_student().clone(), + kind: MealLedgerKind::Charge, + amount_minor: amount, + source: Some(booking.get_id().record()), + method: None, + note: None, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }) + } + /// Give the money back for a cancelled `booking`: a new `reversal` line for /// the charge's exact amount, pointing at it. The charge is never touched. /// A booking that was never billed (a free menu) reverses nothing, and @@ -380,46 +393,60 @@ impl MealLedger { /// the very charge it undoes, so it can only exist alongside it. /// /// Keyed by `(booking, attempt)` like the charge, so a retried cancel - /// refunds once. A cancel cut short between the status flip and this - /// reversal is recovered by repeating the cancel — which is precisely why - /// [`MealBooking::cancel`] replays this on an already-cancelled row instead + /// refunds once. The line normally lands *inside* the flip's own + /// transaction ([`MealBooking::release_seat`]); this path is what heals a + /// seat flipped before that was true, and it is why + /// [`MealBooking::cancel`] replays it on an already-cancelled row instead /// of refusing it. Nothing else on the API can append the missing line. pub async fn reverse_booking( booking: &MealBooking, recorded_by: &UserId, db: &Database, ) -> Result<(), AppError> { - let Some(amount) = booking.get_price_minor() else { + let Some((charge, line)) = Self::reversal_for(booking, recorded_by) else { return Ok(()); }; + if Self::read(&charge, db).await?.is_none() { + return Ok(()); + } + Self::append(line, db).await?; + Ok(()) + } + + /// The refund `booking`'s current attempt owes, as `(the charge it undoes, + /// the reversal line)` — the two ids [`MealBooking::release_seat`] needs to + /// append the money back inside the transaction that frees the seat. + /// `None` when the seat was never billed (a free menu), which owes no line. + /// + /// Only the ids and the row are built here: whether the charge exists is a + /// read, and the caller that writes in one transaction has to make it there + /// rather than a round trip earlier. + pub(crate) fn reversal_for( + booking: &MealBooking, + recorded_by: &UserId, + ) -> Option<(MealLedgerId, MealLedger)> { + let amount = booking.get_price_minor()?; let charge = MealLedgerId::for_attempt( booking.get_id(), booking.get_attempt(), MealLedgerKind::Charge, ); - if Self::read(&charge, db).await?.is_none() { - return Ok(()); - } - Self::append( - MealLedger { - id: MealLedgerId::for_attempt( - booking.get_id(), - booking.get_attempt(), - MealLedgerKind::Reversal, - ), - student: booking.get_student().clone(), - kind: MealLedgerKind::Reversal, - amount_minor: amount, - source: Some(charge.record()), - method: None, - note: None, - recorded_by: recorded_by.clone(), - created_at: Timestamp::now(), - }, - db, - ) - .await?; - Ok(()) + let line = MealLedger { + id: MealLedgerId::for_attempt( + booking.get_id(), + booking.get_attempt(), + MealLedgerKind::Reversal, + ), + student: booking.get_student().clone(), + kind: MealLedgerKind::Reversal, + amount_minor: amount, + source: Some(charge.record()), + method: None, + note: None, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }; + Some((charge, line)) } /// Money in: a payment received, or an opening balance. diff --git a/src/domain/menu.rs b/src/domain/menu.rs index f63691a..5cc3842 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -14,13 +14,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use crate::constant::{ - MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, REF_COUNT_FIELD, - SLOT_REF_TABLE, + MAX_MENU_CAPACITY, MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_TABLE, + MENU_VERSION_FIELD, REF_COUNT_FIELD, SLOT_REF_TABLE, }; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, transaction_with_retry, write_with_retry}; use crate::domain::cap; -use crate::domain::field_update::FieldUpdate; -use crate::domain::menu_dish::MenuDish; use crate::domain::page::PagedList; use crate::domain::settings::MealSlotDef; use crate::domain::timestamp::Timestamp; @@ -40,7 +38,13 @@ use crate::error::{AppError, ValidationError}; // backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was // not worth the column here. /// -/// A leaf: nothing held under it takes another lock. +/// **A leaf**: every dish write held under it moves the menu's revision inside +/// its *own* transaction ([`MenuDish::bump_menu_and_write`](crate::domain::menu_dish)), +/// so no path under this lock reaches `cap`'s counter lock any more — it did +/// while the bump was a `cap` call of its own. Should one ever need both, the +/// order is `MENU_LOCK` → `CLAIM_LOCK` and nothing may take this lock while +/// holding a counter lock: that is the invariant a new caller must keep, and it +/// is what would keep the pair deadlock-free. pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); /// The reference counter for one meal slot — how many menus are published under @@ -138,6 +142,22 @@ impl MenuSlot { reason: "not one of the school's meal slots (see GET /settings)", }); } + // The slot goes verbatim into the menu's record id ([`MenuId::for_slot`]), + // and that id is a URL path segment: a slot named `a/b` publishes a menu + // at `/meals/menus/2026-09-14_a/b`, which no route can ever address + // again — the menu could not be read, edited or deleted. + // `MealSlotDef::try_new` refuses the same characters, so no school can + // define such a slot; this is the second gate, and it is what a + // settings row written before that rule runs into. + if value + .chars() + .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) + { + return Err(ValidationError::Invalid { + field: "slot", + reason: "meal slot names used for menus must not contain / \\ ? # or %", + }); + } Ok(Self(value.to_string())) } @@ -297,21 +317,40 @@ impl Menu { /// because moving a published menu to another day is a different menu. /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. /// - /// Moving the cap moves the revision first ([`cap::bump`]): a booking that - /// read the old cap must not claim its seat against it, or a shrink - /// over-admits by exactly the bookings in flight. + /// The revision moves **in the same statement** as the cap, indivisibly: a + /// booking claims its seat against the revision + /// it read the cap at, so a shrink that bumped in a query of its own left a + /// window where the row carried the *new* revision and the *old* cap — and + /// a booking arriving there passes a CAS meant to refuse it, over-admitting + /// by exactly the seats in flight. pub async fn update( self, capacity: Option>, db: &Database, ) -> Result { - if capacity.is_some() { - cap::bump(&self.id.record(), MENU_VERSION_FIELD, db).await?; - } - FieldUpdate::new(self.id.record()) - .set("capacity", capacity) - .run::(db) - .await + let Some(capacity) = capacity else { + // A PATCH carrying nothing writes nothing and bumps nothing: no + // booking's price or cap has moved, so none owes a re-read. + return Self::read(&self.id, db).await?.ok_or(AppError::NotFound); + }; + let sql = format!( + "UPDATE $id SET capacity = $capacity, \ + {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER" + ); + // One counter write in flight at a time, like every other one. + let _guard = cap::counter_lock().await; + write_with_retry::( + db, + &sql, + &[ + ("id".into(), self.id.record().into_value()), + ("capacity".into(), capacity.into_value()), + ], + ) + .await? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Delete the menu and the dishes on it — a dish has no meaning without @@ -330,8 +369,22 @@ impl Menu { /// in a query of its own, a crash between the two left the slot counted by /// a menu that no longer exists: a slot nobody can retire. /// - /// The dishes go *after* the row: their cascade must not run for a delete - /// the counter refused. + /// The marks go in that same `FOR`, for a sharper reason than tidiness: + /// [`MenuId::for_slot`] is deterministic, so republishing the same day and + /// slot mints the *same* record id. A mark left behind would come back as a + /// mark on the new menu — the kitchen reading "served" for a student who + /// never came — and until then the student's own report cites a menu that + /// is gone. Attendance carries no money and no counter, so it is safe to + /// drop; cancelled *bookings* deliberately stay, because their `attempt` + /// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut + /// those and a re-book on a republished menu would reuse a charge id the + /// ledger already holds, and the append (idempotent by design) would bill + /// the seat nothing. + /// + /// The dishes ride in that `FOR` too, and for the same reason as the marks: + /// run after the transaction committed, a crash between the two orphaned + /// them on a record id republishing the day and slot mints again — a new + /// menu serving (and pricing) the old one's food. pub async fn delete(self, db: &Database) -> Result { let sql = format!( "BEGIN TRANSACTION; @@ -339,6 +392,8 @@ impl Menu { FOR $row IN ($gone ?? []) {{ UPSERT $counter SET {REF_COUNT_FIELD} = \ math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); + DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id; + DELETE {MENU_DISH_TABLE} WHERE menu = $id; }}; RETURN $gone; COMMIT TRANSACTION;" @@ -368,7 +423,6 @@ impl Menu { None => AppError::NotFound, }); }; - MenuDish::delete_for_menu(&self.id, db).await?; Ok(deleted) } } @@ -403,6 +457,40 @@ mod tests { assert!(MenuSlot::try_new("lunch", &[]).is_err()); } + /// The slot becomes the menu's record id, and the id becomes a URL path + /// segment: a name carrying a separator publishes a menu at an address no + /// route can match again. `MealSlotDef::try_new` refuses the name too, so + /// no school can define such a slot any more — this gate is what a settings + /// row written *before* that rule still runs into. Ordinary names — spaces + /// and Turkish letters included — are untouched; they percent-encode into + /// one segment as they always have. + #[test] + fn a_slot_name_that_would_break_the_menu_url_is_refused() { + // The only shape that can still carry such a name: a stored slot, + // decoded rather than constructed. + use surrealdb::types::Value; + let stale = |name: &str| { + let Value::Object(mut object) = + MealSlotDef::try_new("lunch", None).unwrap().into_value() + else { + panic!("a slot must encode as an object"); + }; + object.insert("name".to_string(), Value::String(name.into())); + vec![MealSlotDef::from_value(Value::Object(object)).unwrap()] + }; + let named = |name: &str| { + MenuSlot::try_new(name, &stale(name)) + .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot)) + }; + for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] { + assert!(named(broken).is_err(), "{broken} must not become an id"); + } + assert_eq!( + named("öğle yemeği").unwrap().key(), + "2026-09-14_öğle yemeği" + ); + } + #[test] fn capacity_is_bounded_but_optional() { assert!(validate_capacity(None).is_ok()); @@ -541,6 +629,35 @@ mod tests { assert_eq!(refs(&db).await, 0); } + /// The cap and the revision are one write. Nothing single-process can + /// observe the torn state the two-query version left (a bumped revision + /// over a cap that had not moved yet), so what is pinned here is the pair: + /// the revision steps exactly once per cap move, and never for a PATCH that + /// carried no cap at all — a booking re-reads only when something it priced + /// itself against actually changed. + #[tokio::test] + async fn the_cap_and_the_revision_move_together_or_not_at_all() { + let db = school().await; + let menu = publish("2026-08-05", &db).await.unwrap(); + let id = menu.get_id().clone(); + assert_eq!(menu.get_version(), 0); + + let capped = menu.update(Some(Some(5)), &db).await.unwrap(); + assert_eq!(capped.get_capacity(), Some(5)); + assert_eq!(capped.get_version(), 1); + // Re-read out of the store, never off the return value. + let stored = Menu::read(&id, &db).await.unwrap().unwrap(); + assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1)); + + // An empty PATCH moves neither, and reads the row back unchanged. + let same = stored.update(None, &db).await.unwrap(); + assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1)); + + // Clearing the cap is a move like any other. + let uncapped = same.update(Some(None), &db).await.unwrap(); + assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2)); + } + #[tokio::test] async fn deleting_hands_the_reference_back_in_the_same_step() { let db = school().await; diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 6a7ddca..9e4c90a 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -7,7 +7,7 @@ use std::sync::LazyLock; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; use ulid::Generator; use crate::constant::{ @@ -15,8 +15,6 @@ use crate::constant::{ MENU_DISH_TABLE, MENU_VERSION_FIELD, }; use crate::database::{Database, transaction_with_retry}; -use crate::domain::cap; -use crate::domain::field_update::FieldUpdate; use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; @@ -287,21 +285,74 @@ impl MenuDish { Ok(Self::list_for_menu(menu, db).await?.len()) } - /// What a seat on this dish's menu costs changed, so the menu is now at a - /// new revision and any booking that priced itself against the old one has - /// to re-read. Called *before* the write, never after: bumped-and-not-written - /// costs a booking one retry, written-and-not-bumped bills a seat a price - /// the menu no longer carries. + /// Move the menu's revision **and** run `statement`, in one transaction. + /// + /// What a seat on this dish's menu costs is about to change, so any booking + /// that priced itself against the old revision has to re-read. The bump + /// cannot be a query of its own: in the gap the menu row carries the *new* + /// revision with the *old* price, and a booking reading there passes the + /// very CAS that exists to refuse it — a seat billed a price the menu had + /// already left, or admitted past a capacity that had already shrunk. + /// + /// The bump also makes the menu's existence part of the write ([`Self::create`] + /// leans on the same thing): the `UPDATE` matches nothing once the menu row + /// is deleted, and a delete racing this one touches the very key this + /// transaction writes, so the two cannot both commit. /// /// Deliberately on every dish write, not only the ones that move /// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that /// applies to every write cannot be forgotten by the next field added here. - async fn bump_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> { - cap::bump(&menu.record(), MENU_VERSION_FIELD, db).await + /// + /// Admissible for [`transaction_with_retry`]: every statement is an + /// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN`, and none + /// of those can answer "already exists" — a lost round wrote nothing, so + /// re-sending it is the recovery. + async fn bump_menu_and_write( + menu: &MenuId, + statement: &str, + mut bindings: Vec<(String, Value)>, + db: &Database, + ) -> Result, AppError> { + bindings.push(("menu".into(), menu.record().into_value())); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; + LET $row = ({statement}); + RETURN $row; + COMMIT TRANSACTION;" + ), + &bindings, + &["no_menu"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_menu")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. + Ok(result.take::>(4)?.into_iter().next()) } /// Write only the fields the PATCH carried. `description` is nullable, so /// it takes the three-way shape: absent = keep, `Some(None)` = clear. + /// + /// The `SET` is built here rather than by + /// [`FieldUpdate`](crate::domain::field_update::FieldUpdate) because the + /// revision bump lands on *another* row and has to share this write's + /// transaction; the field-by-field scoping — an omitted field is never + /// written, so a concurrent PATCH of another one is not reverted — is the + /// same rule, spelled out. pub async fn update( self, name: Option, @@ -310,29 +361,47 @@ impl MenuDish { tags: Option, db: &Database, ) -> Result { - Self::bump_menu(&self.menu, db).await?; - FieldUpdate::new(self.id.record()) - .set("name", name) - .set("description", description) - .set("price_minor", price_minor) - .set("tags", tags) - .run::(db) - .await + let mut sets: Vec<&str> = Vec::new(); + let mut bindings: Vec<(String, Value)> = vec![("id".into(), self.id.record().into_value())]; + let mut set = |field: &'static str, value: Option| { + if let Some(value) = value { + sets.push(field); + bindings.push((field.into(), value)); + } + }; + set("name", name.map(SurrealValue::into_value)); + set("description", description.map(SurrealValue::into_value)); + set("price_minor", price_minor.map(SurrealValue::into_value)); + set("tags", tags.map(SurrealValue::into_value)); + // A PATCH that carried nothing writes nothing and reads the row back, + // exactly as `FieldUpdate` answers one — but it still moves the + // revision, because "every dish write bumps" is the rule a caller can + // rely on without knowing which fields were on the wire. + let statement = if sets.is_empty() { + "SELECT * FROM $id".to_string() + } else { + format!( + "UPDATE $id SET {} RETURN AFTER", + sets.iter() + .map(|field| format!("{field} = ${field}")) + .collect::>() + .join(", ") + ) + }; + Self::bump_menu_and_write(&self.menu, &statement, bindings, db) + .await? + .ok_or(AppError::NotFound) } pub async fn delete(self, db: &Database) -> Result { - Self::bump_menu(&self.menu, db).await?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) - } - - /// Drop every dish on a menu — the menu delete's cascade. - pub async fn delete_for_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> { - db.query("DELETE menu_dish WHERE menu = $menu") - .bind(("menu", menu.record())) - .await? - .check()?; - Ok(()) + Self::bump_menu_and_write( + &self.menu, + "DELETE $id RETURN BEFORE", + vec![("id".into(), self.id.record().into_value())], + db, + ) + .await? + .ok_or(AppError::NotFound) } } diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 79340ca..ef9b0e3 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -67,9 +67,12 @@ impl Registration { /// cap is set and every seat is taken. Someone already listed gets their /// existing row back untouched — a true no-op that never counts against /// the cap and never rewrites who placed them. The seat is taken by - /// [`cap::claim`] on the event row — an atomic single-record conditional - /// write, so neither a racing registration nor a concurrent - /// capacity/audience/schedule PATCH can over-admit. + /// [`cap::claim_live_and_create`] on the event row — an atomic single-record + /// conditional write that reads `audience.capacity` off that same row as it + /// decides, so neither a racing registration nor a concurrent PATCH + /// *lowering* the capacity can over-admit. Bound as a number instead, the + /// snapshot below would admit every request already in flight when the + /// lower cap landed. pub async fn register( event: &EventId, user: &UserId, @@ -79,7 +82,9 @@ impl Registration { if let Some(existing) = Self::read_for_user(event, user, db).await? { return Ok(existing); } - let capacity = Event::read(event, db) + // Read for its refusals only — the audience kind and the closing time. + // The seat count itself is re-read by the claim. + Event::read(event, db) .await? .ok_or(AppError::NotFound)? .registration_capacity()?; @@ -89,10 +94,14 @@ impl Registration { user: user.clone(), registered_by: registered_by.clone(), }; - match cap::claim_and_create( + match cap::claim_live_and_create( &event.record(), REGISTRATION_COUNT_FIELD, - capacity.unwrap_or(cap::UNLIMITED), + // An uncapped registration list stores no `capacity` key at all + // (SurrealDB drops a `NONE`-valued object key), so the coalesce is + // what "unlimited" reads as. + "audience.capacity ?? $num", + cap::UNLIMITED, ®istration.id.record(), ®istration, db, diff --git a/src/domain/settings.rs b/src/domain/settings.rs index daecb69..99f0ca4 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -12,6 +12,7 @@ //! existing rows, and `UPDATE` re-validates whole records). use surrealdb::types::{RecordId, SurrealValue}; +use tokio::sync::Mutex; use crate::constant::{ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, @@ -27,6 +28,32 @@ use crate::database::Database; use crate::domain::text_fold; use crate::error::{AppError, ValidationError}; +/// One settings edit at a time, over the whole process. +/// +/// A list edit is a **pair** of writes, and the pair is the guard: every name +/// the edit drops is retired on its reference counter first (which refuses +/// every later claim), and only then is the list itself committed with a +/// compare-and-set against the snapshot the removals were judged from. Neither +/// write can be made to cover the other. Both retirement and un-retirement are +/// *idempotent*, so a rival that decided the same removal against the same +/// snapshot is told "already retired" and records no rollback — and when it is +/// that rival's save that wins the compare-and-set, the attempt which really +/// flipped the bit rolls it back, leaving the name off the stored list with a +/// counter reading "in service": gradable again, and unremovable for good once +/// a mark lands. No per-name bit can close that, because `Unchanged` has +/// erased which attempt owns the flip. +/// +/// So the pair is serialized instead. Every writer of the singleton goes +/// through `PATCH /settings`, and the deployment runs one replica by contract +/// (stop-the-world upgrades), so process-wide is deployment-wide here — the +/// same argument [`crate::domain::cap`]'s own lock makes for `retire_name`'s +/// two statements, one level up. The compare-and-set stays: it is what keeps a +/// crashed or rolled-back attempt from writing a list nobody merged. +/// +/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse — +/// the retirements are taken while this is held. +pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(()); + /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight: /// how many times an exam of that kind counts into its course's average. /// Weight lives here, not on the exam — reweighting a kind reweights every @@ -86,6 +113,24 @@ pub struct MealSlotDef { impl MealSlotDef { pub fn try_new(name: &str, serving_minute: Option) -> Result { + Self::build(name, serving_minute, false) + } + + /// [`Self::try_new`] for a name the stored list *already* carries. + /// + /// The URL-safety rule below is younger than the lists it validates, and + /// `PATCH /settings` re-validates the whole submitted list — so a school + /// that stored a slot named `a/b` before the rule existed could never edit + /// `meal_slots` again: re-sending the name is a 400, and dropping it is a + /// 409 the moment a menu was published under it. Grandfathering a name the + /// row already holds unwedges the rest of the list while leaving the rule + /// in full force for every *new* name — the stored one is exactly as + /// unusable as it already was, and dropping it stays the only way out. + pub fn try_kept(name: &str, serving_minute: Option) -> Result { + Self::build(name, serving_minute, true) + } + + fn build(name: &str, serving_minute: Option, kept: bool) -> Result { let name = name.trim(); if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { return Err(ValidationError::Invalid { @@ -93,6 +138,21 @@ impl MealSlotDef { reason: "slot names must be 1 to 50 characters", }); } + // The name goes verbatim into a menu's record id, and that id is a URL + // path segment: a slot named `a/b` would define a slot no menu can ever + // be published under (`MenuSlot::try_new` refuses the same characters, + // at the one place a name becomes an id). Refusing it here too is what + // keeps the settings from offering a slot the canteen cannot use. + if !kept + && name + .chars() + .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) + { + return Err(ValidationError::Invalid { + field: "meal_slots", + reason: "meal slot names used for menus must not contain / \\ ? # or %", + }); + } if let Some(minute) = serving_minute { in_range( "meal_slots", diff --git a/src/lib.rs b/src/lib.rs index 684ceb9..3dbd952 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into classes (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (untagged = placed by hand, and a hand-placed row is never adopted, never swept). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into classes (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", ), modifiers(&SecurityAddon), tags( @@ -58,13 +58,13 @@ use crate::state::AppState; (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), - (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge — the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), + (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), + (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), - (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), + (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board, since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"), ), )] diff --git a/src/migration_sql.rs b/src/migration_sql.rs index f1f6b1d..e8b1fa9 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -280,6 +280,14 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record; DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record; DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record; + -- When the student was put in. Both link tables key on the *pair* + -- (`_`), so ordering a roster by its record id sorts it by the + -- member's account ULID — an arbitrary order the routes nevertheless + -- documented as newest-first. `option` and no BACKFILL: rows written + -- before this column are of unknown age, and an absent stamp is NONE, which + -- SurrealDB sorts *last* under DESC — already the honest place for them, so + -- there is no number to invent. + DEFINE FIELD IF NOT EXISTS added_at ON class_member TYPE option; DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE; DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class; DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user; @@ -288,6 +296,9 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record; DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record; DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record; + -- The mirror of `class_member.added_at`, for the same reason: without it + -- the course list is ordered by the *course's* ULID. + DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option; DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; @@ -1057,6 +1068,23 @@ pub const BACKFILL: &str = " FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) { UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE; }; + + -- The clear marker began paying the board's lifetime counter (2026-08-02): + -- it is a real `board_stroke` row, so a marker that charged nothing left + -- `total_stroke_count` counting marks *drawn* instead of rows *stored*, and + -- every board an older binary cleared is short exactly one per past clear. + -- + -- The only repair here that is NOT `= NONE`-guarded, and the one counter + -- that may be: it is not an opinion the live system maintains, it is the + -- board's row count — every stroke and every marker charges 1, and a stroke + -- row is only ever deleted with the board itself (domain::board_stroke). + -- So recomputing converges instead of overwriting, and `!= $row.n` writes + -- nothing on the next boot, when every counter already equals its count. + -- No zero pass: a board nobody drew on forms no group, and an absent + -- counter already reads as zero through the `?? 0` every reader applies. + FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) { + UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n; + }; "; /// The migration batches, in the order a boot applies them — and the *only* diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 8ee460b..26255e9 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -68,7 +68,7 @@ use tokio::sync::broadcast::error::RecvError; use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN}; use crate::database::Database; use crate::domain::board::{Board, BoardId}; -use crate::domain::board_stroke::BoardStroke; +use crate::domain::board_stroke::{self, BoardStroke}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -524,24 +524,23 @@ async fn creator_board( } } -/// A machine-readable `code` beside the public words. The three refusals the -/// stroke path can raise are distinguished by their message, because that is -/// what [`BoardStroke::append`] hands back and each one means a different thing -/// to a client: `epoch_full` is recoverable by clearing, `locked` is a pause -/// that will lift, `board_closed` is terminal. +/// A machine-readable `code` beside the public words. Each refusal the board +/// path can raise means a different thing to a client: `epoch_full` is +/// recoverable by clearing, `locked` is a pause that will lift, `canvas_blank` +/// is nothing to do, `board_closed` is terminal. +/// +/// The match is on the refusal *constants* [`board_stroke`] raises, by value — +/// never on a substring of them. Guessing from a substring made every reworded +/// refusal a silent re-labelling: "the canvas is already blank" contains the +/// word "closed", so a blank canvas told a live room its board was finished. fn error_frame(err: &AppError, client_seq: Option) -> Value { let code = match err { AppError::Forbidden(_) => "forbidden", - AppError::Conflict(message) if message.contains("clear it to keep drawing") => "epoch_full", - AppError::Conflict(message) if message.contains("locked") => "locked", - // "read-only" (the lifetime cap), and the clear's own "it is closed, or - // you did not create it" — the socket already checked the creator, so - // what is left is closed, and that is what the client must act on. - AppError::Conflict(message) - if message.contains("read-only") || message.contains("closed") => - { - "board_closed" - } + AppError::Conflict(message) if *message == board_stroke::EPOCH_FULL => "epoch_full", + AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked", + AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed", + AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank", + // Everything else, `BOARD_MOVED` included: retryable, never terminal. AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", AppError::NotFound => "not_found", @@ -563,45 +562,44 @@ fn error_frame(err: &AppError, client_seq: Option) -> Value { mod tests { use super::*; - /// The three refusals `append` can answer with are one `Conflict` variant - /// apiece, told apart only by their wording — so this pairing is the whole - /// contract behind `epoch_full` (clear and carry on), `locked` (wait) and - /// `board_closed` (never again). Getting it wrong sends a paused room off - /// clearing a canvas it never needed to lose. + fn code(err: AppError) -> String { + error_frame(&err, None)["code"] + .as_str() + .unwrap() + .to_string() + } + + /// The pairing is the whole contract behind `epoch_full` (clear and carry + /// on), `locked` (wait), `canvas_blank` (nothing to do) and `board_closed` + /// (never again). Getting it wrong sends a paused room off clearing a + /// canvas it never needed to lose. + /// + /// Written against the constants, never against copies of their words: a + /// test that pins the wording rots into a test of a string the code can no + /// longer emit, which is exactly how the blank canvas shipped as + /// `board_closed` through a green suite. The length assertion is the other + /// half — a refusal added to `board_stroke::REFUSALS` fails here until it + /// is given the code its client must act on. #[test] fn every_refusal_gets_the_code_its_client_must_act_on() { - let code = |err: AppError| { - error_frame(&err, None)["code"] - .as_str() - .unwrap() - .to_string() - }; + let pairs = [ + (board_stroke::EPOCH_FULL, "epoch_full"), + (board_stroke::BOARD_LOCKED, "locked"), + (board_stroke::BOARD_CLOSED, "board_closed"), + (board_stroke::CANVAS_BLANK, "canvas_blank"), + // A stroke that lost its epoch to a clear is a plain retryable + // conflict, and must never be mistaken for terminal. + (board_stroke::BOARD_MOVED, "conflict"), + ]; assert_eq!( - code(AppError::Conflict( - "this board is full — clear it to keep drawing" - )), - "epoch_full" - ); - assert_eq!( - code(AppError::Conflict( - "this board is locked — the creator has paused drawing" - )), - "locked" - ); - assert_eq!( - code(AppError::Conflict( - "this board is closed — it is permanently read-only" - )), - "board_closed" - ); - // A stroke that lost its epoch to a clear is none of the three: it is a - // plain retryable conflict, and must never be mistaken for terminal. - assert_eq!( - code(AppError::Conflict( - "this board changed while you were drawing — draw it again" - )), - "conflict" + pairs.len(), + board_stroke::REFUSALS.len(), + "a refusal the room cannot code" ); + for (message, expected) in pairs { + assert!(board_stroke::REFUSALS.contains(&message)); + assert_eq!(code(AppError::Conflict(message)), expected, "{message}"); + } assert_eq!(code(AppError::Forbidden("nope")), "forbidden"); // Internals are logged, never wired. let frame = error_frame(&AppError::Internal("secret".into()), None); @@ -609,36 +607,23 @@ mod tests { assert_eq!(frame["message"], "internal server error"); } - /// Every refusal the room can raise has to reach the client as the code - /// that tells it what to *do*: clear (recoverable), wait (paused) or stop - /// (terminal). The clear's own refusal is the one that hides — it names two - /// causes, but the socket has already checked the creator, so what is left - /// is `board_closed` and never the generic `conflict`. + /// A blank canvas is the refusal that hides: it is a *live* board saying + /// "nothing to clear", so it must never carry the terminal code. The two it + /// sits between are checked with it, since what matters is that no two of + /// the three collapse into one code. #[test] - fn each_refusal_keeps_its_own_code() { - let code = |err: AppError| { - error_frame(&err, None)["code"] - .as_str() - .unwrap() - .to_string() - }; + fn a_blank_canvas_is_never_terminal() { assert_eq!( - code(AppError::Conflict( - "this board cannot be cleared — it is closed, or you did not create it" - )), - "board_closed" + code(AppError::Conflict(board_stroke::CANVAS_BLANK)), + "canvas_blank" ); assert_eq!( - code(AppError::Conflict( - "this board is locked — the creator has paused drawing" - )), - "locked" + code(AppError::Conflict(board_stroke::BOARD_CLOSED)), + "board_closed" ); assert_eq!( - code(AppError::Conflict( - "this board is full — clear it to keep drawing" - )), - "epoch_full" + code(AppError::Conflict(board_stroke::BOARD_LOCKED)), + "locked" ); } diff --git a/src/web/boards.rs b/src/web/boards.rs index 8b33c21..b71a71b 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -504,7 +504,9 @@ async fn update_board( /// stroke count, so the live canvas is blank while every mark ever drawn stays /// readable through `/history`. Also resets the live-canvas cap, which is how a /// board that answered "clear it to keep drawing" is recovered. `409` on a -/// closed board. +/// closed board, and on a canvas that is **already blank** — the marker is a +/// real stroke row charged to the board's lifetime cap, so a clear has to close +/// at least one mark to be worth a row. #[utoipa::path( post, path = "/{id}/clear", @@ -516,7 +518,7 @@ async fn update_board( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Only the creator may clear the board", body = ErrorResponse), (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), - (status = 409, description = "The board is closed", body = ErrorResponse), + (status = 409, description = "The canvas is already blank, or the board is closed", body = ErrorResponse), ), )] async fn clear_board( diff --git a/src/web/classes.rs b/src/web/classes.rs index 68beb03..460c8c9 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -362,7 +362,7 @@ async fn delete_class( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Class not found", body = ErrorResponse), - (status = 409, description = "Already in this class, or one of its courses is full", body = ErrorResponse), + (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), one of its courses is full, or one of them no longer exists (a stale attachment — detach it)", body = ErrorResponse), ), )] async fn add_member( @@ -488,7 +488,7 @@ async fn remove_member( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Class not found", body = ErrorResponse), - (status = 409, description = "Already attached, or the course cannot hold the whole class", body = ErrorResponse), + (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), or the course cannot hold the whole class", body = ErrorResponse), ), )] async fn attach_course( @@ -556,7 +556,9 @@ async fn list_class_courses( /// that course, like attaching. The enrollments the class pumped into it are /// swept — except rows another attached class still claims (re-tagged to it) /// and rows placed by hand (left standing). A course that was not attached is a -/// 404. +/// 404 — but a course row that is *gone* is not: the link a deleted course left +/// behind detaches (the rights check has nothing left to read, and no roster +/// left to protect), or the class holding it could never be deleted. #[utoipa::path( delete, path = "/{id}/courses/{course}", @@ -570,7 +572,7 @@ async fn list_class_courses( (status = 204, description = "Detached"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "Class or course not found, or that course was not attached", body = ErrorResponse), + (status = 404, description = "Class not found, or that course was not attached — a course row that is gone does not refuse the detach, it is the reason for it", body = ErrorResponse), ), )] async fn detach_course( @@ -579,15 +581,21 @@ async fn detach_course( Path((id, course)): Path<(String, String)>, ) -> Result { let class = class_or_404(&id, &st.db).await?; - let course = Course::read(&CourseId::from_key(&course), &st.db) - .await? - .ok_or(AppError::NotFound)?; - if !can_manage_course(&course, &user) { + let course = CourseId::from_key(&course); + // The rights check is skipped when the course row is gone, rather than the + // whole detach refused: management rights are read *off* the course, so a + // link left pointing at a deleted course had no readable owner and this + // route answered 404 forever — which also left the class undeletable, its + // attachment counter counting a row nothing could sweep. There is no roster + // left to protect, and the caller is already teacher+. + if let Some(course) = Course::read(&course, &st.db).await? + && !can_manage_course(&course, &user) + { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class", )); } - ClassCourse::detach(class.get_id(), course.get_id(), &st.db).await?; + ClassCourse::detach(class.get_id(), &course, &st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/courses.rs b/src/web/courses.rs index dd7311c..0e8b81e 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -160,6 +160,13 @@ struct EnrollmentResponse { user: PersonRef, /// Who enrolled them. enrolled_by: PersonRef, + /// The class (`GET /classes/{id}`) this row was pumped by, or `null` when a + /// human placed it directly. A row with a class on it is *swept* when that + /// class drops the student or detaches the course; a `null` one is nobody's + /// to take back. Without it no client could tell which of its roster rows a + /// class change is about to remove. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + source: Option, } impl EnrollmentResponse { @@ -169,6 +176,7 @@ impl EnrollmentResponse { course: enrollment.get_course().key().to_string(), user: PersonRef::resolve(people, enrollment.get_user()), enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()), + source: enrollment.get_source().map(|class| class.key().to_string()), } } } @@ -609,6 +617,9 @@ async fn unassign_teacher( /// student membership, and it gates sitting exams, being graded, and the class /// roster, all student-only. A course with a `capacity` refuses new members /// once the roster is full (someone already enrolled is returned as-is). +/// Enrolling a student a class pumped in takes the row *off* that class — +/// `source` comes back `null` — so a later class sweep can no longer undo a +/// placement made by hand, the mirror of a manual unenroll winning permanently. #[utoipa::path( post, path = "/{id}/enrollments", diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index e941e23..2233b38 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -644,6 +644,22 @@ async fn grade( if exam.is_draft() { return Err(crate::domain::exam_result::draft_error()); } + // The exam's kind must still be one the school offers. `kind_ref`'s retired + // bit is what actually refuses the mark inside `ExamResult::grade`, and it + // is a *different record* from the list — a settings PATCH moves both, so + // anything that leaves them disagreeing (a rolled-back retirement, a hand + // edit) would otherwise reopen grading under a kind nobody lists, which is + // also a mark that averages at weight 1 forever. Both gates, same answer; + // this one is a read, the counter's is the one that survives a race. + let kind = exam.get_kind().as_str(); + if !Settings::load(&st.db) + .await? + .get_exam_kinds() + .iter() + .any(|offered| offered.get_name() == kind) + { + return Err(crate::domain::exam_result::retired_kind_error(kind)); + } let mark = Mark::try_new(req.mark)?; let target = UserId::from_key(&req.user_id); diff --git a/src/web/limits.rs b/src/web/limits.rs index 7f4abd4..a49edbe 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -122,6 +122,10 @@ struct CourseLimits { max_class_name_len: usize, /// A class's optional free-text grade label ("9", "10-A"). max_class_grade_len: usize, + /// Students one class may hold. Removing one frees a place. + max_class_members: i64, + /// Courses one class may be attached to. Detaching one frees a place. + max_class_courses: i64, } /// Exams, their questions, answers, and marks. @@ -426,6 +430,8 @@ impl LimitsResponse { max_term_name_len: MAX_TERM_NAME_LEN, max_class_name_len: MAX_CLASS_NAME_LEN, max_class_grade_len: MAX_CLASS_GRADE_LEN, + max_class_members: MAX_CLASS_MEMBERS, + max_class_courses: MAX_CLASS_COURSES, }, exam: ExamLimits { max_title_len: MAX_EXAM_TITLE_LEN, diff --git a/src/web/meals.rs b/src/web/meals.rs index 626d3bf..6af6ffa 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -3,7 +3,8 @@ //! //! Reads are open to every authenticated user (a student picks their lunch), //! writes are manager+ — publishing what the school serves is kitchen -//! administration, not teaching. +//! administration, not teaching. The balance and the ledger are the exception: +//! they are manager+ like `/payments`, since canteen debt is family debt. //! //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price //! snapshot, cancelling reverses it, and recording a payment is admin-only. @@ -414,7 +415,10 @@ async fn add_dish( // is write-skew, so the count and the insert have to be one step. The // *price* no longer needs it — a dish write moves the menu's revision, and // a booking claims its seat at the revision it priced itself against. - // The lock stays a leaf: nothing below here takes another. + // The lock is a leaf again: the revision bump rides the dish write's own + // transaction now, so nothing held under it takes `cap`'s counter lock. It + // stays a leaf only while that holds — see [`MENU_LOCK`] for the order a + // caller that changes it must keep. let _guard = MENU_LOCK.lock().await; // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` // running in the gap takes its cascade with it and this dish lands on a menu @@ -902,8 +906,13 @@ async fn list_menu_bookings( /// Give the seat back. The row survives, flipped to `cancelled` — the seat is /// free for someone else, and the cancellation stays auditable. Only the -/// student it is for, or their parent, may cancel it. Refused (`409`) once the -/// school's `meal_cancel_cutoff_minutes` has closed the meal. +/// student it is for, or their parent, may cancel it — and for them it is +/// refused (`409`) once the school's `meal_cancel_cutoff_minutes` has closed +/// the meal. +/// +/// Manager+ may cancel anyone's booking, and is not bound by the cutoff — the +/// seat and the money have to stay reachable when the student it was booked for +/// is no longer a student, or when the meal has already closed. /// /// **Idempotent**: cancelling an already-cancelled booking is a `200` with the /// row as it stands, not a `409`. Repeating it also replays the refund, so a @@ -919,9 +928,9 @@ async fn list_menu_bookings( responses( (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse), + (status = 403, description = "Not the booking's student, their parent, nor a manager", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The cutoff has passed, or the menu was too contended to free the seat", body = ErrorResponse), + (status = 409, description = "The cutoff has passed (students and parents only), or the menu was too contended to free the seat", body = ErrorResponse), ), )] async fn cancel_booking( @@ -932,14 +941,34 @@ async fn cancel_booking( let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db) .await? .ok_or(AppError::NotFound)?; - // Same door as booking: whoever may take the seat may give it back. - let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?; - if &target != booking.get_student() { - return Err(AppError::Forbidden("not your booking")); + // Manager+ may give back *any* seat. Not a convenience: `booking_target` + // grants only students and parents, so a student promoted to staff (or a + // parent unlinked) left a live seat nobody on the API could cancel — the + // menu 409s its own delete forever and the charge can never be reversed, + // since cancelling is the only route that reverses one. Promotion itself + // deliberately sweeps nothing: moving money is a decision, not a side + // effect of a role change. + let staff = user.get_role().at_least(Role::Manager); + if !staff { + // Same door as booking: whoever may take the seat may give it back. + let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?; + if &target != booking.get_student() { + return Err(AppError::Forbidden("not your booking")); + } } - let cutoff = meal_cutoff(&st.db).await?; - // Flips the row and appends the reversal for that attempt's charge - // together, under the same lock booking uses; the charge itself stays. + // …and the cutoff does not bind them either. It exists to stop students + // gaming the kitchen's headcount, which is no reason to leave staff holding + // a seat they cannot free: past the cutoff the seat was uncancellable, and + // its menu — which refuses its own delete while a seat is held — was + // undeletable with it, forever. A deadline that binds nobody is exactly the + // one a school that set no `meal_cancel_cutoff_minutes` already runs under. + let cutoff = if staff { + MealCutoff::default() + } else { + meal_cutoff(&st.db).await? + }; + // Flips the row and appends the reversal for that attempt's charge in one + // transaction; the charge itself stays. let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?; let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?; Ok(Json( @@ -1051,8 +1080,12 @@ async fn mark_attendance( reason: "target user does not exist", })); } - let row = - MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?; + // The menu rides in the write's own target (see [`MealAttendance::mark`]), + // so a delete landing between the read above and this write leaves no mark + // behind — it answers 404 instead, exactly as the read would have. + let row = MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; Ok(Json( items.into_iter().next().expect("one mark in, one out"), @@ -1225,6 +1258,39 @@ async fn ensure_can_read_student( super::ensure_can_observe(caller, target, db).await } +/// May `caller` read `target`'s meal *money* — balance and ledger? Own always; +/// a parent only for a student they hold a live link to; manager+ for anyone. +/// +/// Deliberately narrower than [`ensure_can_read_student`], which still gates +/// the profile, booking and attendance reads at teacher+: **a teacher sees no +/// money**. Canteen debt is family debt, so this is the same rule (and the same +/// 403) `/payments` has always held — what a family owes the school is not +/// classroom information, and neither is what it owes the canteen. +async fn ensure_can_read_money( + caller: &User, + target: &UserId, + db: &Database, +) -> Result<(), AppError> { + if caller.get_id() == target || caller.get_role().at_least(Role::Manager) { + return Ok(()); + } + // The link row alone is not the grant: a link whose student side changed + // role must be inert, so the target's live role is re-read. A missing or + // non-student target falls through to the same 403 — a parent never gets an + // existence oracle. + if caller.get_role() == Role::Parent + && ParentLink::exists(caller.get_id(), target, db).await? + && User::read(target, db) + .await? + .is_some_and(|target| target.get_role() == Role::Student) + { + return Ok(()); + } + Err(AppError::Forbidden( + "requires manager role or higher, or a parent link to this student", + )) +} + /// What the caller owes or has on account. #[utoipa::path( get, @@ -1243,8 +1309,9 @@ async fn my_balance( balance_response(user.get_id(), &st.db).await } -/// One student's meal balance. Requires teacher+, or a parent link to them — -/// the caller's own id always passes. +/// One student's meal balance. Requires manager+, or a parent link to them — +/// the caller's own id always passes. A teacher gets a `403`: canteen debt is +/// family debt, gated exactly like `/payments`. #[utoipa::path( get, path = "/balance/{user}", @@ -1254,7 +1321,7 @@ async fn my_balance( responses( (status = 200, description = "The student's meal balance", body = BalanceResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_balance( @@ -1263,7 +1330,7 @@ async fn user_balance( Path(user): Path, ) -> Result, AppError> { let target = UserId::from_key(&user); - ensure_can_read_student(&caller, &target, &st.db).await?; + ensure_can_read_money(&caller, &target, &st.db).await?; balance_response(&target, &st.db).await } @@ -1280,7 +1347,7 @@ async fn user_balance( (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_ledger( @@ -1291,7 +1358,7 @@ async fn user_ledger( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); - ensure_can_read_student(&caller, &target, &st.db).await?; + ensure_can_read_money(&caller, &target, &st.db).await?; let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?; let items = ledger_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) @@ -1313,7 +1380,9 @@ struct RecordCredit { } /// Record money received from a student. **Admin only** — not manager: writing -/// down cash is the highest-trust action in the app. Appends a `credit` line; +/// down cash is the highest-trust action in the app. The target must be a +/// student, or anyone who already carries meal-ledger lines — a debt survives +/// its debtor's role change, and it has to stay settleable. Appends a `credit` line; /// nothing in the ledger is ever edited or removed, so an over-credit is /// corrected by a compensating line, not by a fix-up. #[utoipa::path( @@ -1337,12 +1406,20 @@ async fn record_credit( ) -> Result<(StatusCode, Json), AppError> { let student = UserId::from_key(&req.student_id); // Only a student carries a meal balance; crediting anyone else is a typo, - // and a typo here is money in the wrong ledger. + // and a typo here is money in the wrong ledger. Unless they already carry + // ledger lines: a debt outlives its debtor's role change (a student + // promoted to staff keeps what they owed), and the student rule alone made + // that debt permanently unsettleable — there is no other route that + // appends a credit. A typo'd staff id has no lines, so it still 400s. if User::read(&student, &st.db) .await? .ok_or(AppError::NotFound)? .get_role() != Role::Student + && MealLedger::list_for_student(&student, Some(1), 0, &st.db) + .await? + .0 + .is_empty() { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", diff --git a/src/web/settings.rs b/src/web/settings.rs index 446d6e5..689c66f 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -12,7 +12,7 @@ use crate::database::Database; use crate::domain::cap; use crate::domain::exam_result::kind_ref; use crate::domain::menu::slot_ref; -use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; +use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, SETTINGS_LOCK, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; @@ -189,7 +189,10 @@ struct UpdateSettings { /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts /// back from. `[]` switches the meal program off. A slot a menu was already /// published for cannot be removed (409); its serving time may be edited - /// freely and applies live, to menus already published for it too. + /// freely and applies live, to menus already published for it too. Names + /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) — + /// except a name the school already stores, which stays submittable so a + /// list written before that rule can still be edited. #[schema(max_items = 20)] meal_slots: Option>, /// Replaces the whole list when present: at most 20 unique entries, each @@ -239,7 +242,10 @@ async fn get_settings( /// applies at upload time only — already-stored files keep their size, and the /// chatbot knobs apply to the next chat request only. `meal_slots` follows the /// exam-kind rule: a slot a menu was already published for cannot be dropped -/// (409), because the menu snapshotted its name. +/// (409), because the menu snapshotted its name. Slot names must not contain +/// `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name +/// already on the school's stored list is exempt, so a list written before that +/// rule can still be edited around it. #[utoipa::path( patch, path = "/", @@ -259,12 +265,24 @@ async fn update_settings( RequireManager(_user): RequireManager, Json(req): Json, ) -> Result, AppError> { + Ok(Json(SettingsResponse::new(&apply(&req, &st.db).await?))) +} + +/// The whole edit — snapshot, merge, retire, save — as one operation, so the +/// tests can drive it the way two managers do. Split out of the handler for +/// nothing else. +async fn apply(req: &UpdateSettings, db: &Database) -> Result { + // One settings edit at a time: the removals below are decided against the + // snapshot this loop loads and written *before* the save that justifies + // them, and no per-name bookkeeping can make that pair survive a rival's + // pair interleaving with it (see `SETTINGS_LOCK`). + let _guard = SETTINGS_LOCK.lock().await; // Merge over a snapshot, then save only while the row still matches it — // otherwise a concurrent PATCH of a *different* field would be silently // reverted by whichever whole-row write lands second. A refused save // reloads and re-merges, so both edits land. for _ in 0..CAS_UPDATE_RETRIES { - let current = Settings::load(&st.db).await?; + let current = Settings::load(db).await?; let exam_kinds = match &req.exam_kinds { Some(kinds) => kinds @@ -273,10 +291,21 @@ async fn update_settings( .collect::, _>>()?, None => current.get_exam_kinds().to_vec(), }; + let was_slots = slot_names(¤t.get_meal_slots()); let meal_slots = match &req.meal_slots { Some(slots) => slots .iter() - .map(|slot| MealSlotDef::try_new(&slot.name, slot.serving_minute)) + .map(|slot| { + // A name the row already carries is validated as a kept one: + // the charset rule is younger than the stored lists, and + // re-validating one under it would leave a school unable to + // edit the rest of its slots at all (`MealSlotDef::try_kept`). + if was_slots.iter().any(|kept| kept == slot.name.trim()) { + MealSlotDef::try_kept(&slot.name, slot.serving_minute) + } else { + MealSlotDef::try_new(&slot.name, slot.serving_minute) + } + }) .collect::, _>>()?, None => current.get_meal_slots(), }; @@ -295,7 +324,6 @@ async fn update_settings( // guards below — a list edit is judged by which names it drops. let was_kinds = kind_names(current.get_exam_kinds()); let now_kinds = kind_names(&exam_kinds); - let was_slots = slot_names(¤t.get_meal_slots()); let now_slots = slot_names(&meal_slots); // Merge over the snapshot's resolved values: an omitted field keeps @@ -336,17 +364,27 @@ async fn update_settings( // Retired before the save, never after: the other order leaves a window // in which a mark lands under a kind the settings no longer list. A save // that then does not land undoes them (`restore`) before the next try. - let mut retired: Vec = Vec::new(); + // + // Only a write that actually *flipped* a bit is recorded for that undo. + // Retirement is idempotent, so two PATCHes dropping the same kind are + // both told "retired" — and the one whose save then loses the row's CAS + // used to un-retire the winner's kind, leaving it off the list with its + // counter in service: gradable again, its count then non-zero, and so + // impossible to remove ever after. + let mut undo: Vec = Vec::new(); let mut refused = None; for gone in missing(&was_kinds, &now_kinds) { let counter = kind_ref(&gone); - if !cap::retire(&counter, &st.db).await? { - refused = Some(AppError::ConflictOwned(format!( - "exams of kind '{gone}' are already graded — the kind cannot be removed" - ))); - break; + match cap::retire_name(&counter, db).await? { + cap::Switched::Flipped => undo.push(Undo::Retired(counter)), + cap::Switched::Unchanged => {} + cap::Switched::InUse => { + refused = Some(AppError::ConflictOwned(format!( + "exams of kind '{gone}' are already graded — the kind cannot be removed" + ))); + break; + } } - retired.push(counter); } // Same shape for meal slots: a slot a menu was already published for // cannot leave the list — the menu snapshotted the name as text, and a @@ -355,37 +393,46 @@ async fn update_settings( if refused.is_none() { for gone in missing(&was_slots, &now_slots) { let counter = slot_ref(&gone); - if !cap::retire(&counter, &st.db).await? { - refused = Some(AppError::ConflictOwned(format!( - "menus are already published for the '{gone}' slot — it cannot be removed" - ))); - break; + match cap::retire_name(&counter, db).await? { + cap::Switched::Flipped => undo.push(Undo::Retired(counter)), + cap::Switched::Unchanged => {} + cap::Switched::InUse => { + refused = Some(AppError::ConflictOwned(format!( + "menus are already published for the '{gone}' slot — it cannot be removed" + ))); + break; + } } - retired.push(counter); } } if let Some(refused) = refused { - restore(&retired, &st.db).await?; + restore(&undo, db).await?; return Err(refused); } // A name re-entering a list is back in service: its counter still // carries the retirement from the edit that dropped it, and a mark (or // a menu) under a kind the school offers again must not be refused. + // Recorded for the same undo as the retirements — a re-add whose save + // does not land leaves a name off the list that grades happily. for back in missing(&now_kinds, &was_kinds) { - cap::unretire(&kind_ref(&back), &st.db).await?; + if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? { + undo.push(Undo::Unretired(kind_ref(&back))); + } } for back in missing(&now_slots, &was_slots) { - cap::unretire(&slot_ref(&back), &st.db).await?; + if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? { + undo.push(Undo::Unretired(slot_ref(&back))); + } } - match settings.save_if_unchanged(¤t, &st.db).await { - Ok(Some(saved)) => return Ok(Json(SettingsResponse::new(&saved))), + match settings.save_if_unchanged(¤t, db).await { + Ok(Some(saved)) => return Ok(saved), // The row moved under the snapshot these guards were judged against: // put the names back and re-merge, or the next attempt would decide // against a list nobody asked for. - Ok(None) => restore(&retired, &st.db).await?, + Ok(None) => restore(&undo, db).await?, Err(err) => { - restore(&retired, &st.db).await?; + restore(&undo, db).await?; return Err(err); } } @@ -419,11 +466,335 @@ fn missing(before: &[String], after: &[String]) -> Vec { .collect() } -/// Put back every name this attempt retired: the edit that would have removed -/// them did not land, so they are still names the school offers. -async fn restore(names: &[RecordId], db: &Database) -> Result<(), AppError> { - for name in names { - cap::unretire(name, db).await?; +/// One `retired` bit this attempt moved, and which way — what `restore` needs +/// to put it back. Only bits this attempt actually *flipped* are listed: a +/// write that changed nothing has nothing to take back, and taking it back +/// would undo the concurrent edit that really did move it. +enum Undo { + /// Retired for a removal; put it back in service. + Retired(RecordId), + /// Put back in service for a re-add; retire it again. + Unretired(RecordId), +} + +/// Undo every bit this attempt moved: the edit that justified them did not +/// land, so the lists the school offers are still the ones it started with. +async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> { + for step in undo { + match step { + Undo::Retired(name) => { + cap::unretire_name(name, db).await?; + } + // A re-retirement can be refused: a mark (or a menu) landed under + // the name during the window it was in service. Refusing to undo is + // then the honest answer — the reference is real, and retiring over + // it would make the row's kind ungradable while nothing lists it. + // The name is left in service, matching the list this attempt is + // about to re-read. + Undo::Unretired(name) => { + cap::retire_name(name, db).await?; + } + } } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + + /// The `retired` bit as the store holds it, `None` when no counter row was + /// ever written — read back, never inferred from a return value. + async fn bit(db: &Database, counter: RecordId) -> Option { + let mut result = db + .query("SELECT VALUE retired FROM $id") + .bind(("id", counter)) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().first().copied() + } + + /// Two managers drop the same exam kind at once; one of them loses the + /// row's compare-and-set and rolls its attempt back. The winner's + /// retirement must survive that rollback — undone, the kind is off the list + /// with a counter that still grades, and the first mark to land makes it + /// unremovable for good. + /// + /// The loser's half is what runs here: a retirement that changed nothing + /// records no undo, so `restore` has nothing to take back. + #[tokio::test] + async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() { + let db = init_mem().await.unwrap(); + let counter = kind_ref("midterm"); + + // The winner's PATCH retires the kind. + assert!(matches!( + cap::retire_name(&counter, &db).await.unwrap(), + cap::Switched::Flipped + )); + + // The loser's PATCH decides the same removal against the same snapshot, + // then its save is refused. + let mut undo = Vec::new(); + if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() { + undo.push(Undo::Retired(counter.clone())); + } + assert!(undo.is_empty(), "a no-op retirement records no undo"); + restore(&undo, &db).await.unwrap(); + + assert_eq!( + bit(&db, counter).await, + Some(true), + "the winner's retirement must outlive the loser's rollback" + ); + } + + /// The mirror hole: a re-*added* name is put back in service before the + /// save, so a save that does not land owes a re-retirement. Without it the + /// name is off the stored list with a counter that grades happily. + #[tokio::test] + async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() { + let db = init_mem().await.unwrap(); + let counter = slot_ref("lunch"); + cap::retire_name(&counter, &db).await.unwrap(); + + // The attempt re-adds the slot, then its save is refused. + let mut undo = Vec::new(); + if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() { + undo.push(Undo::Unretired(counter.clone())); + } + assert_eq!(undo.len(), 1, "a real un-retirement is undoable"); + restore(&undo, &db).await.unwrap(); + + assert_eq!( + bit(&db, counter).await, + Some(true), + "a re-add that never landed must leave the slot retired" + ); + } + + /// ...unless a menu was published in the window the slot was back in + /// service. The reference is real, so the re-retirement is refused and the + /// slot stays usable — the honest end of the same rule, not a silent + /// overwrite of a live reference. + #[tokio::test] + async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() { + let db = init_mem().await.unwrap(); + let counter = slot_ref("lunch"); + cap::retire_name(&counter, &db).await.unwrap(); + cap::unretire_name(&counter, &db).await.unwrap(); + db.query("UPDATE $id SET count = 1") + .bind(("id", counter.clone())) + .await + .unwrap() + .check() + .unwrap(); + + restore(&[Undo::Unretired(counter.clone())], &db) + .await + .unwrap(); + + assert_eq!(bit(&db, counter).await, Some(false)); + } + + // --- the whole edit, driven the way two managers drive it ------------- + + /// A `PATCH` body, built the way the router builds one. + fn patch(body: serde_json::Value) -> UpdateSettings { + serde_json::from_value(body).unwrap() + } + + /// A `meal_slots`/`exam_kinds` list as the DTO carries it. + fn kinds(names: &[&str]) -> serde_json::Value { + names + .iter() + .map(|name| serde_json::json!({ "name": name, "weight": 1 })) + .collect() + } + + fn slots(names: &[&str]) -> serde_json::Value { + names + .iter() + .map(|name| serde_json::json!({ "name": name, "serving_minute": null })) + .collect() + } + + /// The lists as the store holds them. + async fn stored(db: &Database) -> (Vec, Vec) { + let settings = Settings::load(db).await.unwrap(); + ( + kind_names(settings.get_exam_kinds()), + slot_names(&settings.get_meal_slots()), + ) + } + + /// The whole invariant, over the reachable half of the race: two managers + /// drop the same exam kind at once, both edits go through the real path, + /// and when both have returned the counter's `retired` bit must agree with + /// the list the store actually holds. + /// + /// One of the two decides the removal, retires the kind and saves; the + /// other cannot even see the old list, because the whole snapshot-retire- + /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second + /// attempt would be told "already retired", record no undo, win the + /// compare-and-set, and leave the first attempt un-retiring the kind it had + /// legitimately removed — off the list and gradable. + #[tokio::test] + async fn two_edits_dropping_the_same_kind_leave_it_retired() { + let db = init_mem().await.unwrap(); + let without = patch(serde_json::json!({ + "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), + })); + + let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db)); + a.unwrap(); + b.unwrap(); + + let (kinds, _) = stored(&db).await; + assert!( + !kinds.contains(&"midterm".to_string()), + "dropped from the list" + ); + assert_eq!( + bit(&db, kind_ref("midterm")).await, + Some(true), + "a kind the stored list no longer offers must not grade" + ); + } + + /// The property those two outcomes rest on, asserted on its own because a + /// `join!` cannot be made to schedule the losing order: the edit is a pair + /// of writes — retire the dropped names, then commit the list — and no + /// rival's pair may run between them. + /// + /// Retirement is idempotent, so an interleaved rival is told "already + /// retired", records no rollback, wins the compare-and-set, and leaves the + /// attempt that really flipped the bit un-retiring a kind the stored list + /// no longer offers: gradable again, and unremovable for good once a mark + /// lands. Holding the lock stands in for a rival mid-pair here — nothing + /// the other edit does may be visible until the pair completes. + #[tokio::test] + async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() { + let db = init_mem().await.unwrap(); + let without = patch(serde_json::json!({ + "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), + })); + + let held = SETTINGS_LOCK.lock().await; + let rival = tokio::spawn({ + let db = db.clone(); + async move { apply(&without, &db).await.map(|_| ()) } + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + + assert_eq!( + bit(&db, kind_ref("midterm")).await, + None, + "a rival's pair must not have started, let alone half-landed" + ); + assert!(stored(&db).await.0.contains(&"midterm".to_string())); + + drop(held); + rival.await.unwrap().unwrap(); + assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true)); + assert!(!stored(&db).await.0.contains(&"midterm".to_string())); + } + + /// The mirror: two managers put the same kind *back* at once. The attempt + /// that loses must not re-retire a name the winner's stored list carries — + /// a listed kind that refuses every grade. + #[tokio::test] + async fn two_edits_re_adding_the_same_kind_leave_it_in_service() { + let db = init_mem().await.unwrap(); + let without = patch(serde_json::json!({ + "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]), + })); + apply(&without, &db).await.unwrap(); + let with = patch(serde_json::json!({ + "exam_kinds": kinds(&["homework", "quiz", "midterm", "final", "project", "oral"]), + })); + + let (a, b) = tokio::join!(apply(&with, &db), apply(&with, &db)); + a.unwrap(); + b.unwrap(); + + let (kinds, _) = stored(&db).await; + assert!(kinds.contains(&"midterm".to_string()), "back on the list"); + assert_eq!( + bit(&db, kind_ref("midterm")).await, + Some(false), + "a kind the stored list offers must grade" + ); + } + + /// The same pair over meal slots, which retire on their own counters. + #[tokio::test] + async fn two_edits_dropping_the_same_slot_leave_it_retired() { + let db = init_mem().await.unwrap(); + let without = patch(serde_json::json!({ + "meal_slots": slots(&["breakfast", "snack"]), + })); + + let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db)); + a.unwrap(); + b.unwrap(); + + let (_, stored_slots) = stored(&db).await; + assert!(!stored_slots.contains(&"lunch".to_string())); + assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true)); + } + + // --- the stale slot name that wedged the whole list ------------------- + + /// A school that stored `a/b` before the URL-safety rule existed. + async fn a_school_with_a_stale_slot(db: &Database) { + let mut params = Settings::defaults().params(); + params.meal_slots = vec![ + MealSlotDef::try_kept("a/b", None).unwrap(), + MealSlotDef::try_new("lunch", None).unwrap(), + ]; + Settings::try_new(params).unwrap().save(db).await.unwrap(); + } + + /// The wedge: re-sending a stored name is the only way to *keep* it, and + /// dropping it 409s once a menu references it — so validating it under the + /// younger rule locks the school out of its own `meal_slots` forever. A + /// stored name is submittable; a new one with the same characters is not. + #[tokio::test] + async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() { + let db = init_mem().await.unwrap(); + a_school_with_a_stale_slot(&db).await; + + let edit = patch(serde_json::json!({ + "meal_slots": slots(&["a/b", "lunch", "dinner"]), + })); + apply(&edit, &db).await.unwrap(); + let (_, stored_slots) = stored(&db).await; + assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]); + + let fresh = patch(serde_json::json!({ + "meal_slots": slots(&["a/b", "lunch", "c/d"]), + })); + assert!( + apply(&fresh, &db).await.is_err(), + "a name no school ever stored is still refused" + ); + } + + /// And an edit that never mentions `meal_slots` still carries the list + /// over unvalidated — the behaviour the wedge report leaned on. + #[tokio::test] + async fn an_unrelated_edit_carries_a_stale_slot_name_over() { + let db = init_mem().await.unwrap(); + a_school_with_a_stale_slot(&db).await; + + let elsewhere = patch(serde_json::json!({ "max_file_bytes": 2048 })); + let saved = apply(&elsewhere, &db).await.unwrap(); + + assert_eq!(saved.get_max_file_bytes(), 2048); + assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]); + } +} diff --git a/src/web/users.rs b/src/web/users.rs index 6756db5..508e5b2 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -7,9 +7,8 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::class_member::ClassMember; +use crate::domain::class_pump; use crate::domain::course::Course; -use crate::domain::enrollment::Enrollment; use crate::domain::parent_link::ParentLink; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; @@ -399,14 +398,12 @@ async fn set_role( // Parent links get the same sweep on both sides: only students are // observed and only parents observe, so a role change off either end // drops the rows instead of leaving dead grants around. - // The class memberships go first and the enrollments second: the class - // sweep deliberately leaves the enrollment rows alone, so running it after - // would find nothing to repair and running it before costs nothing either - // way. Both are needed — a membership left behind would keep pumping the - // user back into courses and make its class undeletable. + // The class memberships and the enrollments go in *one* transaction: run + // as two, a failure between them left enrollment rows tagged with a class + // whose counters had already been released, so the class could be deleted + // and nothing could ever sweep the rows again. if role != Role::Student { - ClassMember::delete_for_user(&target, &st.db).await?; - Enrollment::delete_for_user(&target, &st.db).await?; + class_pump::sweep_non_student(&target, &st.db).await?; ParentLink::delete_where_student(&target, &st.db).await?; } if role != Role::Parent { diff --git a/tests/e2e.rs b/tests/e2e.rs index 67a3227..ea22df2 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -3003,6 +3003,44 @@ async fn a_roster_change_drops_only_the_socket_it_removed() { ); } +/// Test 15 — clearing a blank canvas is a *live* board saying "nothing to do", +/// and the room must say so with a non-terminal code. It shipped as +/// `board_closed` — the terminal one — because the classifier guessed the code +/// from a substring of the refusal's words, and the reworded refusal happens to +/// contain "closed". A creator who double-clicks clear would have been told the +/// board was finished forever, on a board still open and still drawable. +#[tokio::test] +async fn clearing_a_blank_canvas_never_tells_the_room_the_board_is_closed() { + let room = board_room_fixture().await; + let (base, board) = (&room.base, &room.board_id); + let mut ali = board_open(base, board, Some(&room.creator_cookie)) + .await + .expect("upgrade"); + board_join(&mut ali, None, None).await; + + // Nothing drawn yet: there is no epoch to close. + ws_send(&mut ali, json!({ "type": "clear" })).await; + let error = board_frame_of_type(&mut ali, "error").await; + assert_eq!(error["code"], "canvas_blank", "{error}"); + + // The same refusal after a real clear — the second press of the button. + board_draw(&mut ali, "one").await; + ws_send(&mut ali, json!({ "type": "clear" })).await; + board_frame_of_type(&mut ali, "cleared").await; + ws_send(&mut ali, json!({ "type": "clear" })).await; + assert_eq!( + board_frame_of_type(&mut ali, "error").await["code"], + "canvas_blank" + ); + + // And the board really is live: the socket draws on, into the new epoch. + board_draw(&mut ali, "two").await; + assert_eq!( + stored_payloads(&room.db, board, 1).await, + vec!["two".to_string()] + ); +} + /// The class layer over real HTTP with three cookie jars: the office builds the /// class, the teacher hands over their own course, and the student — who was /// never enrolled by anyone — finds it on `GET /courses/me`. Taking them out of diff --git a/tests/integration.rs b/tests/integration.rs index 862144a..02bc0b3 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -22076,9 +22076,9 @@ async fn meal_credits_are_admin_only_and_raise_the_balance() { } /// Whose money a caller may read: their own, their linked child's, or — as -/// teacher+ — anyone's. Never another family's. +/// manager+ — anyone's. Never another family's, and never a teacher's business. #[tokio::test] -async fn meal_balance_reads_follow_the_observer_gate() { +async fn meal_balance_reads_are_manager_only_outside_the_family() { let (app, db) = app_and_db().await; let admin = login_as(&app, &db, "wallet_boss", "admin").await; let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await; @@ -22149,7 +22149,8 @@ async fn meal_balance_reads_follow_the_observer_gate() { .await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); - // Teacher+ reads any student's. + // A teacher does not, however: what a family owes the canteen is money, + // and money is manager+ here exactly as it is on /payments. let res = send( &app, "GET", @@ -22158,6 +22159,17 @@ async fn meal_balance_reads_follow_the_observer_gate() { None, ) .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // Manager+ reads any student's. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&admin), + None, + ) + .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); } @@ -22322,6 +22334,90 @@ async fn meal_attendance_never_moves_money() { assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); } +/// Deleting a menu takes its marks with it. The menu id is deterministic on +/// `(date, slot)`, so republishing the same meal mints the *same* record id: a +/// mark left behind by the deleted menu would come back as a mark on the new +/// one — the kitchen would read "served" for a student who never came, and the +/// student's own report would cite a menu that no longer exists. +#[tokio::test] +async fn deleting_a_menu_takes_its_attendance_with_it() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "ghost_mgr", "manager").await; + let teacher = login_as(&app, &db, "ghost_teacher", "teacher").await; + let ali = login(&app, "ghost_ali").await; + let ali_id = me_id(&app, &ali).await; + + let publish = json!({ "date": "2026-10-05", "slot": "lunch" }); + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(publish.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let menu = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/attendance"), + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // No seat was ever taken, so the counter guard lets the delete through. + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // The student's own report must not cite a menu that is gone. + let res = send( + &app, + "GET", + &format!("/meals/attendance/{ali_id}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + common::total(&res.body), + 0, + "the mark outlived the menu it was taken on" + ); + + // Republishing the same day and slot lands on the same record id. + let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(publish)).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let again = id_of(&res.body); + assert_eq!(again, menu, "the id is deterministic on (date, slot)"); + + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/attendance"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + common::total(&res.body), + 0, + "the deleted menu's mark came back on the republished one" + ); +} + /// The per-student report: a lexical `?from=&to=` window over the menu's day, /// readable by teacher+ or a linked parent and by nobody else. #[tokio::test] @@ -24718,8 +24814,9 @@ async fn a_full_canvas_is_refused_until_the_creator_clears_it() { ); assert_eq!( stored_counters(&db, &board).await, - vec![1, MAX_EPOCH_STROKES + 1], - "the epoch counter reset; the lifetime counter did not" + vec![1, MAX_EPOCH_STROKES + 2], + "the epoch counter reset; the lifetime counter kept the clear marker \ + it minted and the new stroke" ); let res = send( &app, diff --git a/tests/persistence.rs b/tests/persistence.rs index 0072bae..db0f177 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -2079,8 +2079,9 @@ async fn boards_and_their_strokes_survive_remigration() { .unwrap(); assert_eq!( result.take::>>(0).unwrap()[0], - vec![1, 3, 1], - "epoch counter, lifetime counter and the creator's board_count" + vec![1, 4, 1], + "epoch counter, lifetime counter (three strokes and the clear marker \ + they paid for) and the creator's board_count" ); // And the board is still writable after the boot — the counters that came diff --git a/tests/regress_caps.rs b/tests/regress_caps.rs new file mode 100644 index 0000000..8dff9fe --- /dev/null +++ b/tests/regress_caps.rs @@ -0,0 +1,607 @@ +//! Regressions for the counter/cap defects found in the 2026-08-02 sweep: +//! settings retirement rollback, the exam-kind gate on grading, snapshotted +//! caps, and the whiteboard clear marker. +//! +//! Everything here is deterministic. Where a defect only bites a true race, the +//! *reachable half* is driven instead — the corrupt state the race leaves +//! behind is written straight into the store, and the assertion is on what the +//! store holds afterwards. The in-memory engine forges wins under concurrency +//! (src/domain/cap.rs), so no test below asks it who won. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, send}; +use hezarfen_backend::domain::board::BoardId; +use hezarfen_backend::domain::board_stroke::BoardStroke; +use hezarfen_backend::domain::user::UserId; +use serde_json::json; + +/// The default kinds, minus one — the body a manager sends to drop `midterm`. +fn kinds_without_midterm() -> serde_json::Value { + json!({"exam_kinds": [{"name": "final", "weight": 3}, {"name": "oral", "weight": 1}]}) +} + +/// Grading is gated twice: by the school's list and by the kind's reference +/// counter. Only the counter used to be consulted, so *any* disagreement +/// between the two records reopened grading under a kind nobody offers — which +/// is exactly what a settings PATCH whose save lost the row's compare-and-set +/// used to leave behind (it un-retired the winner's kind). The list is the +/// school's own answer, so it refuses on its own. +#[tokio::test] +async fn a_kind_off_the_schools_list_cannot_be_graded_even_with_a_live_counter() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let manager = login_as(&app, &db, "mudur", "manager").await; + let student = login(&app, "ogrenci").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Matematik").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await; + + // The kind leaves the list — legal, nothing is graded under it yet. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(kinds_without_midterm()), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The corrupt half a lost settings race used to leave: the name is off the + // list, but its counter says "in service". + db.query("UPSERT kind_ref:midterm SET retired = false") + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "user_id": student_id, "mark": 80 })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .unwrap() + .contains("removed from the school's settings"), + "{}", + res.body + ); + + // And nothing landed: no mark, and the exam's result counter never moved. + let res = send( + &app, + "GET", + &format!("/exams/{exam}/results"), + Some(&teacher), + None, + ) + .await; + assert_eq!(common::total(&res.body), 0); +} + +/// Putting the kind back in the list makes the very same grade land — the gate +/// is the list, not a one-way door. +#[tokio::test] +async fn re_adding_the_kind_lets_the_grade_land() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let manager = login_as(&app, &db, "mudur", "manager").await; + let student = login(&app, "ogrenci").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Matematik").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await; + let grade = json!({ "user_id": student_id, "mark": 80 }); + + send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(kinds_without_midterm()), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(grade.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({"exam_kinds": [ + {"name": "midterm", "weight": 2}, + {"name": "final", "weight": 3}, + {"name": "oral", "weight": 1}, + ]})), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(grade), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + +/// The chatbot cap lives on the *settings singleton*, not on the row the seat +/// is taken on, so the claim sub-queries it inside its own conditional write. +/// A cap read at the wrong place answers one of two ways — always the built-in +/// default (the school's edit ignored) or always zero (nobody may ever start a +/// thread) — and this pins it against both. +#[tokio::test] +async fn the_chatbot_cap_is_the_one_on_the_settings_row() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mudur", "manager").await; + let user = login(&app, "ali").await; + + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "max_chatbot_threads": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // One thread fits the school's cap of 1... + let res = start_thread(&app, &user).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + // ...the second does not. (Under the built-in default of 50 it would.) + let res = start_thread(&app, &user).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // Raising the cap re-opens it, which no always-zero read could do. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "max_chatbot_threads": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = start_thread(&app, &user).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); +} + +/// Open one chatbot thread as `cookie`. +async fn start_thread(app: &axum::Router, cookie: &str) -> common::Res { + send( + app, + "POST", + "/chatbot/threads", + Some(cookie), + Some(json!({ "title": "Soru" })), + ) + .await +} + +/// The registration cap is read off `audience.capacity` on the event row as the +/// seat is taken, not bound as a number the handler read first. A mis-aimed +/// live read is an *unlimited* list (the column reads `NONE`), so the refusal +/// below is what proves the expression lands on the real column. +#[tokio::test] +async fn a_registration_list_is_capped_by_the_column_on_its_own_row() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let first = login(&app, "ali").await; + let second = login(&app, "veli").await; + let first_id = me_id(&app, &first).await; + let second_id = me_id(&app, &second).await; + + let res = send( + &app, + "POST", + "/events", + Some(&teacher), + Some(json!({ + "title": "Gezi", + "audience": { "kind": "registration", "capacity": 1 }, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let event = id_of(&res.body); + + let res = seat(&app, &teacher, &event, &first_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = seat(&app, &teacher, &event, &second_id).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // The refusal wrote nothing: one seat, one row. + let res = send( + &app, + "GET", + &format!("/events/{event}/roster"), + Some(&teacher), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "{}", res.body); +} + +/// Put `user` on `event`'s signup list as `cookie`. +async fn seat(app: &axum::Router, cookie: &str, event: &str, user: &str) -> common::Res { + send( + app, + "POST", + &format!("/events/{event}/register"), + Some(cookie), + Some(json!({ "user_id": user })), + ) + .await +} + +/// A whiteboard clear mints a real `board_stroke` row (the epoch marker) and +/// claims neither counter, so a clear of an already-blank canvas was a free row +/// — pressed in a loop, an unbounded table behind a cap that only ever counted +/// strokes *drawn*. Nothing to clear is now a refusal, which pays for every +/// marker with at least one stroke it closes. +#[tokio::test] +async fn a_blank_canvas_cannot_be_cleared_for_a_free_row() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let res = send( + &app, + "POST", + "/boards", + Some(&ali), + Some(json!({ "title": "Geometri", "participants": [] })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let board = id_of(&res.body); + // A board nobody has drawn on has nothing to clear. + let res = clear(&app, &ali, &board).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(rows(&db, &board).await, 0, "the refusal minted no marker"); + + // One mark pays for one marker... + BoardStroke::append( + &BoardId::from_key(&board), + &UserId::from_key(&ali_id), + "{\"p\":[1,2]}", + 0, + &db, + ) + .await + .expect("append"); + let res = clear(&app, &ali, &board).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker"); + + // ...and the blank canvas it leaves buys no more. + let res = clear(&app, &ali, &board).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(rows(&db, &board).await, 2); + assert_eq!( + stored_epoch(&db, &board).await, + 1, + "a refused clear must not move the epoch either" + ); +} + +/// End the board's current epoch as `cookie`. +async fn clear(app: &axum::Router, cookie: &str, board: &str) -> common::Res { + send( + app, + "POST", + &format!("/boards/{board}/clear"), + Some(cookie), + None, + ) + .await +} + +/// Rows on `board_stroke` for one board, markers included. +async fn rows(db: &hezarfen_backend::database::Database, board: &str) -> usize { + let mut result = db + .query("SELECT VALUE id FROM board_stroke WHERE board = $b") + .bind(("b", BoardId::from_key(board).record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .len() +} + +/// The board's stored epoch — the clear's other half. +async fn stored_epoch(db: &hezarfen_backend::database::Database, board: &str) -> i64 { + let mut result = db + .query("SELECT VALUE epoch FROM $b") + .bind(("b", BoardId::from_key(board).record())) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap()[0] +} + +/// The clear marker is a row on the table, so the lifetime counter has to +/// count it. Charging only the strokes made `total_stroke_count` under-count +/// the rows it is supposed to bound by one per clear — `MAX_BOARD_STROKES` +/// stopped meaning "rows on this board". The counter is asserted against the +/// rows the store actually holds, which is the invariant, not a number. +#[tokio::test] +async fn a_clear_marker_is_charged_to_the_lifetime_counter() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let res = send( + &app, + "POST", + "/boards", + Some(&ali), + Some(json!({ "title": "Geometri", "participants": [] })), + ) + .await; + let board = id_of(&res.body); + for _ in 0..2 { + BoardStroke::append( + &BoardId::from_key(&board), + &UserId::from_key(&ali_id), + "{\"p\":[1,2]}", + 0, + &db, + ) + .await + .expect("append"); + } + let res = clear(&app, &ali, &board).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // Two strokes plus the marker that closed them: three rows, and the + // lifetime counter says three. The epoch counter reset, as always. + assert_eq!(rows(&db, &board).await, 3); + assert_eq!(counters(&db, &board).await, (0, 3)); + + // The next epoch keeps counting from there — a marker is never re-counted + // and never uncounted. + BoardStroke::append( + &BoardId::from_key(&board), + &UserId::from_key(&ali_id), + "{\"p\":[3,4]}", + 1, + &db, + ) + .await + .expect("append"); + clear(&app, &ali, &board).await; + assert_eq!(rows(&db, &board).await, 5); + assert_eq!(counters(&db, &board).await, (0, 5)); +} + +/// `(epoch_stroke_count, total_stroke_count)` as the store holds them. +async fn counters(db: &hezarfen_backend::database::Database, board: &str) -> (i64, i64) { + let mut result = db + .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM $b") + .bind(("b", BoardId::from_key(board).record())) + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + (rows[0][0], rows[0][1]) +} + +/// A menu's record id is `_` and that id is a URL path segment, so +/// a slot named `a/b` is a slot no menu can ever be published under. The menu +/// side refuses those characters; the settings side used to accept them, which +/// let a school define a slot the canteen could never use — a dead entry only +/// another settings PATCH could clear. +#[tokio::test] +async fn a_slot_name_that_no_menu_id_could_carry_is_refused_by_settings() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mudur", "manager").await; + for bad in ["a/b", "a\\b", "a?b", "a#b", "a%b"] { + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({"meal_slots": [{"name": bad}]})), + ) + .await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "slot {bad} was accepted: {}", + res.body + ); + } + // The legal name still lands, and the refusals left the list alone. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({"meal_slots": [{"name": "öğle yemeği"}]})), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["meal_slots"][0]["name"], "öğle yemeği"); + + // Stale data: a row written before this rule keeps its name, and must not + // wedge an edit that never touches the meal slots. The carried-over list + // goes back into the row as it stands (`MealSlotDef::try_new` runs on the + // *request's* slots only), so an unrelated PATCH still lands. + db.query("UPDATE settings:school SET meal_slots = [{ name: 'a/b', serving_minute: NONE }]") + .await + .unwrap() + .check() + .unwrap(); + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({"max_file_bytes": 1048576})), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["max_file_bytes"], 1048576); + assert_eq!( + res.body["meal_slots"][0]["name"], "a/b", + "the stale slot rides through untouched" + ); +} + +/// A board an older binary cleared carries a lifetime counter short by one row +/// per past clear, because the marker only started paying it on 2026-08-02 — +/// and `MAX_BOARD_STROKES` bounds *rows*, so an under-counted board can outgrow +/// the table cap it is supposed to obey. Boot recomputes the counter from the +/// rows themselves, which is what the counter means. +#[tokio::test] +async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let res = send( + &app, + "POST", + "/boards", + Some(&ali), + Some(json!({ "title": "Geometri", "participants": [] })), + ) + .await; + let board = id_of(&res.body); + BoardStroke::append( + &BoardId::from_key(&board), + &UserId::from_key(&ali_id), + "{\"p\":[1,2]}", + 0, + &db, + ) + .await + .expect("append"); + clear(&app, &ali, &board).await; + assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker"); + + // Age the row to what the previous binary left behind: the marker charged + // nothing, so the counter counts the stroke alone. + db.query("UPDATE $b SET total_stroke_count = 1") + .bind(("b", BoardId::from_key(&board).record())) + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(counters(&db, &board).await, (0, 1)); + + hezarfen_backend::database::migrate(&db) + .await + .expect("re-migration"); + assert_eq!( + counters(&db, &board).await, + (0, 2), + "the counter is the board's row count again" + ); + + // Idempotent: it recomputes the same number, it does not add one per boot — + // the failure mode a counter repair actually has. + for _ in 0..2 { + hezarfen_backend::database::migrate(&db) + .await + .expect("re-migration"); + } + assert_eq!(counters(&db, &board).await, (0, 2)); + assert_eq!(rows(&db, &board).await, 2, "and it wrote no rows"); +} + +/// A slot name the school *already stores* must stay submittable. +/// +/// The URL-safety rule on slot names is younger than the lists it validates, +/// and `PATCH /settings` re-validates the whole submitted list — so a school +/// holding a pre-rule name was locked out of `meal_slots` entirely: re-sending +/// the name 400s, and dropping it 409s the moment a menu references it. The +/// stored name is grandfathered; a new one with the same characters is not. +#[tokio::test] +async fn a_stale_slot_name_no_longer_wedges_the_rest_of_the_list() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "slot_wedge_admin", "admin").await; + + // A legal edit first: `UPDATE` on the singleton is a no-op until the row + // exists, and an absent row reads as the built-in defaults. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{"name": "lunch"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The list as a database written before the rule holds it, plus the menu + // reference that makes dropping the name a 409. + db.query( + "UPDATE settings:school SET meal_slots = \ + [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]; + UPSERT slot_ref:`a/b` SET count = 1;", + ) + .await + .unwrap() + .check() + .unwrap(); + + // Editing the *rest* of the list works, stale name carried along. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [ + {"name": "a/b"}, {"name": "lunch"}, {"name": "kahvaltı"}, + ] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Dropping it is still the 409 the published menu earns it... + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{"name": "lunch"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // ...and a name nobody stored is still refused outright. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{"name": "a/b"}, {"name": "lunch"}, {"name": "c/d"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs new file mode 100644 index 0000000..e7a555b --- /dev/null +++ b/tests/regress_classes.rs @@ -0,0 +1,774 @@ +//! Regressions for the class (şube) layer, its enrollment side, and the sweep a +//! role change runs. Every test here pins a defect that shipped: a link left +//! pointing at a deleted course, the refusal that misnamed it, a hand enroll a +//! class could still undo, and the two-transaction role sweep. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, create_course, login_as, me_id, send}; +use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::class_course::ClassCourse; +use hezarfen_backend::domain::class_group::{ClassGroup, ClassName}; +use hezarfen_backend::domain::class_member::ClassMember; +use hezarfen_backend::domain::course::CourseId; +use hezarfen_backend::domain::user::UserId; +use hezarfen_backend::error::AppError; +use serde_json::json; + +/// One counter, re-read out of the store — never off a response body. +async fn counter(sql: &str, db: &Database) -> i64 { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) +} + +/// How many rows `sql` selects ids for. +async fn rows(sql: &str, db: &Database) -> i64 { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result + .take::>(0) + .unwrap() + .len() as i64 +} + +/// Delete a course row the way a *concurrent* `DELETE /courses/{id}` racing an +/// attach leaves the store: the row goes, the `class_course` link it never saw +/// stays. The real cascade sweeps those links, so this is the only way to reach +/// the state from a test — and the state the pump's in-transaction claim exists +/// to make unreachable in the first place. +async fn wipe_course_row(course: &str, db: &Database) { + db.query("DELETE type::record('course', $key)") + .bind(("key", course.to_string())) + .await + .unwrap() + .check() + .unwrap(); +} + +/// B1(a). A class with *zero* members makes the pump's pair loop empty, so the +/// attach transaction touched no row a concurrent course delete wrote and +/// SurrealDB's write-skew let both commit — a `class_course` row pointing at a +/// course that does not exist. The pivot claim is what makes that impossible. +#[tokio::test] +async fn an_attach_onto_a_deleted_course_writes_no_link() { + let (_app, db) = app_and_db().await; + let manager = UserId::from_key("manager"); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + &db, + ) + .await + .unwrap(); + // A course id nothing ever created: the same row a delete that won the race + // leaves behind. + let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + + let refused = ClassCourse::attach(class.get_id(), &ghost, &manager, &db).await; + assert!( + refused.is_err(), + "attaching a course that is gone must be refused: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "no link row may point at a course that does not exist" + ); + assert_eq!( + counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await, + 0, + "…and the class must not count one either, or it is undeletable forever" + ); +} + +/// B1(b). The other half: a link that *did* land that way must still be +/// removable. `DELETE /classes/{c}/courses/{id}` read the course before the +/// link, so a deleted course made the route answer 404 forever — and the class +/// 409 forever, over an attachment nothing could sweep. +#[tokio::test] +async fn a_stale_link_detaches_and_frees_its_class() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let course = create_course(&app, &manager, "algebra").await; + let class = { + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + res.body["id"].as_str().unwrap().to_string() + }; + let attached = send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&manager), + Some(json!({ "course_id": course })), + ) + .await; + assert_eq!(attached.status, StatusCode::CREATED); + wipe_course_row(&course, &db).await; + + let detached = send( + &app, + "DELETE", + &format!("/classes/{class}/courses/{course}"), + Some(&manager), + None, + ) + .await; + assert_eq!( + detached.status, + StatusCode::NO_CONTENT, + "a link whose course is gone must still detach: {:?}", + detached.body + ); + let deleted = send( + &app, + "DELETE", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!( + deleted.status, + StatusCode::NO_CONTENT, + "…and the class it blocked must be deletable again: {:?}", + deleted.body + ); + + // A course that was never attached is still a 404 — the guard that turns + // "sweep the stale link" into "delete anything" is the link row, not the + // course row. + let again = send( + &app, + "DELETE", + &format!("/classes/{class}/courses/{course}"), + Some(&manager), + None, + ) + .await; + assert_eq!(again.status, StatusCode::NOT_FOUND); +} + +/// B2. Every member add into a class holding such a link answered +/// `409 " is full"` — a course that does not exist, so no capacity +/// anyone could raise would ever let a student in. The two causes come out of +/// one seat claim matching nothing, and they must not read as one answer. +#[tokio::test] +async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let student = login_as(&app, &db, "student", "student").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &manager, "algebra").await; + let class = { + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A" })), + ) + .await; + res.body["id"].as_str().unwrap().to_string() + }; + send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&manager), + Some(json!({ "course_id": course })), + ) + .await; + wipe_course_row(&course, &db).await; + + let refused = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(refused.status, StatusCode::CONFLICT); + let message = refused.body["error"].as_str().unwrap_or_default(); + assert!( + message.contains("no longer exists") && message.contains(&course), + "the refusal must name the vanished course, not a capacity: {message}" + ); + assert!( + !message.contains("full"), + "a course that does not exist is not a full one: {message}" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_member", &db).await, + 0, + "a refused add writes nothing" + ); +} + +/// B3. A hand enroll over a row a class pumped must take the row off the class, +/// or the next sweep unenrolls a student an operator placed on purpose — +/// the mirror of the manual unenroll that a class may never undo. +#[tokio::test] +async fn a_hand_enroll_takes_the_row_off_the_class() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let student = login_as(&app, &db, "student", "student").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &manager, "algebra").await; + let class = { + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A" })), + ) + .await; + res.body["id"].as_str().unwrap().to_string() + }; + send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&manager), + Some(json!({ "course_id": course })), + ) + .await; + let added = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(added.status, StatusCode::CREATED); + + // The pumped row names its class, and says so on the wire — a client that + // cannot see `source` cannot tell which of its roster rows is sweepable. + let roster = send( + &app, + "GET", + &format!("/courses/{course}/enrollments"), + Some(&manager), + None, + ) + .await; + assert_eq!(roster.body["items"][0]["source"], json!(class)); + + let by_hand = send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(by_hand.status, StatusCode::OK); + assert_eq!( + by_hand.body["source"], + json!(null), + "a hand enroll must take the row off the class" + ); + assert_eq!( + rows("SELECT VALUE id FROM enrollment WHERE source != NONE", &db).await, + 0, + "…in the stored row, not just the response" + ); + + // Which is the whole point: the class letting the student go now leaves the + // hand-placed row standing, with its seat still counted. + let removed = send( + &app, + "DELETE", + &format!("/classes/{class}/members/{student_id}"), + Some(&manager), + None, + ) + .await; + assert_eq!(removed.status, StatusCode::NO_CONTENT); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 1, + "the class may not unenroll a student an operator enrolled by hand" + ); + assert_eq!( + counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + 1, + "…and the seat it never paid for may not be released" + ); +} + +/// B5. The role sweep is one transaction over both tables. Pinned end to end: +/// a promotion leaves no membership, no enrollment and no counter behind, so +/// the class is deletable and no row is left tagged with it. (The half-apply +/// itself needs a crash between two statements, which no test can schedule — +/// this pins the state the fold must always land in.) +#[tokio::test] +async fn a_role_change_sweeps_memberships_and_enrollments_together() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "patron", "admin").await; + let manager = login_as(&app, &db, "manager", "manager").await; + let student = login_as(&app, &db, "student", "student").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &manager, "algebra").await; + let class = { + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A" })), + ) + .await; + res.body["id"].as_str().unwrap().to_string() + }; + send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&manager), + Some(json!({ "course_id": course })), + ) + .await; + send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 1); + + let promoted = send( + &app, + "PATCH", + &format!("/users/{student_id}/role"), + Some(&admin), + Some(json!({ "role": "teacher" })), + ) + .await; + assert_eq!(promoted.status, StatusCode::OK); + + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 0, + "a non-student holds no roster row, whoever wrote it" + ); + assert_eq!( + counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + 0, + "the seat comes back exactly once" + ); + assert_eq!( + counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + 0 + ); + // Nothing is left tagged with the class, so letting it go strands nothing. + let detached = send( + &app, + "DELETE", + &format!("/classes/{class}/courses/{course}"), + Some(&manager), + None, + ) + .await; + assert_eq!(detached.status, StatusCode::NO_CONTENT); + let deleted = send( + &app, + "DELETE", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!(deleted.status, StatusCode::NO_CONTENT); +} + +/// B4. The roster cap is claimed off the course row's *own* `capacity` column +/// now, not off an integer read moments earlier — so a capacity PATCH cannot be +/// outrun by an enroll that snapshotted the old number. The over-admit that +/// bug allowed needs two writers interleaved inside one request, which the +/// in-memory engine cannot be made to schedule; what is pinned here is that the +/// converted statement still refuses, still admits, and still tells a full +/// course from a deleted one. +#[tokio::test] +async fn the_roster_cap_is_claimed_off_the_live_capacity_column() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let first = login_as(&app, &db, "sena", "student").await; + let second = login_as(&app, &db, "suat", "student").await; + let first_id = me_id(&app, &first).await; + let second_id = me_id(&app, &second).await; + let course = { + let res = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "algebra", "capacity": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + res.body["id"].as_str().unwrap().to_string() + }; + let enroll = |who: String| { + let app = app.clone(); + let manager = manager.clone(); + let course = course.clone(); + async move { + send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&manager), + Some(json!({ "user_id": who })), + ) + .await + } + }; + + assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK); + assert_eq!( + enroll(second_id.clone()).await.status, + StatusCode::CONFLICT, + "the cap must bite at one" + ); + // Re-enrolling the student who is already in is answered off their row, not + // off the (full) counter, and costs no seat. + assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK); + assert_eq!( + counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + 1 + ); + + // Raise the cap and the very next claim sees the new number, because it + // reads the column rather than a copy of it. + let raised = send( + &app, + "PATCH", + &format!("/courses/{course}"), + Some(&manager), + Some(json!({ "capacity": 2 })), + ) + .await; + assert_eq!(raised.status, StatusCode::OK); + assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK); + assert_eq!( + counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + 2 + ); + + // And a course deleted out from under the claim is a 404, not a 409: the + // conditional write matches nothing either way, and only that path pays for + // the read that tells them apart. + wipe_course_row(&course, &db).await; + db.query("DELETE enrollment") + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND); +} + +/// D1. Both link tables key on the *pair* (`_`), so the +/// documented "newest first" was implemented as `ORDER BY id DESC` — which +/// sorts the roster by the member's account ULID, an order that has nothing to +/// do with when anyone was added. The three students here are added in an order +/// their ids do not reproduce, so id-ordering and stamp-ordering disagree. +#[tokio::test] +async fn a_roster_is_ordered_by_when_a_student_was_added() { + let (_app, db) = app_and_db().await; + let manager = UserId::from_key("manager"); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + + // Keys chosen so `id DESC` (c, b, a) is not the reverse of the insertion + // order (a, c, b): only a real stamp can tell the two apart. The waits are + // what keep the millisecond stamps distinct — a tie falls back to the id, + // which is the very order under test. + let added = ["a", "c", "b"]; + for key in added { + ClassMember::add(&class, &UserId::from_key(key), &manager, &db) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + + let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db) + .await + .unwrap(); + let order: Vec<&str> = roster + .iter() + .map(|member| member.get_user().key()) + .collect(); + assert_eq!( + order, + vec!["b", "c", "a"], + "the roster must come back newest-added first, not sorted by account id" + ); + + // A row written before the stamp column existed carries no `added_at` at + // all — the state a real volume is in. It is of unknown age, and NONE + // sorting last under DESC is what makes that the oldest, rather than an + // invented number putting it anywhere else. + db.query("UPDATE class_member SET added_at = NONE WHERE user = $usr") + .bind(("usr", UserId::from_key("c").record())) + .await + .unwrap() + .check() + .unwrap(); + let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db) + .await + .unwrap(); + assert_eq!( + roster + .iter() + .map(|member| member.get_user().key()) + .collect::>(), + vec!["b", "a", "c"], + "a stamp-less row must sort oldest, not first" + ); +} + +/// D1, the other axis: the course list had the same defect, ordered by the +/// *course's* ULID. +#[tokio::test] +async fn a_class_course_list_is_ordered_by_when_it_was_attached() { + let (app, db) = app_and_db().await; + let manager_cookie = login_as(&app, &db, "manager", "manager").await; + let manager = UserId::from_key(&me_id(&app, &manager_cookie).await); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + + // Courses are ULID-keyed, so their ids rise with creation; attaching them + // back-to-front makes id order and attach order disagree. + let mut courses = Vec::new(); + for title in ["first", "second", "third"] { + courses.push(CourseId::from_key( + &create_course(&app, &manager_cookie, title).await, + )); + } + for course in courses.iter().rev() { + ClassCourse::attach(&class, course, &manager, &db) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + + let (attached, _) = ClassCourse::list_for_class(&class, None, 0, &db) + .await + .unwrap(); + let order: Vec<&str> = attached + .iter() + .map(|link| link.get_course().key()) + .collect(); + assert_eq!( + order, + courses.iter().map(|c| c.key()).collect::>(), + "the list must come back newest-attached first, not sorted by course id" + ); +} + +/// D2. Attaching a course writes one enrollment per member and adding a member +/// writes one per attached course, both in a *single* transaction — with no +/// class-size ceiling anywhere, that transaction was unbounded. The counter's +/// claim now carries the bound, so the refusal happens before the loop runs. +/// +/// The counter is seeded rather than filled by 200 real adds: it *is* the gate +/// the claim reads, and the boundary is what is under test, not the 199 adds +/// that lead up to it. +#[tokio::test] +async fn a_class_refuses_the_member_past_its_ceiling() { + let (_app, db) = app_and_db().await; + let manager = UserId::from_key("manager"); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + db.query("UPDATE $class SET class_member_count = $at") + .bind(("class", class.record())) + .bind(("at", MAX_CLASS_MEMBERS - 1)) + .await + .unwrap() + .check() + .unwrap(); + + ClassMember::add(&class, &UserId::from_key("last"), &manager, &db) + .await + .expect("the place under the ceiling is still free"); + let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref message)) + if message.contains(&MAX_CLASS_MEMBERS.to_string())), + "a full class is a 409 naming its ceiling, never a 404: {refused:?}" + ); + assert_eq!( + counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + MAX_CLASS_MEMBERS, + "a refused add may not tick the counter past the cap" + ); + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 1); + + // And the refusal a *deleted* class earns must stay a 404: both come out of + // the same counter claim matching nothing, and only one of them is a + // ceiling anybody can make room under. + db.query("DELETE $class") + .bind(("class", class.record())) + .await + .unwrap() + .check() + .unwrap(); + let gone = ClassMember::add(&class, &UserId::from_key("ghost"), &manager, &db).await; + assert!( + matches!(gone, Err(AppError::NotFound)), + "a class that is gone is a 404: {gone:?}" + ); +} + +/// The ceilings bind the axis being *added*, and the transaction they bound is +/// the length of the *other* one — so a class that already stands above a +/// ceiling walked straight past both. The class layer shipped before either +/// number existed, so a real volume can hold a 300-strong class, and attaching +/// one course to it wrote 300 enrollments in a single transaction: exactly the +/// unbounded write `MAX_CLASS_MEMBERS` was added to make impossible. The attach +/// now refuses on the other axis too, and says which one. +/// +/// The counter is seeded rather than filled by 201 real adds: it *is* what the +/// pump reads, and it is what a stale class carries. +#[tokio::test] +async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { + let (app, db) = app_and_db().await; + let cookie = login_as(&app, &db, "manager", "manager").await; + let manager = UserId::from_key(&me_id(&app, &cookie).await); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await); + db.query("UPDATE $class SET class_member_count = $over") + .bind(("class", class.record())) + .bind(("over", MAX_CLASS_MEMBERS + 1)) + .await + .unwrap() + .check() + .unwrap(); + + let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref message)) + if message.contains(&MAX_CLASS_MEMBERS.to_string())), + "the refusal must name the axis that is over, not the one with room: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "a refused attach may not leave the link behind" + ); + assert_eq!( + counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await, + 0, + "…nor tick the axis it was refused on" + ); + + // Back under the ceiling, the very same attach goes through: the refusal is + // the standing count, not the class. + db.query("UPDATE $class SET class_member_count = $at") + .bind(("class", class.record())) + .bind(("at", MAX_CLASS_MEMBERS)) + .await + .unwrap() + .check() + .unwrap(); + ClassCourse::attach(&class, &algebra, &manager, &db) + .await + .expect("a class exactly at the ceiling is still a bounded transaction"); +} + +/// The mirror: a class carrying more courses than `MAX_CLASS_COURSES` takes no +/// new member, because adding one enrolls them into every attached course. +#[tokio::test] +async fn a_class_over_the_course_ceiling_takes_no_member() { + let (_app, db) = app_and_db().await; + let manager = UserId::from_key("manager"); + let class = ClassGroup::create( + &manager, + ClassName::try_new("9-B").unwrap(), + None, + None, + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + db.query("UPDATE $class SET class_course_count = $over") + .bind(("class", class.record())) + .bind(("over", MAX_CLASS_COURSES + 1)) + .await + .unwrap() + .check() + .unwrap(); + + let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await; + assert!( + matches!(refused, Err(AppError::ConflictOwned(ref message)) + if message.contains(&MAX_CLASS_COURSES.to_string())), + "the refusal must name the courses, not the roster: {refused:?}" + ); + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!( + counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + 0 + ); +} diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs new file mode 100644 index 0000000..912b870 --- /dev/null +++ b/tests/regress_meals.rs @@ -0,0 +1,673 @@ +//! Regressions for the food program's money and its menus. Each test here +//! stands for one defect that shipped: a seat that could not be replayed, a +//! seat nobody could cancel, a debt nobody could settle, a mark that outlived +//! its menu, a dish edit that outlived its own. +//! +//! Router-level, same shape as `integration.rs`, plus a few direct domain calls +//! where the defect sits *below* a handler's read (a mark landing after the +//! menu is gone is not reachable through the route, which reads it first). + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, id_of, login, login_as, me_id, send, set_role}; +use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; +use hezarfen_backend::domain::menu::MenuId; +use hezarfen_backend::domain::user::UserId; +use serde_json::json; + +/// Publish a menu for `date`, uncapped unless told otherwise. +async fn publish(app: &axum::Router, mgr: &str, date: &str) -> String { + let res = send( + app, + "POST", + "/meals/menus", + Some(mgr), + Some(json!({ "date": date, "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + id_of(&res.body) +} + +async fn add_dish(app: &axum::Router, mgr: &str, menu: &str, price: i64) -> String { + let res = send( + app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(mgr), + Some(json!({ "name": "çorba", "price_minor": price })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + id_of(&res.body) +} + +/// A repeat `POST` of a seat the student already holds must replay that seat, +/// whatever the menu costs *now*. Pricing the menu before the already-booked +/// short circuit made it a `400` ("amount_minor must be between…") the moment +/// the dishes summed past the chargeable maximum — refusing to hand back a seat +/// over a price it was never going to be billed. +#[tokio::test] +async fn a_repeat_booking_replays_the_held_seat_however_dear_the_menu_gets() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "dear_mgr", "manager").await; + let ali = login(&app, "dear_ali").await; + let menu = publish(&app, &mgr, "2026-09-14").await; + add_dish(&app, &mgr, &menu, 1_000).await; + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + // The menu is re-dressed until a seat on it could not be billed at all + // (`MAX_LEDGER_AMOUNT_MINOR` is 10 000 000 minor units). + for _ in 0..11 { + add_dish(&app, &mgr, &menu, 1_000_000).await; + } + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(id_of(&res.body), booking, "the same seat, replayed"); + assert_eq!(res.body["status"], "booked"); + + // …and the replay bills nothing new: the seat still owes its own price. + let res = send( + &app, + "GET", + &format!("/meals/balance/{}", me_id(&app, &ali).await), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], -1_000); + + // A student who has no seat yet is still refused outright, rather than + // being handed one nothing can charge for. + let veli = login(&app, "dear_veli").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&veli), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} + +/// A seat outlives the role that took it. Only the student or their parent may +/// cancel, so a promoted student's live seat used to be uncancellable: the menu +/// refused its own delete forever and the charge could never be reversed, since +/// cancelling is the only route that appends a reversal. Manager+ may cancel +/// any seat, and nothing sweeps bookings on a role change — moving money is a +/// decision, never a side effect. +#[tokio::test] +async fn a_manager_can_cancel_the_seat_of_someone_who_is_no_longer_a_student() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "promo_mgr", "manager").await; + let ali = login(&app, "promo_ali").await; + let ali_id = me_id(&app, &ali).await; + let menu = publish(&app, &mgr, "2026-09-15").await; + add_dish(&app, &mgr, &menu, 4_500).await; + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + // Ali becomes staff. The seat is still held, still counted, still charged. + set_role(&db, "promo_ali", "teacher").await; + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "a teacher does not book meals, so they do not cancel their own either" + ); + + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled"); + + // The seat is genuinely back — the menu may be unpublished — and so is the + // money: the reversal landed with the flip. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 0); + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // A classmate still cannot cancel someone else's seat. + let menu = publish(&app, &mgr, "2026-09-16").await; + let veli = login(&app, "promo_veli").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&veli), + Some(json!({})), + ) + .await; + let seat = id_of(&res.body); + let can = login(&app, "promo_can").await; + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{seat}"), + Some(&can), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} + +/// A debt survives its debtor's role change, so settling it has to. The credit +/// route took students only, which made such a debt permanently unpayable — +/// there is no other route that appends a credit. A target with no ledger +/// history at all is still refused, so a typo'd staff id cannot take money. +#[tokio::test] +async fn a_credit_settles_a_debt_that_outlived_the_students_role() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "credit_admin", "admin").await; + let ali = login(&app, "credit_ali").await; + let ali_id = me_id(&app, &ali).await; + let menu = publish(&app, &admin, "2026-09-17").await; + add_dish(&app, &admin, &menu, 4_500).await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + set_role(&db, "credit_ali", "teacher").await; + let res = send( + &app, + "POST", + "/meals/credits", + Some(&admin), + Some(json!({ "student_id": ali_id, "amount_minor": 4_500 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 0, "the debt is settled"); + + // Staff who never ate here carry no balance, so the typo still bites. + let clean = login_as(&app, &db, "credit_clean", "teacher").await; + let clean_id = me_id(&app, &clean).await; + let res = send( + &app, + "POST", + "/meals/credits", + Some(&admin), + Some(json!({ "student_id": clean_id, "amount_minor": 4_500 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} + +/// A mark must not create a row for a menu that is gone. The handler reads the +/// menu first, so this is driven below it — exactly the interleaving a mark in +/// flight while `DELETE /meals/menus/{id}` commits produces. The stake is not +/// tidiness: menu ids are deterministic on (date, slot), so an orphan mark comes +/// back as a mark on the *next* menu published for that meal. +#[tokio::test] +async fn a_mark_for_a_menu_that_is_gone_writes_no_row() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "mark_mgr", "manager").await; + let ali = login(&app, "mark_ali").await; + let ali_id = UserId::from_key(&me_id(&app, &ali).await); + let mgr_id = UserId::from_key(&me_id(&app, &mgr).await); + let menu = MenuId::from_key(&publish(&app, &mgr, "2026-09-18").await); + + // The menu goes while the mark is on its way down. + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{}", menu.key()), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + let marked = MealAttendance::mark( + &menu, + &ali_id, + MealAttendanceStatus::try_new("served").unwrap(), + &mgr_id, + &db, + ) + .await + .expect("the mark is refused, not an error"); + assert!(marked.is_none(), "no menu, no mark"); + + // Republishing that very day and slot mints the same id — and must not + // inherit a mark for a meal nobody attended. + let again = publish(&app, &mgr, "2026-09-18").await; + assert_eq!(again, menu.key(), "the id is deterministic on date+slot"); + let res = send( + &app, + "GET", + &format!("/meals/menus/{again}/attendance"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 0, "{}", res.body); + + // The live menu still takes marks, and re-marking corrects in place. + for status in ["served", "missed"] { + let res = send( + &app, + "POST", + &format!("/meals/menus/{again}/attendance"), + Some(&mgr), + Some(json!({ "student_id": ali_id.key(), "status": status })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], status); + } + let res = send( + &app, + "GET", + &format!("/meals/menus/{again}/attendance"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "one row per (menu, person)"); +} + +/// A dish write is fenced by its menu's existence, because the revision bump it +/// rides on *is* that fence: both are one transaction now, so an edit can no +/// longer land on a menu that has been unpublished — which is the same window +/// that let a booking see a bumped revision with the old price. +#[tokio::test] +async fn a_dish_write_is_refused_once_its_menu_is_gone() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "orphan_mgr", "manager").await; + let menu = publish(&app, &mgr, "2026-09-19").await; + let dish = add_dish(&app, &mgr, &menu, 1_000).await; + + // The menu row alone is removed, leaving the dish exactly as a delete + // interrupted between the row and its cascade would have. + db.query("DELETE $id") + .bind(("id", MenuId::from_key(&menu).record())) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "price_minor": 9_000 })), + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + + // …and on a live menu both still work, at a fresh revision each time. + let menu = publish(&app, &mgr, "2026-09-20").await; + let dish = add_dish(&app, &mgr, &menu, 1_000).await; + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "price_minor": 9_000 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["price_minor"], 9_000); + let res = send( + &app, + "DELETE", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// Unpublishing takes the dishes with it *in the delete's own transaction*: the +/// menu id is deterministic, so a cascade that ran afterwards and was cut short +/// left the next menu for that meal serving — and pricing — the old one's food. +#[tokio::test] +async fn unpublishing_takes_the_dishes_with_the_row() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "cascade_mgr", "manager").await; + let menu = publish(&app, &mgr, "2026-09-21").await; + add_dish(&app, &mgr, &menu, 1_000).await; + send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + + let again = publish(&app, &mgr, "2026-09-21").await; + assert_eq!(again, menu, "the id is deterministic on date+slot"); + let res = send( + &app, + "GET", + &format!("/meals/menus/{again}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + res.body["dishes"].as_array().unwrap().len(), + 0, + "a republished meal starts empty" + ); + + // A seat on it is therefore free, not billed for food nobody serves. + let ali = login(&app, "cascade_ali").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{again}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/balance/{}", me_id(&app, &ali).await), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 0); +} + +/// A slot name goes verbatim into the menu's record id, and that id is a URL +/// path segment. A slot named `a/b` published a menu at an address no route +/// could ever match again — unreadable, uneditable, undeletable. +/// +/// The settings now refuse the name outright, so the only way such a slot can +/// still be on a school's list is a row written before that rule — which is +/// what is staged straight into the store here. This gate is what that row +/// runs into. +#[tokio::test] +async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "slot_admin", "admin").await; + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{"name": "a/b"}, {"name": "lunch"}] })), + ) + .await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "the settings must refuse the name themselves: {}", + res.body + ); + + // The legal half of that edit lands, which is what creates the row... + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{"name": "lunch"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // ...and the stale row is that list as a database written before the rule. + db.query( + "UPDATE settings:school SET meal_slots = \ + [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]", + ) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&admin), + Some(json!({ "date": "2026-09-22", "slot": "a/b" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + // The school's other slots are unaffected. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&admin), + Some(json!({ "date": "2026-09-22", "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); +} + +/// The cutoff exists to stop students moving the kitchen's headcount at the +/// last minute. It bound *staff* too, and that half-closed the very wedge +/// manager-cancel was widened to open: past the deadline the seat could not be +/// freed by anyone, and a menu refuses its own delete while a seat is held — +/// so the menu was undeletable and the charge unreversible, forever. Manager+ +/// now cancels through a closed cutoff; students and parents still do not. +#[tokio::test] +async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "shut_adm", "admin").await; + let mgr = login_as(&app, &db, "shut_mgr", "manager").await; + let ali = login(&app, "shut_ali").await; + let ali_id = me_id(&app, &ali).await; + // A day long past — booked while the school ran no deadline at all. + let menu = publish(&app, &mgr, "2020-01-02").await; + add_dish(&app, &mgr, &menu, 1_000).await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + // The school sets a deadline, and it closed on this menu long ago. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_cancel_cutoff_minutes": 60 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "the student is still bound by the cutoff: {}", + res.body + ); + + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + // The refund is the point: a bypass that freed the seat and kept the charge + // would only move the wedge onto the money. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 0, "{}", res.body); + + // …and with the seat back, the menu is deletable again. + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// Canteen debt is family debt, not classroom information — the same rule +/// `/payments` has always held. The two money reads shipped gated teacher+ +/// (`ensure_can_observe`), so a form teacher could read what a family owed the +/// canteen while the identical `/payments` read 403'd them. Everything else in +/// the meals block — dietary profiles, bookings, attendance — stays teacher+ on +/// purpose; only the money moved. +#[tokio::test] +async fn only_manager_reads_another_students_meal_money() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "money_admin", "admin").await; + let mgr = login_as(&app, &db, "money_mgr", "manager").await; + let teacher = login_as(&app, &db, "money_teacher", "teacher").await; + let ali = login(&app, "money_ali").await; + let ali_id = me_id(&app, &ali).await; + let mother = login_as(&app, &db, "money_mother", "parent").await; + let stranger = login_as(&app, &db, "money_stranger", "parent").await; + let res = send( + &app, + "POST", + &format!("/users/{}/students", me_id(&app, &mother).await), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + for route in [ + format!("/meals/balance/{ali_id}"), + format!("/meals/ledger/{ali_id}"), + ] { + for (who, cookie, want) in [ + ("teacher", &teacher, StatusCode::FORBIDDEN), + ("unlinked parent", &stranger, StatusCode::FORBIDDEN), + ("manager", &mgr, StatusCode::OK), + ("admin", &admin, StatusCode::OK), + ("linked parent", &mother, StatusCode::OK), + ("the student themselves", &ali, StatusCode::OK), + ] { + let res = send(&app, "GET", &route, Some(cookie), None).await; + assert_eq!(res.status, want, "{who} on {route}: {}", res.body); + } + } + + // The rest of the block did not move with the money: a teacher still reads + // the allergen list and the attendance history they need at the door. + for route in [ + format!("/meals/profiles/{ali_id}"), + format!("/meals/attendance/{ali_id}"), + ] { + let res = send(&app, "GET", &route, Some(&teacher), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "teacher on {route}: {}", + res.body + ); + } +}